code
stringlengths
2
1.05M
function OverdoneError() { var e = Error.apply(this, arguments); var _this = this; var _arguments = arguments; Object.defineProperty(this, 'message', {value: e.message}); Object.defineProperty(this, 'name', {value: 'OverdoneError'}); Object.defineProperty(this, 'stack', {get: function() {return e.stack}}); Object.keys(arguments[1] || {}).forEach(function(key) { Object.defineProperty(_this, key, { enumerable: true, get: function(){return _arguments[1][key]} }); }); return this; } OverdoneError.prototype = Error.prototype; OverdoneError.prototype.constructor = OverdoneError; module.exports = OverdoneError;
const webpack = require('webpack'); const path = require('path'); const ManifestPlugin = require('webpack-manifest-plugin'); const HardSourceWebpackPlugin = require('hard-source-webpack-plugin'); const env = process.env.NODE_ENV || 'development'; const production = env === 'production'; const development = env === 'development'; const travis = process.env.TRAVIS === 'true'; const config = { mode: env, entry: { coursemology: [ '@babel/polyfill', 'jquery', './app/index', './app/lib/moment-timezone', ], }, output: { filename: production ? '[name]-[chunkhash].js' : '[name].js', path: path.join(__dirname, '..', 'public', 'webpack'), publicPath: '/webpack/', }, resolve: { extensions: ['.js', '.jsx'], alias: { lib: path.resolve('./app/lib'), api: path.resolve('./app/api'), course: path.resolve('./app/bundles/course'), }, }, optimization: { splitChunks: { chunks: 'all', }, }, plugins: [ new webpack.IgnorePlugin(/__test__/), new webpack.HashedModuleIdsPlugin(), new ManifestPlugin({ publicPath: '/webpack/', writeToFileEmit: true }), // Do not require all locales in moment new webpack.ContextReplacementPlugin(/moment\/locale$/, /^\.\/(en-.*|zh-.*)$/), ], module: { rules: [ { test: /\.jsx?$/, use: 'babel-loader', exclude: /node_modules/, }, { test: /\.css$/, use: [ 'style-loader', 'css-loader', ], }, { test: /\.scss$/, use: [ 'style-loader', 'css-loader', 'sass-loader', ], include: [ path.resolve(__dirname, 'app/lib/styles/MaterialSummernote.scss'), path.resolve(__dirname, 'app/lib/styles/MaterialSummernoteModal.scss'), ], }, { test: /\.scss$/, use: [ 'style-loader', { loader: 'css-loader', options: { importLoaders: 1, modules: true, localIdentName: '[path]___[name]__[local]___[hash:base64:5]', }, }, 'sass-loader', ], exclude: [ /node_modules/, path.resolve(__dirname, 'app/lib/styles/MaterialSummernote.scss'), path.resolve(__dirname, 'app/lib/styles/MaterialSummernoteModal.scss'), ], }, { test: require.resolve('jquery'), use: [{ loader: 'expose-loader', options: 'jQuery', }, { loader: 'expose-loader', options: '$', }], }, { test: require.resolve('./app/lib/moment-timezone'), use: [{ loader: 'expose-loader', options: 'moment', }], }, ], }, }; if (development) { const devServerPort = 8080; config.devServer = { port: devServerPort, headers: { 'Access-Control-Allow-Origin': '*' }, }; config.output.publicPath = `//localhost:${devServerPort}/webpack/`; config.devtool = 'cheap-module-eval-source-map'; } else { console.log(`\nWebpack ${env} build for Rails...`); // eslint-disable-line no-console } // Only enable HardSourceWebpackPlugin in Travis if (travis) { config.plugins.push(new HardSourceWebpackPlugin({ cacheDirectory: path.join(__dirname, 'hard-source-cache/[confighash]'), })); } module.exports = config;
/* Copyright 2013,2014 Guy de Pourtalès Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ (function () { var module = angular.module('ngcTableDirective', ['ngc-template', 'ngSanitize', 'ngScrollable']); module.directive('ngcTable', ['$templateCache', '$sce', '$timeout', '$parse', function ($templateCache, $sce, $timeout, $parse) { /** * ngcTable Controller declaration. The format is given to be able to minify the directive. The scope is * injected. * @type {*[]} */ var controllerDecl = ['$scope', function ($scope) { /** * Registers a range declaration in the scope * @param range The new range declaration */ this.addRange = function (range) { $scope.ranges.push(range); }; }]; function compile(/*tElement, tAttrs*/) { return { pre: function preLink(scope /*, iElement, iAttrs, controller */) { /** * Utility function to create a style declaration based on the value declaration * @param attrName The name of the CSS attribute * @param valueDecl The value of the style declaration given in the directive attributes * @param index The index of the element if the value declaration is an array * @returns {string} The CSS attribute declaration */ function $$getStyleDecl(attrName, valueDecl, index) { return angular.isArray(valueDecl) ? index < valueDecl.length ? attrName + ':' + valueDecl[index] : attrName + ':' + valueDecl[valueDecl.length - 1] : angular.isDefined(valueDecl) ? attrName + ':' + valueDecl : '' } /** * Utility function to create and register new columns * @param n The number of columns to create * @param array The array in which register the newly creted columns * @param widths The widths array to apply to each columns */ function $$createColumns(n, array, widths) { if (angular.isNumber(n)) { for (var i = 0; i < n; i++) { array.push({ style: $$getStyleDecl('width', widths, i) + ';' + $$getStyleDecl('max-width', widths, i) }); } } } /** * Left row header columns definitions * @type {Array} */ scope.$$leftRowHeadersColumns = []; /** * Left fixed columns definitions * @type {Array} */ scope.$$leftFixedColumns = []; /* Create the columns based on directive parameters */ $$createColumns(angular.isNumber(scope.leftColumnNumber) ? scope.leftColumnNumber : 1, scope.$$leftFixedColumns, scope.leftColumnWidths); /** * Variable center column definitions * @type {Array} */ scope.$$variableCenterColumns = []; /* Create the columns based on directive parameters */ $$createColumns(angular.isNumber(scope.centerColumnNumber) ? scope.centerColumnNumber : 10, scope.$$variableCenterColumns, scope.centerColumnWidths); /** * Right fixed columns definitions * @type {Array} */ scope.$$rightFixedColumns = []; /* Create the columns based on directive parameters */ $$createColumns(angular.isNumber(scope.rightColumnNumber) ? scope.rightColumnNumber : 1, scope.$$rightFixedColumns, scope.rightColumnWidths); /* Headers and tools */ /** * Top left row headers data * @type {Array} */ scope.$$topLeftRowHeadersData = []; /** * Middle left row headers data * @type {Array} */ scope.$$middleLeftRowHeadersData = []; /** * Bottom left row headers data * @type {Array} */ scope.$$bottomLeftRowHeadersData = []; /** * Left column names * @type {Array} */ scope.$$leftColumnNames = []; /** * Center column names * @type {Array} */ scope.$$centerColumnNames = []; /** * Right column names * @type {Array} */ scope.$$rightColumnNames = []; scope.$$scrollTopPosition = angular.isNumber(scope.$$scrollTopPosition) ? scope.$$scrollTopPosition : 0; scope.$$scrollLeftPosition = angular.isNumber(scope.$$scrollLeftPosition) ? scope.$$scrollLeftPosition : 0; /* Register the data function */ if (angular.isFunction(scope['customDataValueFn'])) { scope.$$getDataValue = scope['customDataValueFn']; } else { scope.$$getDataValue = function (data, row, col) { return angular.isArray(data[row]) ? data[row][col] : undefined; }; } /* Data regions */ /** * Top left data array * @type {Array} */ scope.$$topLeftData = []; /** * Top center data array * @type {Array} */ scope.$$topCenterData = []; /** * Top right data array * @type {Array} */ scope.$$topRightData = []; /** * Middle left data array * @type {Array} */ scope.$$middleLeftData = []; /** * Middle center data array * @type {Array} */ scope.$$middleCenterData = []; /** * Middle right data array * @type {Array} */ scope.$$middleRightData = []; /** * Bottom left data array * @type {Array} */ scope.$$bottomLeftData = []; /** * Bottom center data array * @type {Array} */ scope.$$bottomCenterData = []; /** * Bottom right data array * @type {Array} */ scope.$$bottomRightData = []; /** * Scroll position in the data matrix * @type {{top: number, left: number}} */ scope.$$scrollPosition = { top: angular.isDefined(scope.scrollTopPosition) ? scope.scrollTopPosition : 0, left: angular.isDefined(scope.scrollLeftPosition) ? scope.scrollLeftPosition : 0 }; /** * Ranges for events, styles, etc... * @type {Array} */ scope.ranges = []; /** * Flag to show the column names. Default value is true * @type {string|.scope.showColumnNames|showColumnNames} */ scope.showColumnNames = angular.isDefined(scope.showColumnNames) ? scope.showColumnNames : true; /** * Flag to show the row number. Default value is true * @type {string|.scope.showColumnNames|showColumnNames} */ scope.showRowNumbers = angular.isDefined(scope.showRowNumbers) ? scope.showRowNumbers : true; /* If the show row number flag is on, add the required column */ if (scope.showRowNumbers) { scope.$$leftRowHeadersColumns.push({ clazz: 'row-number', rowNumberColumn: true }); } /** * Creates a row definition object * @param {number|Array} rowHeight Row height as a number, or an array * @param {number} index Index of the rowHeight to use, when it's an array * @returns {{index: *, height: string}} */ function createRowDefinitionByIndex(rowHeight, index) { return { index: index, height: $$getStyleDecl('height', rowHeight, index) + ';' + $$getStyleDecl('max-height', rowHeight, index) }; } /** * Creates row definitions array based on provided row properties * @param params * @returns {Array} */ function createRowsDefinitions(params) { var showRows = params.showRows, rowNumber = params.rowNumber, rowHeights = params.rowHeights, defaultRowNumber = params.defaultRowNumber || 1, rows = []; if (!showRows) { return rows; } rowNumber = angular.isNumber(rowNumber) ? rowNumber : defaultRowNumber; for (var i = 0; i < rowNumber; i++) { rows.push(createRowDefinitionByIndex(rowHeights, i)); } return rows; } /** * Flag to show the header rows. * @type {string|.scope.showHeader|showHeader} */ scope.showHeader = angular.isDefined(scope.showHeader) ? scope.showHeader : true; /** * Header rows definitions * @type {Array} */ scope.$$headerRows = createRowsDefinitions({ showRows: scope.showHeader, rowNumber: scope.headerRowNumber, rowHeights: scope.headerRowHeights, defaultRowNumber: 1 }); /** * Flag to show the filter rows. * @type {string|.scope.showFilter|showFilter} */ scope.showFilter = angular.isDefined(scope.showFilter) ? scope.showFilter : false; /** * Row definitions * @type {Array} */ scope.$$rows = createRowsDefinitions({ showRows: true, rowNumber: scope.rowNumber, rowHeights: scope.rowHeights, defaultRowNumber: 10 }); /** * Flag to show the footer rows. * @type {string|.scope.showFilter|showFilter} */ scope.showFooter = angular.isDefined(scope.showFooter) ? scope.showFooter : true; /** * Footer row definitions */ scope.$$footerRows = createRowsDefinitions({ showRows: scope.showFooter, rowNumber: scope.footerRowNumber, rowHeights: scope.footerRowHeights, defaultRowNumber: 1 }); }, post: function postLink(scope, iElement, iAttrs, controller) { /** * Returns a letter combination for an index * @param index * @returns {string} */ function getLettersForIndex(index) { var remainder = index % 26; var letter = String.fromCharCode(65 + remainder); if (index > 25) { letter = getLettersForIndex((index - remainder) / 26 - 1) + letter; } return letter; } /** * Default style function for the cells. Returns an empty string * @returns {string} */ function defaultStyleFn(/*data, row, col*/) { return ''; } /** * Default format function for the cells content. Returns the raw data * @param data * @returns {*} */ function defaultFormatFn(data /*, row, col*/) { return angular.isDefined(data) ? data : '&nbsp;'; } /** * Default html content function * @param data * @returns {*} */ function defaultHtmlFn(data, row, col, formattedValue) { return angular.isDefined(formattedValue) ? String(formattedValue) : '&nbsp;'; } /** * Event dispatcher function. Calls the registered event callback * @param eventName the name of the event * @param event the event object as passed by the listener * @param cellData the data registered for the cell */ scope.$$dispatchEvent = function (eventName, event, cellData) { /* Only handle callbacks that are actually functions */ if (cellData && angular.isFunction(cellData.eventCallbacks[eventName])) { /* apply the callback */ cellData.eventCallbacks[eventName](event, cellData); } }; /** * Return the cell data object given the row the column and the scope * @param scope The scope * @param row The row in data space * @param col The column in data space * @returns {{row: *, col: *, data: *, value: *, clazz: string, style: *, eventCallbacks: {}, enclosingRanges: Array, customCellTemplate: (string|Function), customHTML: string}} */ function $$getCellData(scope, row, col) { /* The additional optional class(es) */ var clazz = ''; /* The optional style function declaration */ var style = ''; /* The optional style function declaration */ var styleFn = defaultStyleFn; /* The data format function */ var formatFn = defaultFormatFn; /* The data value */ var data = scope.$$getDataValue(scope.data, row, col); /* The custom append function */ var customHtmlFn = defaultHtmlFn; /* The custom append function */ var customTrustedHtmlFn = undefined; /** * The custom template resolver * @type {string|Function} A template URL string or a function that returns the template url string. * Function signature: function(rawData, row, col, formattedValue, scope) */ var customCellTemplate = undefined; /* The cell event callbacks */ var eventCallbacks = {}; /* The ranges which contains this cell */ var enclosingRanges = []; /* Supported events */ var events = [ 'click', 'dblclick', 'keydown', 'keypress', 'keyup', 'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseover', 'mouseup' ]; /* Check all ranges and apply the range attributes if the cell is enclosed */ angular.forEach(scope.ranges, function (range) { if (row >= range.top && row < range.bottom && col >= range.left && col < range.right) { /* Register the enclosing range */ enclosingRanges.push(range); /* Register the format function */ if (angular.isFunction(range.formatFn)) formatFn = range['formatFn']; /* Register the CSS class */ if (angular.isString(range.clazz)) clazz = range.clazz; /* Register the CSS style declaration */ if (angular.isString(range.style)) style = range.style; if (angular.isFunction(range.styleFn)) styleFn = range['styleFn']; if (angular.isFunction(range.customHtmlFn)) customHtmlFn = range['customHtmlFn']; if (angular.isFunction(range.customTrustedHtmlFn)) customTrustedHtmlFn = range['customTrustedHtmlFn']; if (angular.isDefined(range.customCellTemplate)) { customCellTemplate = range.customCellTemplate; } /* Register available event callbacks */ angular.forEach(events, function (event) { if (angular.isFunction(range[event])) eventCallbacks[event] = range[event]; }); } }); var value = formatFn(data, row, col), customHTML; if (customCellTemplate && angular.isFunction(customCellTemplate)) { customCellTemplate = customCellTemplate(data, row, col, value, scope); } if (customCellTemplate == null || customCellTemplate == '') { // null, undefined or empty string customHTML = (angular.isDefined(customTrustedHtmlFn)) ? $sce.trustAsHtml(customTrustedHtmlFn(data, row, col, value)) : customHtmlFn(data, row, col, value); } return { row: row, col: col, data: data, value: value, clazz: clazz, style: styleFn(data, row, col) + ';' + style, eventCallbacks: eventCallbacks, enclosingRanges: enclosingRanges, customCellTemplate: customCellTemplate, customHTML: customHTML }; } /** * Updates the variable center cells * @param nRows Number of rows * @param centerData The center data part. may be top, middle or bottom * @param dataRowStartIndex The row start index, related to the data part */ scope.$$setCenterColumnsData = function (nRows, centerData, dataRowStartIndex) { var col; /* Update the column names */ for (col = 0; col < this.$$variableCenterColumns.length; col++) { this.$$centerColumnNames[col] = { value: getLettersForIndex(col + this.$$leftFixedColumns.length + this.$$scrollPosition.left) }; } /* Update all rows of the center table part */ for (var row = 0; row < nRows; row++) { var r = row + dataRowStartIndex; /* Reset the center data array to empty */ centerData[row] = []; for (col = 0; col < this.$$variableCenterColumns.length; col++) { /* the column is the current column index + the number of columns to the left + the left scroll position */ var c = col + this.$$leftFixedColumns.length + this.$$scrollPosition.left; centerData[row].push($$getCellData(scope, r, c)); } } }; /** * Updates the left and right fixed cells * @param nRows Number of rows of the table part * @param rowHeadersData The headers row data * @param leftData The data for the left part (top, middle or bottom) * @param rightData The data for the right part (top, middle or bottom) * @param dataRowStartIndex The row start index, related to the data part */ scope.$$setLeftAndRightColumnsData = function (nRows, rowHeadersData, leftData, rightData, dataRowStartIndex) { var col; /* Update the column names on the left */ for (col = 0; col < this.$$leftFixedColumns.length; col++) { this.$$leftColumnNames[col] = { value: getLettersForIndex(col) }; } /* Update the column names on the right */ var rowLength = angular.isDefined(this.data[0]) ? this.data[0].length : 0; var startColumnIndex = Math.max(rowLength - this.$$rightFixedColumns.length, this.$$leftFixedColumns.length + this.$$variableCenterColumns.length); for (col = 0; col < this.$$rightFixedColumns.length; col++) { this.$$rightColumnNames[col] = { value: getLettersForIndex(startColumnIndex + col) }; } /* Update each row */ for (var row = 0; row < nRows; row++) { /* Get the row index */ var r = dataRowStartIndex + row; /* Reset the row headers data */ rowHeadersData[row] = []; /* add the row number */ rowHeadersData[row][this.$$leftRowHeadersColumns.length - 1] = { value: r + 1 }; /* Reset the left data array */ leftData[row] = []; /* Update the left data */ for (col = 0; col < this.$$leftFixedColumns.length; col++) { leftData[row].push($$getCellData(scope, r, col)); } /* Reset the right data array */ rightData[row] = []; /* Update the right data */ for (col = 0; col < this.$$rightFixedColumns.length; col++) { rightData[row].push($$getCellData(scope, r, startColumnIndex + col)); } } }; /** * Updates data in all table parts */ scope.$$updateData = function () { /* Initialize the header parts */ this.$$setCenterColumnsData(this.$$headerRows.length, this.$$topCenterData, 0); this.$$setLeftAndRightColumnsData(this.$$headerRows.length, this.$$topLeftRowHeadersData, this.$$topLeftData, this.$$topRightData, 0); /* Initiaize the variable middle parts */ this.$$setCenterColumnsData(this.$$rows.length, this.$$middleCenterData, this.$$headerRows.length + this.$$scrollPosition.top); this.$$setLeftAndRightColumnsData(this.$$rows.length, this.$$middleLeftRowHeadersData, this.$$middleLeftData, this.$$middleRightData, this.$$headerRows.length + this.$$scrollPosition.top); /* Initialize the fixed footer parts */ /* The footer start row should be either the total data rows minus the footer height or the number of header rows + the number of rows */ var footerStartRow = Math.max(this.data.length - this.$$footerRows.length, this.$$headerRows.length + this.$$rows.length); this.$$setCenterColumnsData(this.$$footerRows.length, this.$$bottomCenterData, footerStartRow); this.$$setLeftAndRightColumnsData(this.$$footerRows.length, this.$$bottomLeftRowHeadersData, this.$$bottomLeftData, this.$$bottomRightData, footerStartRow); }; // Send an initial callback to set the scroll position on correct values if required if (angular.isFunction(scope.scrollFn)) scope.scrollFn(null, { top: scope.$$headerRows.length, left: scope.$$leftFixedColumns.length, direction: 'none' }); // Initialize the data scope.$$updateData(); scope.dataTotalRows = 0; scope.dataTotalCols = 0; scope.$watch( 'data', function (newValue, oldValue) { if (newValue !== oldValue) { if (newValue.length !== scope.dataTotalRows || newValue[0].length !== scope.dataTotalCols) { scope.$emit('content.reload'); if (scope.$$scrollPosition.top > newValue.length - scope.$$headerRows.length - scope.$$middleCenterData.length - scope.$$footerRows.length) { updateVerticalScroll(scope, null, newValue.length - scope.$$headerRows.length - scope.$$middleCenterData.length - scope.$$footerRows.length); } if (scope.$$scrollPosition.left > scope.data[0].length - scope.$$leftFixedColumns.length - scope.$$variableCenterColumns.length - scope.$$rightFixedColumns.length) { updateHorizontalScroll(scope, null, newValue.length - scope.$$leftFixedColumns.length - scope.$$variableCenterColumns.length - scope.$$rightFixedColumns.length); } scope.$$updateData(); } else { // Update the data $timeout(function() {scope.$$updateData();}); } } } ); scope.$$containerWidth = undefined; scope.$$containerHeight = undefined; scope.$$onVerticalScrollUpdate = false; scope.$$onHorizontalScrollUpdate = false; /* Externally controlled scroll positions */ scope.$watch('scrollTopPosition', function (newValue, oldValue) { if (!scope.$$onVerticalScrollUpdate && angular.isNumber(newValue) && angular.isNumber(oldValue) && newValue !== oldValue && !isNaN(newValue) && newValue >= 0) { updateVerticalScroll(scope, null, newValue); scope.$$updateData(); } } ); /* Internally controlled scroll positions */ scope.$watch('$$scrollTopPosition', function (newValue, oldValue) { if (angular.isNumber(newValue) && angular.isNumber(oldValue) && newValue !== oldValue && !isNaN(newValue) && newValue >= 0) { updateVerticalScroll(scope, newValue, null); scope.$$updateData(); } } ); function updateVerticalScroll(scope, contentPos, dataPos) { scope.$$onVerticalScrollUpdate = true; var totalRows = scope.data.length - scope.$$headerRows.length - scope.$$footerRows.length; var maxTop = totalRows - scope.$$middleCenterData.length; var percentage = 0; if (angular.isNumber(contentPos)) { percentage = contentPos / scope.$$contentHeight; } else if (angular.isNumber(dataPos)) { percentage = dataPos / totalRows; } var topPos = Math.min(Math.ceil(totalRows * Math.min(percentage, 1)), maxTop); scope.$$scrollPosition.top = topPos; if (angular.isNumber(contentPos)) { $parse('scrollTopPosition').assign(scope, topPos); } else if (angular.isNumber(dataPos)) { scope.$$scrollTopPosition = percentage * scope.$$contentHeight; scope.$emit('content.reload'); } $timeout(function () { scope.$$onVerticalScrollUpdate = false; }); } scope.$watch('scrollLeftPosition', function (newValue, oldValue) { if (!scope.$$onHorizontalScrollUpdate && angular.isNumber(newValue) && angular.isNumber(oldValue) && newValue !== oldValue && !isNaN(newValue) && newValue >= 0) { updateHorizontalScroll(scope, null, newValue); scope.$$updateData(); } } ); scope.$watch( '$$scrollLeftPosition', function (newValue, oldValue) { if (angular.isNumber(newValue) && angular.isNumber(oldValue) && newValue !== oldValue && !isNaN(newValue) && newValue >= 0) { updateHorizontalScroll(scope, newValue, null); scope.$$updateData(); } } ); function updateHorizontalScroll(scope, contentPos, dataPos) { scope.$$onHorizontalScrollUpdate = true; var totalMiddleCols = scope.data[0].length - scope.$$leftFixedColumns.length - scope.$$rightFixedColumns.length; var maxLeft = totalMiddleCols - scope.$$variableCenterColumns.length; var percentage = 0; if (angular.isNumber(contentPos)) { percentage = contentPos / scope.$$contentWidth; } else if (angular.isNumber(dataPos)) { percentage = dataPos / totalMiddleCols; } var leftPos = Math.min(Math.ceil(totalMiddleCols * Math.min(percentage, 1)), maxLeft); scope.$$scrollPosition.left = leftPos; if (angular.isNumber(contentPos)) { $parse('scrollLeftPosition').assign(scope, leftPos); } else if (angular.isNumber(dataPos)) { scope.$$scrollLeftPosition = percentage * scope.$$contentWidth; scope.$emit('content.reload'); } $timeout(function () { scope.$$onHorizontalScrollUpdate = false; }); } scope.$on('scrollable.dimensions', function (event, containerWidth, containerHeight, contentWidth, contentHeight, id) { // If there's no change in the contentWidth and contentHeight if (contentWidth == scope.$$contentWidth && contentHeight == scope.$$contentHeight && containerWidth == scope.$$containerWidth && containerHeight == scope.$$containerHeight) { return; } scope.dataTotalRows = scope.data.length; scope.dataTotalCols = scope.data[0].length; var totalRows = scope.data.length - scope.$$headerRows.length - scope.$$footerRows.length; var totalVisibleRows = scope.$$rows.length; var totalCols = scope.data[0].length - scope.$$leftFixedColumns.length - scope.$$rightFixedColumns.length; var totalVisibleCols = scope.$$variableCenterColumns.length; var nVPages = totalRows / totalVisibleRows; var nHPages = totalCols / totalVisibleCols; scope.$$contentHeight = containerHeight * nVPages; scope.$$contentWidth = containerWidth * nHPages; scope.$$containerWidth = containerWidth; scope.$$containerHeight = containerHeight; // Update scrollbars size scope.$emit('content.changed'); }); } } } return { scope: { /* Custom data function */ customDataValueFn: '=?', /* Data to display */ data: '=', /* Flag to show/hide the column names. By default true */ showColumnNames: '=?', /* Flag to show the row numbers. By default true */ showRowNumbers: '=?', /* Flag to show the header rows. By default true */ showHeader: '=?', /* Unimplemented yet. By default false */ showFilter: '=?', /* Flag to show the footer rows. By default true */ showFooter: '=?', /* Number of left fixed columns. By default 1 */ leftColumnNumber: '=?', /* Widths of the fixed left columns. */ leftColumnWidths: '=?', /* Number of center variable columns. By default 10 */ centerColumnNumber: '=', /* Widths of the center variable columns. */ centerColumnWidths: '=?', /* Number of right fixed columns. By default 1 */ rightColumnNumber: '=?', /* Widths of the fixed right columns. */ rightColumnWidths: '=?', /* Number of rows in the header. By default 1 */ headerRowNumber: '=?', /* Heights of the header rows (array or single value). No default (min-height:10px) */ headerRowHeights: '=?', /* Number of rows in the middle. By default 10 */ rowNumber: '=?', /* Heights of the middle rows (array or single value). No default (min-height:10px) */ rowHeights: '=?', /* Number of rows in the footer. By default 1 */ footerRowNumber: '=?', /* Heights of the footer rows (array or single value). No default (min-height:10px) */ footerRowHeights: '=?', /* Let read or set the vertical data position in the middle center part */ scrollTopPosition: '=?', /* Let read or set the horizontal data position in the middle center part */ scrollLeftPosition: '=?', /* Let read or set the vertical data position in the middle center part */ $$scrollTopPosition: '=?', /* Let read or set the horizontal data position in the middle center part */ $$scrollLeftPosition: '=?', $$contentHeight: '=?', $$contentWidth: '=?' }, restrict: 'AE', replace: true, transclude: true, template: $templateCache.get('ngc.table.tpl.html'), compile: compile, controller: controllerDecl }; }]) /* Internal directive for range declarations */ .directive('ngcRange', function () { return { require: "^ngcTable", restrict: 'AE', scope: { /* Top position of the range in data space */ top: '=', /* Bottom position of the range in data space */ bottom: '=', /* Left position of the range in data space */ left: '=', /* Right position of the range in data space */ right: '=', /* Format function for the cells enclosed in the range */ formatFn: '=?', /* Function to insert custom sanitized HTML in the range */ customHtmlFn: '=?', /* Function to insert custom trusted HTML in the range */ customTrustedHtmlFn: '=?', /* URL string of a custom template to render the cell contents. Can also be a Function instead, with the following signature: function(rawData, row, col, formattedValue, scope) */ customCellTemplate: '=?', /* CSS class to be added to the cells */ clazz: '=?', /* Direct CSS styling to be injected in the cells */ style: '=?', /* CSS style additional declaration to be added to the cell */ styleFn: '=?', /* Callback for the 'click' event */ clickFn: '=?', /* Callback for the 'dblclick' event */ dblclickFn: '=?', /* Callback for the 'keydown' event */ keydownFn: '=?', /* Callback for the 'keypress' event */ keypressFn: '=?', /* Callback for the 'keyup' event */ keyupFn: '=?', /* Callback for the 'mousedown' event */ mousedownFn: '=?', /* Callback for the 'mouseenter' event */ mouseenterFn: '=?', /* Callback for the 'mouseleave' event */ mouseleaveFn: '=?', /* Callback for the 'mousemove' event */ mousemoveFn: '=?', /* Callback for the 'mouseover' event */ mouseoverFn: '=?', /* Callback for the 'mouseup' event */ mouseupFn: '=?' }, link: function (scope, element, attrs, parentCtrl) { /* On the linking (post-compile) step, call the parent (ngc-table) controller to register the current range */ parentCtrl.addRange({ top: scope.top, bottom: scope.bottom, left: scope.left, right: scope.right, formatFn: scope.formatFn, clazz: scope.clazz, styleFn: scope.styleFn, style: scope.style, customHtmlFn: scope.customHtmlFn, customTrustedHtmlFn: scope.customTrustedHtmlFn, customCellTemplate: scope.customCellTemplate, click: scope.clickFn, dblclick: scope.dblclickFn, keydown: scope.keydownFn, keypress: scope.keypressFn, keyup: scope.keyupFn, mousedown: scope.mousedownFn, mouseenter: scope.mouseenterFn, mouseleave: scope.mouseleaveFn, mousemove: scope.mousemoveFn, mouseover: scope.mouseoverFn, mouseup: scope.mouseupFn, touchstart: scope.touchstartFn, touchmove: scope.touchmoveFn, touchend: scope.touchendFn }); } }; }) /** * @name extInclude * Extended version of ngInclude where we can also specify an additional scope variable as 'scopeExtension'. * Can only be used as an Attribute. * * @param {string} extInclude Angular expression evaluating to a template URL * @param {string} scopeExtension Angular expression evaluating to an object. Its value will be available in the * inner scope of the directive. */ .directive('extInclude', [ function () { // List of attributes to map to the scope var attrToMap = ['extInclude', 'scopeExtension']; /** * Sets a given attribute onto the scope after evaluating it and watch for future value changes * @param {Object} scope * @param {Object} attr * @param {string} attrName * @return {void} */ var setupScopeVar = function (scope, attr, attrName) { scope.$watch(attr[attrName], function (newValue, oldValue) { if (newValue === oldValue) { return; } scope[attrName] = newValue; }, true); scope[attrName] = scope.$eval(attr[attrName]); }; return { restrict: 'A', template: '<ng-include src="extInclude"></ng-include>', scope: true, link: function (scope, element, attr) { for (var i = 0, len = attrToMap.length; i < len; i++) { setupScopeVar(scope, attr, attrToMap[i]); } } }; } ]); })(); angular.module('ngc-template', ['ngc.table.tpl.html']); angular.module("ngc.table.tpl.html", []).run(["$templateCache", function($templateCache) { $templateCache.put("ngc.table.tpl.html", "<div class=\"ngc table\">\n" + " <div ng-transclude style=\"display: hidden\"></div>\n" + "\n" + " <div class=\"ngc scroll-wrapper\" ng-scrollable=\"{updateContentPosition:false, enableKinetic:false, wheelSpeed:1}\"\n" + " spy-x=\"$$scrollLeftPosition\"\n" + " spy-y=\"$$scrollTopPosition\"\n" + " spy-custom-content-width=\"$$contentWidth\"\n" + " spy-custom-content-height=\"$$contentHeight\"\n" + " >\n" + " <table class=\"ngc\">\n" + " <!-- Column Names -->\n" + " <tr class=\"ngc row column-names\" ng-show=\"{{showColumnNames}}\" ng-class=\"{first: $first, last: $last}\">\n" + " <!-- Cells for row headers columns -->\n" + " <td ng-repeat=\"column in $$leftRowHeadersColumns\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc row-header column-name cell {{column.clazz}}\"\n" + " style=\"{{column.style}}\">\n" + " <div class=\"ngc cell-content\" style=\"{{column.style}}\"></div>\n" + " </td>\n" + "\n" + " <!-- Cells for left fixed columns -->\n" + " <td ng-repeat=\"column in $$leftFixedColumns\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc left column-name cell {{$$leftColumnNames[$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$leftColumnNames[$index].style}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content\" style=\"{{column.style}}\">{{$$leftColumnNames[$index].value}}</div>\n" + " </td>\n" + "\n" + " <!-- Cells for middle variable columns -->\n" + " <td ng-repeat=\"column in $$variableCenterColumns\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc center column-name cell {{$$centerColumnNames[$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$centerColumnNames[$index].style}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content\" style=\"{{column.style}}\">{{$$centerColumnNames[$index].value}}</div>\n" + " </td>\n" + "\n" + " <!-- Cells for right fixed columns -->\n" + " <td ng-repeat=\"column in $$rightFixedColumns\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc right column-name cell {{$$rightColumnNames[$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$rightColumnNames[$index].style}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content\" style=\"{{column.style}}\">{{$$rightColumnNames[$index].value}}</div>\n" + " </td>\n" + "\n" + " </tr>\n" + "\n" + " <!-- Headers -->\n" + " <tr class=\"ngc row header\" ng-show=\"{{showHeader}}\" ng-repeat=\"row in $$headerRows\" ng-class=\"{first: $first, last: $last}\">\n" + " <!-- Cells for row headers columns -->\n" + " <td ng-repeat=\"column in $$leftRowHeadersColumns\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc row-header header cell {{$$topLeftRowHeadersData[$parent.$index][$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$topLeftRowHeadersData[$parent.$index][$index].style}}; {{row.height}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content\" style=\"{{row.height}}; {{column.style}}\" >{{$$topLeftRowHeadersData[$parent.$index][$index].value}}</div>\n" + " </td>\n" + "\n" + " <!-- Cells for left fixed columns -->\n" + " <td ng-repeat=\"column in $$leftFixedColumns\"\n" + " ng-click=\"$$dispatchEvent('click', $event, $$topLeftData[$parent.$index][$index])\"\n" + " ng-dblclick=\"$$dispatchEvent('dblclick', $event, $$topLeftData[$parent.$index][$index])\"\n" + " ng-keydown=\"$$dispatchEvent('keydown', $event, $$topLeftData[$parent.$index][$index])\"\n" + " ng-keypress=\"$$dispatchEvent('keypress', $event, $$topLeftData[$parent.$index][$index])\"\n" + " ng-keyup=\"$$dispatchEvent('keyup', $event, $$topLeftData[$parent.$index][$index])\"\n" + " ng-mousedown=\"$$dispatchEvent('mousedown', $event, $$topLeftData[$parent.$index][$index])\"\n" + " ng-mouseleave=\"$$dispatchEvent('mouseleave', $event, $$topLeftData[$parent.$index][$index])\"\n" + " ng-mouseenter=\"$$dispatchEvent('mouseenter', $event, $$topLeftData[$parent.$index][$index])\"\n" + " ng-mousemove=\"$$dispatchEvent('mousemove', $event, $$topLeftData[$parent.$index][$index])\"\n" + " ng-mouseover=\"$$dispatchEvent('mouseover', $event, $$topLeftData[$parent.$index][$index])\"\n" + " ng-mouseup=\"$$dispatchEvent('mouseup', $event, $$topLeftData[$parent.$index][$index])\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc left header cell {{$$topLeftData[$parent.$index][$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$topLeftData[$parent.$index][$index].style}}; {{row.height}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content ngc-custom-html\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"!$$topLeftData[$parent.$index][$index].customCellTemplate\"\n" + " ng-bind-html=\"$$topLeftData[$parent.$parent.$index][$index].customHTML\"></div>\n" + " <div class=\"ngc cell-content ngc-custom-cell-template\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"$$topLeftData[$parent.$index][$index].customCellTemplate\"\n" + " ext-include=\"$$topLeftData[row.index][$index].customCellTemplate\"\n" + " scope-extension=\"{'rawCellData': $$topLeftData[row.index][$index]}\"></div>\n" + " </td>\n" + "\n" + " <!-- Cells for middle variable columns -->\n" + " <td ng-repeat=\"column in $$variableCenterColumns\"\n" + " ng-click=\"$$dispatchEvent('click', $event, $$topCenterData[$parent.$index][$index])\"\n" + " ng-dblclick=\"$$dispatchEvent('dblclick', $event, $$topCenterData[$parent.$index][$index])\"\n" + " ng-keydown=\"$$dispatchEvent('keydown', $event, $$topCenterData[$parent.$index][$index])\"\n" + " ng-keypress=\"$$dispatchEvent('keypress', $event, $$topCenterData[$parent.$index][$index])\"\n" + " ng-keyup=\"$$dispatchEvent('keyup', $event, $$topCenterData[$parent.$index][$index])\"\n" + " ng-mousedown=\"$$dispatchEvent('mousedown', $event, $$topCenterData[$parent.$index][$index])\"\n" + " ng-mouseleave=\"$$dispatchEvent('mouseleave', $event, $$topCenterData[$parent.$index][$index])\"\n" + " ng-mouseenter=\"$$dispatchEvent('mouseenter', $event, $$topCenterData[$parent.$index][$index])\"\n" + " ng-mousemove=\"$$dispatchEvent('mousemove', $event, $$topCenterData[$parent.$index][$index])\"\n" + " ng-mouseover=\"$$dispatchEvent('mouseover', $event, $$topCenterData[$parent.$index][$index])\"\n" + " ng-mouseup=\"$$dispatchEvent('mouseup', $event, $$topCenterData[$parent.$index][$index])\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc center header cell {{$$topCenterData[$parent.$index][$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$topCenterData[$parent.$index][$index].style}}; {{row.height}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content ngc-custom-html\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"!$$topCenterData[$parent.$index][$index].customCellTemplate\"\n" + " ng-bind-html=\"$$topCenterData[$parent.$parent.$index][$index].customHTML\"></div>\n" + " <div class=\"ngc cell-content ngc-custom-cell-template\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"$$topCenterData[$parent.$index][$index].customCellTemplate\"\n" + " ext-include=\"$$topCenterData[row.index][$index].customCellTemplate\"\n" + " scope-extension=\"{'rawCellData': $$topCenterData[row.index][$index]}\"></div>\n" + " </td>\n" + "\n" + " <!-- Cells for right fixed columns -->\n" + " <td ng-repeat=\"column in $$rightFixedColumns\"\n" + " ng-click=\"$$dispatchEvent('click', $event, $$topRightData[$parent.$index][$index])\"\n" + " ng-dblclick=\"$$dispatchEvent('dblclick', $event, $$topRightData[$parent.$index][$index])\"\n" + " ng-keydown=\"$$dispatchEvent('keydown', $event, $$topRightData[$parent.$index][$index])\"\n" + " ng-keypress=\"$$dispatchEvent('keypress', $event, $$topRightData[$parent.$index][$index])\"\n" + " ng-keyup=\"$$dispatchEvent('keyup', $event, $$topRightData[$parent.$index][$index])\"\n" + " ng-mousedown=\"$$dispatchEvent('mousedown', $event, $$topRightData[$parent.$index][$index])\"\n" + " ng-mouseleave=\"$$dispatchEvent('mouseleave', $event, $$topRightData[$parent.$index][$index])\"\n" + " ng-mouseenter=\"$$dispatchEvent('mouseenter', $event, $$topRightData[$parent.$index][$index])\"\n" + " ng-mousemove=\"$$dispatchEvent('mousemove', $event, $$topRightData[$parent.$index][$index])\"\n" + " ng-mouseover=\"$$dispatchEvent('mouseover', $event, $$topRightData[$parent.$index][$index])\"\n" + " ng-mouseup=\"$$dispatchEvent('mouseup', $event, $$topRightData[$parent.$index][$index])\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc right header cell {{$$topRightData[$parent.$index][$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$topRightData[$parent.$index][$index].style}}; {{row.height}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content ngc-custom-html\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"!$$topRightData[$parent.$index][$index].customCellTemplate\"\n" + " ng-bind-html=\"$$topRightData[$parent.$parent.$index][$index].customHTML\"></div>\n" + " <div class=\"ngc cell-content ngc-custom-cell-template\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"$$topRightData[$parent.$index][$index].customCellTemplate\"\n" + " ext-include=\"$$topRightData[row.index][$index].customCellTemplate\"\n" + " scope-extension=\"{'rawCellData': $$topRightData[row.index][$index]}\"></div>\n" + " </td>\n" + "\n" + "\n" + " </tr>\n" + "\n" + " <!-- Middle -->\n" + " <tr class=\"ngc row middle\" ng-repeat=\"row in $$rows\" ng-class=\"{first: $first, last: $last}\">\n" + " <!-- Cells for row headers columns -->\n" + " <td ng-repeat=\"column in $$leftRowHeadersColumns\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc row-header middle cell {{$$middleLeftRowHeadersData[$parent.$index][$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$middleLeftRowHeadersData[$parent.$index][$index].style}}; {{row.height}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content\" style=\"{{row.height}}; {{column.style}}\">{{$$middleLeftRowHeadersData[$parent.$index][$index].value}}</div>\n" + " </td>\n" + "\n" + " <!-- Cells for left fixed columns -->\n" + " <td ng-repeat=\"column in $$leftFixedColumns\"\n" + " ng-click=\"$$dispatchEvent('click', $event, $$middleLeftData[$parent.$index][$index])\"\n" + " ng-dblclick=\"$$dispatchEvent('dblclick', $event, $$middleLeftData[$parent.$index][$index])\"\n" + " ng-keydown=\"$$dispatchEvent('keydown', $event, $$middleLeftData[$parent.$index][$index])\"\n" + " ng-keypress=\"$$dispatchEvent('keypress', $event, $$middleLeftData[$parent.$index][$index])\"\n" + " ng-keyup=\"$$dispatchEvent('keyup', $event, $$middleLeftData[$parent.$index][$index])\"\n" + " ng-mousedown=\"$$dispatchEvent('mousedown', $event, $$middleLeftData[$parent.$index][$index])\"\n" + " ng-mouseleave=\"$$dispatchEvent('mouseleave', $event, $$middleLeftData[$parent.$index][$index])\"\n" + " ng-mouseenter=\"$$dispatchEvent('mouseenter', $event, $$middleLeftData[$parent.$index][$index])\"\n" + " ng-mousemove=\"$$dispatchEvent('mousemove', $event, $$middleLeftData[$parent.$index][$index])\"\n" + " ng-mouseover=\"$$dispatchEvent('mouseover', $event, $$middleLeftData[$parent.$index][$index])\"\n" + " ng-mouseup=\"$$dispatchEvent('mouseup', $event, $$middleLeftData[$parent.$index][$index])\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc left middle cell {{$$middleLeftData[$parent.$index][$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$middleLeftData[$parent.$index][$index].style}} ; {{row.height}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content ngc-custom-html\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"!$$middleLeftData[$parent.$index][$index].customCellTemplate\"\n" + " ng-bind-html=\"$$middleLeftData[$parent.$parent.$index][$index].customHTML\"></div>\n" + " <div class=\"ngc cell-content ngc-custom-cell-template\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"$$middleLeftData[$parent.$index][$index].customCellTemplate\"\n" + " ext-include=\"$$middleLeftData[row.index][$index].customCellTemplate\"\n" + " scope-extension=\"{'rawCellData': $$middleLeftData[row.index][$index]}\"></div>\n" + " </td>\n" + "\n" + " <!-- Cells for middle variable columns -->\n" + " <td ng-repeat=\"column in $$variableCenterColumns\"\n" + " ng-click=\"$$dispatchEvent('click', $event, $$middleCenterData[$parent.$index][$index])\"\n" + " ng-dblclick=\"$$dispatchEvent('dblclick', $event, $$middleCenterData[$parent.$index][$index])\"\n" + " ng-keydown=\"$$dispatchEvent('keydown', $event, $$middleCenterData[$parent.$index][$index])\"\n" + " ng-keypress=\"$$dispatchEvent('keypress', $event, $$middleCenterData[$parent.$index][$index])\"\n" + " ng-keyup=\"$$dispatchEvent('keyup', $event, $$middleCenterData[$parent.$index][$index])\"\n" + " ng-mousedown=\"$$dispatchEvent('mousedown', $event, $$middleCenterData[$parent.$index][$index])\"\n" + " ng-mouseleave=\"$$dispatchEvent('mouseleave', $event, $$middleCenterData[$parent.$index][$index])\"\n" + " ng-mouseenter=\"$$dispatchEvent('mouseenter', $event, $$middleCenterData[$parent.$index][$index])\"\n" + " ng-mousemove=\"$$dispatchEvent('mousemove', $event, $$middleCenterData[$parent.$index][$index])\"\n" + " ng-mouseover=\"$$dispatchEvent('mouseover', $event, $$middleCenterData[$parent.$index][$index])\"\n" + " ng-mouseup=\"$$dispatchEvent('mouseup', $event, $$middleCenterData[$parent.$index][$index])\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc center cell middle {{$$middleCenterData[$parent.$index][$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$middleCenterData[$parent.$index][$index].style}}; {{row.height}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content ngc-custom-html\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"!$$middleCenterData[$parent.$index][$index].customCellTemplate\"\n" + " ng-bind-html=\"$$middleCenterData[$parent.$parent.$index][$index].customHTML\"></div>\n" + " <div class=\"ngc cell-content ngc-custom-cell-template\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"$$middleCenterData[$parent.$index][$index].customCellTemplate\"\n" + " ext-include=\"$$middleCenterData[row.index][$index].customCellTemplate\"\n" + " scope-extension=\"{'rawCellData': $$middleCenterData[row.index][$index]}\"></div>\n" + " </td>\n" + "\n" + " <!-- Cells for right fixed columns -->\n" + " <td ng-repeat=\"column in $$rightFixedColumns\"\n" + " ng-click=\"$$dispatchEvent('click', $event, $$middleRightData[$parent.$index][$index])\"\n" + " ng-dblclick=\"$$dispatchEvent('dblclick', $event, $$middleRightData[$parent.$index][$index])\"\n" + " ng-keydown=\"$$dispatchEvent('keydown', $event, $$middleRightData[$parent.$index][$index])\"\n" + " ng-keypress=\"$$dispatchEvent('keypress', $event, $$middleRightData[$parent.$index][$index])\"\n" + " ng-keyup=\"$$dispatchEvent('keyup', $event, $$middleRightData[$parent.$index][$index])\"\n" + " ng-mousedown=\"$$dispatchEvent('mousedown', $event, $$middleRightData[$parent.$index][$index])\"\n" + " ng-mouseleave=\"$$dispatchEvent('mouseleave', $event, $$middleRightData[$parent.$index][$index])\"\n" + " ng-mouseenter=\"$$dispatchEvent('mouseenter', $event, $$middleRightData[$parent.$index][$index])\"\n" + " ng-mousemove=\"$$dispatchEvent('mousemove', $event, $$middleRightData[$parent.$index][$index])\"\n" + " ng-mouseover=\"$$dispatchEvent('mouseover', $event, $$middleRightData[$parent.$index][$index])\"\n" + " ng-mouseup=\"$$dispatchEvent('mouseup', $event, $$middleRightData[$parent.$index][$index])\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc right cell middle {{$$middleRightData[$parent.$index][$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$middleRightData[$parent.$index][$index].style}}; {{row.height}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content ngc-custom-html\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"!$$middleRightData[$parent.$index][$index].customCellTemplate\"\n" + " ng-bind-html=\"$$middleRightData[$parent.$parent.$index][$index].customHTML\"></div>\n" + " <div class=\"ngc cell-content ngc-custom-cell-template\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"$$middleRightData[$parent.$index][$index].customCellTemplate\"\n" + " ext-include=\"$$middleRightData[row.index][$index].customCellTemplate\"\n" + " scope-extension=\"{'rawCellData': $$middleRightData[row.index][$index]}\"></div>\n" + " </td>\n" + "\n" + " </tr>\n" + "\n" + " <!-- Bottom -->\n" + " <tr class=\"ngc row footer\" ng-repeat=\"row in $$footerRows\" ng-class=\"{first: $first, last: $last}\">\n" + " <!-- Cells for row headers columns -->\n" + " <td ng-repeat=\"column in $$leftRowHeadersColumns\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc row-header footer cell {{$$bottomLeftRowHeadersData[$parent.$index][$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$bottomLeftRowHeadersData[$parent.$index][$index].style}}; {{row.height}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content\" style=\"{{row.height}}; {{column.style}}\">{{$$bottomLeftRowHeadersData[$parent.$index][$index].value}}</div>\n" + " </td>\n" + "\n" + " <!-- Cells for left fixed columns -->\n" + " <td ng-repeat=\"column in $$leftFixedColumns\"\n" + " ng-click=\"$$dispatchEvent('click', $event, $$bottomLeftData[$parent.$index][$index])\"\n" + " ng-dblclick=\"$$dispatchEvent('dblclick', $event, $$bottomLeftData[$parent.$index][$index])\"\n" + " ng-keydown=\"$$dispatchEvent('keydown', $event, $$bottomLeftData[$parent.$index][$index])\"\n" + " ng-keypress=\"$$dispatchEvent('keypress', $event, $$bottomLeftData[$parent.$index][$index])\"\n" + " ng-keyup=\"$$dispatchEvent('keyup', $event, $$bottomLeftData[$parent.$index][$index])\"\n" + " ng-mousedown=\"$$dispatchEvent('mousedown', $event, $$bottomLeftData[$parent.$index][$index])\"\n" + " ng-mouseleave=\"$$dispatchEvent('mouseleave', $event, $$bottomLeftData[$parent.$index][$index])\"\n" + " ng-mouseenter=\"$$dispatchEvent('mouseenter', $event, $$bottomLeftData[$parent.$index][$index])\"\n" + " ng-mousemove=\"$$dispatchEvent('mousemove', $event, $$bottomLeftData[$parent.$index][$index])\"\n" + " ng-mouseover=\"$$dispatchEvent('mouseover', $event, $$bottomLeftData[$parent.$index][$index])\"\n" + " ng-mouseup=\"$$dispatchEvent('mouseup', $event, $$bottomLeftData[$parent.$index][$index])\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc left footer cell {{$$bottomLeftData[$parent.$index][$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$bottomLeftData[$parent.$index][$index].style}}; {{row.height}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content ngc-custom-html\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"!$$bottomLeftData[$parent.$index][$index].customCellTemplate\"\n" + " ng-bind-html=\"$$bottomLeftData[$parent.$parent.$index][$index].customHTML\"></div>\n" + " <div class=\"ngc cell-content ngc-custom-cell-template\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"$$bottomLeftData[$parent.$index][$index].customCellTemplate\"\n" + " ext-include=\"$$bottomLeftData[row.index][$index].customCellTemplate\"\n" + " scope-extension=\"{'rawCellData': $$bottomLeftData[row.index][$index]}\"></div>\n" + " </td>\n" + "\n" + " <!-- Cells for middle variable columns -->\n" + " <td ng-repeat=\"column in $$variableCenterColumns\"\n" + " ng-click=\"$$dispatchEvent('click', $event, $$bottomCenterData[$parent.$index][$index])\"\n" + " ng-dblclick=\"$$dispatchEvent('dblclick', $event, $$bottomCenterData[$parent.$index][$index])\"\n" + " ng-keydown=\"$$dispatchEvent('keydown', $event, $$bottomCenterData[$parent.$index][$index])\"\n" + " ng-keypress=\"$$dispatchEvent('keypress', $event, $$bottomCenterData[$parent.$index][$index])\"\n" + " ng-keyup=\"$$dispatchEvent('keyup', $event, $$bottomCenterData[$parent.$index][$index])\"\n" + " ng-mousedown=\"$$dispatchEvent('mousedown', $event, $$bottomCenterData[$parent.$index][$index])\"\n" + " ng-mouseleave=\"$$dispatchEvent('mouseleave', $event, $$bottomCenterData[$parent.$index][$index])\"\n" + " ng-mouseenter=\"$$dispatchEvent('mouseenter', $event, $$bottomCenterData[$parent.$index][$index])\"\n" + " ng-mousemove=\"$$dispatchEvent('mousemove', $event, $$bottomCenterData[$parent.$index][$index])\"\n" + " ng-mouseover=\"$$dispatchEvent('mouseover', $event, $$bottomCenterData[$parent.$index][$index])\"\n" + " ng-mouseup=\"$$dispatchEvent('mouseup', $event, $$bottomCenterData[$parent.$index][$index])\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc center footer cell {{$$bottomCenterData[$parent.$index][$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$bottomCenterData[$parent.$index][$index].style}}; {{row.height}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content ngc-custom-html\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"!$$bottomCenterData[$parent.$index][$index].customCellTemplate\"\n" + " ng-bind-html=\"$$bottomCenterData[$parent.$parent.$index][$index].customHTML\"></div>\n" + " <div class=\"ngc cell-content ngc-custom-cell-template\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"$$bottomCenterData[$parent.$index][$index].customCellTemplate\"\n" + " ext-include=\"$$bottomCenterData[row.index][$index].customCellTemplate\"\n" + " scope-extension=\"{'rawCellData': $$bottomCenterData[row.index][$index]}\"></div>\n" + " </td>\n" + "\n" + " <!-- Cells for right fixed columns -->\n" + " <td ng-repeat=\"column in $$rightFixedColumns\"\n" + " ng-click=\"$$dispatchEvent('click', $event, $$bottomRightData[$parent.$index][$index])\"\n" + " ng-dblclick=\"$$dispatchEvent('dblclick', $event, $$bottomRightData[$parent.$index][$index])\"\n" + " ng-keydown=\"$$dispatchEvent('keydown', $event, $$bottomRightData[$parent.$index][$index])\"\n" + " ng-keypress=\"$$dispatchEvent('keypress', $event, $$bottomRightData[$parent.$index][$index])\"\n" + " ng-keyup=\"$$dispatchEvent('keyup', $event, $$bottomRightData[$parent.$index][$index])\"\n" + " ng-mousedown=\"$$dispatchEvent('mousedown', $event, $$bottomRightData[$parent.$index][$index])\"\n" + " ng-mouseleave=\"$$dispatchEvent('mouseleave', $event, $$bottomRightData[$parent.$index][$index])\"\n" + " ng-mouseenter=\"$$dispatchEvent('mouseenter', $event, $$bottomRightData[$parent.$index][$index])\"\n" + " ng-mousemove=\"$$dispatchEvent('mousemove', $event, $$bottomRightData[$parent.$index][$index])\"\n" + " ng-mouseover=\"$$dispatchEvent('mouseover', $event, $$bottomRightData[$parent.$index][$index])\"\n" + " ng-mouseup=\"$$dispatchEvent('mouseup', $event, $$bottomRightData[$parent.$index][$index])\"\n" + " ng-class=\"{first: $first, last: $last}\"\n" + " class=\"ngc right footer cell {{$$bottomRightData[$parent.$index][$index].clazz}} {{column.clazz}}\"\n" + " style=\"{{$$bottomRightData[$parent.$index][$index].style}}; {{row.height}}; {{column.style}}\">\n" + " <div class=\"ngc cell-content ngc-custom-html\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"!$$bottomRightData[$parent.$index][$index].customCellTemplate\"\n" + " ng-bind-html=\"$$bottomRightData[$parent.$parent.$index][$index].customHTML\"></div>\n" + " <div class=\"ngc cell-content ngc-custom-cell-template\" style=\"{{row.height}}; {{column.style}}\"\n" + " ng-if=\"$$bottomRightData[$parent.$index][$index].customCellTemplate\"\n" + " ext-include=\"$$bottomRightData[row.index][$index].customCellTemplate\"\n" + " scope-extension=\"{'rawCellData': $$bottomRightData[row.index][$index]}\"></div>\n" + " </td>\n" + "\n" + " </tr>\n" + " </table>\n" + " </div>\n" + "</div>"); }]); /* ========================================================= * ng-scrollable.js v0.2.0 * http://github.com/echa/ng-scrollable * ========================================================= * Copyright 2014-2015 Alexander Eichhorn * * The MIT License (MIT) Copyright (c) 2014-2015 Alexander Eichhorn. * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom * the Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * ========================================================= */ angular.module('ngScrollable', []) .directive('ngScrollable', ['$injector', function ($injector) { 'use strict'; // dependencies var $document = $injector.get('$document'); var $interval = $injector.get('$interval'); var $timeout = $injector.get('$timeout'); var $window = $injector.get('$window'); var $parse = $injector.get('$parse'); var extend = angular.extend; var element = angular.element; var isDefined = angular.isDefined; var isTouchDevice = typeof $window.ontouchstart !== 'undefined'; var xform = 'transform'; // use requestAnimationFrame for kinetic scrolling var $$rAF = $window.requestAnimationFrame || $window.webkitRequestAnimationFrame; // Angular used to contain an internal service that is using a task queue // in 1.4.x which makes it incompatible with smooth scrolling // // var $$rAF = $injector.get('$$rAF'); // find the correct CSS transform feature class name ['webkit', 'moz', 'o', 'ms'].every(function (prefix) { var e = prefix + 'Transform'; var body = $document.find('body').eq(0); if (typeof body[0].style[e] !== 'undefined') { xform = e; return false; } return true; }); var defaultOpts = { id: 0, scrollX: 'bottom', scrollY: 'right', scrollXSlackSpace: 0, scrollYSlackSpace: 0, scrollXAlways: false, scrollYAlways: false, usePadding: false, wheelSpeed: 1, minSliderLength: 10, useBothWheelAxes: false, useKeyboard: true, updateOnResize: true, kineticTau: 325, enableKinetic:true, updateContentPosition:true }; return { restrict: 'A', transclude: true, template: "<div class=\"scrollable\"><div class=\"scrollable-content\" ng-transclude></div><div class='scrollable-bar scrollable-bar-x'><div class='scrollable-slider'></div></div><div class='scrollable-bar scrollable-bar-y'><div class='scrollable-slider'></div></div></div>", link: function ($scope, elem, attrs) { var config = extend({}, defaultOpts, $scope.$eval(attrs.ngScrollable)), el = element(elem.children()[0]), dom = { window: element($window), el: el, content: element(el.children()[0]), barX: element(el.children()[1]), barY: element(el.children()[2]), sliderX: element(element(el.children()[1]).children()[0]), sliderY: element(element(el.children()[2]).children()[0]) }, isXActive = false, isYActive = false, containerWidth = 0, containerHeight = 0, contentWidth = 0, contentHeight = 0, customContentWidth = 0, customContentHeight = 0, contentTop = 0, contentLeft = 0, xSliderWidth = 0, xSliderLeft = 0, ySliderHeight = 0, ySliderTop = 0, dragStartLeft = null, dragStartPageX = null, dragStartTop = null, dragStartPageY = null, isXScrolling = false, isYScrolling = false, hovered = false, activeTimeout, spySetter = {}, // kinetic scrolling velocityX = 0, amplitudeX = 0, frameX = 0, targetX = 0, velocityY = 0, amplitudeY = 0, frameY = 0, targetY = 0, trackTime, trackerTimeout, toPix = function (v) { return v.toFixed(3) + 'px'; }, clamp = function (val, min, max) { return Math.max(min, Math.min(val, max)); }, updateSliderX = function () { // adjust container width by the amount of border pixels so that the // slider does not extend outside the bar region var cw = containerWidth - 3; if (isXActive) { xSliderWidth = Math.max(config.minSliderLength, parseInt(cw * cw / contentWidth, 10)); xSliderLeft = parseInt(contentLeft * (cw - xSliderWidth) / (contentWidth - cw), 10); if (xSliderLeft >= cw - xSliderWidth) { xSliderLeft = cw - xSliderWidth; } else if (xSliderLeft < 0) { xSliderLeft = 0; } dom.sliderX[0].style[xform] = 'translate3d(' + toPix(xSliderLeft) + ',0,0)'; dom.sliderX[0].style.width = toPix(xSliderWidth); } else { xSliderWidth = xSliderLeft = 0; dom.sliderX[0].style[xform] = 'translate3d(0,0,0)'; dom.sliderX[0].style.width = '0'; } }, updateSliderY = function () { // adjust container height by the amount of border pixels so that the // slider does not extend outside the bar region var ch = containerHeight - 3; if (isYActive) { ySliderHeight = Math.max(config.minSliderLength, parseInt(ch * ch / contentHeight, 10)); ySliderTop = parseInt(contentTop * (ch - ySliderHeight) / (contentHeight - ch), 10); if (ySliderTop >= ch - ySliderHeight) { ySliderTop = ch - ySliderHeight; } else if (ySliderTop < 0) { ySliderTop = 0; } dom.sliderY[0].style[xform] = 'translate3d(0,' + toPix(ySliderTop) + ',0)'; dom.sliderY[0].style.height = toPix(ySliderHeight); } else { ySliderTop = ySliderHeight = 0; dom.sliderY[0].style[xform] = 'translate3d(0,0,0)'; dom.sliderY[0].style.height = '0'; } }, updateBarX = function () { var showAlways = config.scrollXAlways, scrollbarXStyles = {left: 0, width: toPix(containerWidth), display: isXActive || showAlways ? "inherit" : "none"}; switch (config.scrollX) { case 'bottom': scrollbarXStyles.bottom = 0; dom.content[isXActive || showAlways ? 'addClass' : 'removeClass']('scrollable-bottom'); dom.barX[isXActive || showAlways ? 'addClass' : 'removeClass']('scrollable-bottom'); break; case 'top': scrollbarXStyles.top = 0; dom.content[isXActive || showAlways ? 'addClass' : 'removeClass']('scrollable-top'); dom.barX[isXActive || showAlways ? 'addClass' : 'removeClass']('scrollable-top'); break; } dom.barX.css(scrollbarXStyles); dom.sliderX[0].style.display = isXActive ? 'inherit' : 'none'; }, updateBarY = function () { var showAlways = config.scrollYAlways, scrollbarYStyles = {top: 0, height: toPix(containerHeight), display: isYActive || showAlways ? "inherit" : "none"}; switch (config.scrollY) { case 'right': scrollbarYStyles.right = 0; dom.content[isYActive || showAlways ? 'addClass' : 'removeClass']('scrollable-right'); dom.barY[isYActive || showAlways ? 'addClass' : 'removeClass']('scrollable-right'); break; case 'left': scrollbarYStyles.left = 0; dom.content[isYActive || showAlways ? 'addClass' : 'removeClass']('scrollable-left'); dom.barY[isYActive || showAlways ? 'addClass' : 'removeClass']('scrollable-left'); break; } dom.barY.css(scrollbarYStyles); dom.sliderY[0].style.display = isYActive ? 'inherit' : 'none'; }, scrollTo = function (left, top) { // clamp to 0 .. content{Height|Width} - container{Height|Width} contentTop = clamp(top, 0, contentHeight - containerHeight); contentLeft = clamp(left, 0, contentWidth - containerWidth); if (config.updateContentPosition) { dom.content[0].style[xform] = 'translate3d(' + toPix(-contentLeft) + ',' + toPix(-contentTop) + ',0)'; } // update external scroll spies if (spySetter.spyX) { spySetter.spyX($scope, parseInt(contentLeft, 10)); } if (spySetter.spyY) { spySetter.spyY($scope, parseInt(contentTop, 10)); } if (spySetter.spyCustomContentHeight) { spySetter.spyCustomContentHeight($scope, parseInt(customContentHeight)); } if (spySetter.spyCustomContentWidth) { spySetter.spyCustomContentWidth($scope, parseInt(customContentWidth)); } }, scrollX = function (pos) { if (!isXActive) { return; } scrollTo(pos, contentTop); updateSliderX(); }, scrollY = function (pos) { if (!isYActive) { return; } scrollTo(contentLeft, pos); updateSliderY(); }, refresh = function (event, noNotify) { // read DOM containerWidth = config.usePadding ? dom.el[0].clientWidth : dom.el[0].offsetWidth; // innerWidth() : elm[0].width(); containerHeight = config.usePadding ? dom.el[0].clientHeight : dom.el[0].offsetHeight; // elm[0].innerHeight() : elm[0].height(); contentWidth = angular.isDefined(customContentWidth) ? customContentWidth : dom.content[0].scrollWidth; contentHeight = angular.isDefined(customContentHeight) ? customContentHeight : dom.content[0].scrollHeight; // activate scrollbars if (config.scrollX !== 'none' && containerWidth + config.scrollXSlackSpace < contentWidth) { isXActive = true; } else { isXActive = false; scrollX(0); } if (config.scrollY !== 'none' && containerHeight + config.scrollYSlackSpace < contentHeight) { isYActive = true; } else { isYActive = false; scrollY(0); } // update UI updateBarX(); updateBarY(); updateSliderX(); updateSliderY(); // broadcast the new dimensions down the scope stack so inner content // controllers can react appropriatly if (!noNotify) { $scope.$broadcast('scrollable.dimensions', containerWidth, containerHeight, contentWidth, contentHeight, config.id); } }, stop = function (e, prevent) { e.stopPropagation(); if (prevent) { e.preventDefault(); } return false; }, ypos = function (e) { e = e.originalEvent || e; // touch event if (e.targetTouches && (e.targetTouches.length >= 1)) { return e.targetTouches[0].pageY; } // mouse event return e.pageY; }, xpos = function (e) { e = e.originalEvent || e; // touch event if (e.targetTouches && (e.targetTouches.length >= 1)) { return e.targetTouches[0].pageX; } // mouse event return e.pageX; }, track = function () { var now, elapsed, delta, v; now = Date.now(); elapsed = now - trackTime; trackTime = now; // X delta = contentLeft - frameX; frameX = contentLeft; v = 1000 * delta / (1 + elapsed); velocityX = 0.8 * v + 0.2 * velocityX; // Y delta = contentTop - frameY; frameY = contentTop; v = 1000 * delta / (1 + elapsed); velocityY = 0.8 * v + 0.2 * velocityY; }, autoScrollX = function () { var elapsed, delta; if (amplitudeX) { elapsed = Date.now() - trackTime; delta = -amplitudeX * Math.exp(-elapsed / config.kineticTau); if (delta > 0.5 || delta < -0.5) { scrollX(targetX + delta); $$rAF(autoScrollX); } else { scrollX(targetX); } } }, autoScrollY = function () { var elapsed, delta; if (amplitudeY) { elapsed = Date.now() - trackTime; delta = -amplitudeY * Math.exp(-elapsed / config.kineticTau); if (delta > 0.5 || delta < -0.5) { scrollY(targetY + delta); $$rAF(autoScrollY); } else { scrollY(targetY); } } }, onMouseDownX = function (e) { dragStartPageX = xpos(e); dragStartLeft = contentLeft; isXScrolling = true; velocityX = amplitudeX = 0; frameX = contentLeft; if (!trackerTimeout) { trackerTimeout = $interval(track, 100); } dom.el.addClass('active'); return isTouchDevice || stop(e, !isTouchDevice); }, onMouseMoveX = function (e) { if (isXScrolling) { // scale slider move to content width var deltaSlider = xpos(e) - dragStartPageX, deltaContent = isTouchDevice ? -deltaSlider : parseInt(deltaSlider * (contentWidth - containerWidth) / (containerWidth - xSliderWidth), 10); scrollX(dragStartLeft + deltaContent); return isTouchDevice || stop(e, true); } }, onMouseUpX = function (e) { if (isXScrolling) { isXScrolling = false; dom.el.removeClass('active'); dragStartLeft = dragStartPageX = null; } // kinetic scroll if (config.enableKinetic) { if (trackerTimeout) { $interval.cancel(trackerTimeout); trackerTimeout = null; } if (velocityX > 10 || velocityX < -10) { amplitudeX = 0.8 * velocityX; targetX = Math.round(contentLeft + amplitudeX); trackTime = Date.now(); $$rAF(autoScrollX); } } return isTouchDevice || stop(e, !isTouchDevice); }, onMouseDownY = function (e) { dragStartPageY = ypos(e); dragStartTop = contentTop; isYScrolling = true; velocityY = amplitudeY = 0; frameY = contentTop; if (!trackerTimeout) { trackerTimeout = $interval(track, 100); } dom.el.addClass('active'); return isTouchDevice || stop(e, !isTouchDevice); }, onMouseMoveY = function (e) { if (isYScrolling) { var deltaSlider = ypos(e) - dragStartPageY, deltaContent = isTouchDevice ? -deltaSlider : parseInt(deltaSlider * (contentHeight - containerHeight) / (containerHeight - ySliderHeight), 10); scrollY(dragStartTop + deltaContent); return isTouchDevice || stop(e, true); } }, onMouseUpY = function (e) { if (isYScrolling) { isYScrolling = false; dom.el.removeClass('active'); dragStartTop = dragStartPageY = null; } // kinetic scroll if (config.enableKinetic) { if (trackerTimeout) { $interval.cancel(trackerTimeout); trackerTimeout = null; } if (velocityY > 10 || velocityY < -10) { amplitudeY = 0.8 * velocityY; targetY = Math.round(contentTop + amplitudeY); trackTime = Date.now(); $$rAF(autoScrollY); } } return isTouchDevice || stop(e, true); }, // Get Offset without jquery // element.prop('offsetTop') // element[0].getBoundingClientRect().top clickBarX = function (e) { var halfOfScrollbarLength = parseInt(xSliderWidth / 2, 10), positionLeft = e.clientX - dom.barX[0].getBoundingClientRect().left - halfOfScrollbarLength, maxPositionLeft = containerWidth - xSliderWidth, positionRatio = clamp(positionLeft / maxPositionLeft, 0, 1); scrollX((contentWidth - containerWidth) * positionRatio); $scope.$digest(); }, clickBarY = function (e) { var halfOfScrollbarLength = parseInt(ySliderHeight / 2, 10), positionTop = e.clientY - dom.barY[0].getBoundingClientRect().top - halfOfScrollbarLength, maxPositionTop = containerHeight - ySliderHeight, positionRatio = clamp(positionTop / maxPositionTop, 0, 1); scrollY((contentHeight - containerHeight) * positionRatio); $scope.$digest(); }, hoverOn = function () { hovered = true; }, hoverOff = function () { hovered = false; }, handleKey = function (e) { var deltaX = 0, deltaY = 0, s = 30; if (!hovered || $document[0].activeElement.isContentEditable || e.altKey || e.ctrlKey || e.metaKey) { return; } switch (e.which) { case 37: // left deltaX = -s; break; case 38: // up deltaY = s; break; case 39: // right deltaX = s; break; case 40: // down deltaY = -s; break; case 33: // page up deltaY = containerHeight; break; case 32: // space bar case 34: // page down deltaY = -containerHeight; break; case 35: // end if (isYActive && !isXActive) { deltaY = -contentHeight; } else { deltaX = containerHeight; } break; case 36: // home if (isYActive && !isXActive) { deltaY = contentHeight; } else { deltaX = -containerHeight; } break; default: return; } scrollY(contentTop - deltaY); scrollX(contentLeft + deltaX); // prevent default scrolling e.preventDefault(); $scope.$digest(); }, handleWheel = function (e) { // with jquery use e.originalEvent.deltaX!!! e = e.originalEvent || e; var deltaX = e.deltaX * config.wheelSpeed, deltaY = e.deltaY * config.wheelSpeed; // avoid flickering in Chrome: disabled animated translate dom.el.addClass('active'); $timeout.cancel(activeTimeout); activeTimeout = $timeout(function () {dom.el.removeClass('active'); }, 500); if (!config.useBothWheelAxes) { // deltaX will only be used for horizontal scrolling and deltaY will // only be used for vertical scrolling - this is the default scrollY(contentTop + deltaY); scrollX(contentLeft + deltaX); } else if (isYActive && !isXActive) { // only vertical scrollbar is active and useBothWheelAxes option is // active, so let's scroll vertical bar using both mouse wheel axes if (deltaY) { scrollY(contentTop + deltaY); } else { scrollY(contentTop + deltaX); } } else if (isXActive && !isYActive) { // useBothWheelAxes and only horizontal bar is active, so use both // wheel axes for horizontal bar if (deltaX) { scrollX(contentLeft + deltaX); } else { scrollX(contentLeft + deltaY); } } // prevent default scrolling stop(e, true); $scope.$digest(); }, registerHandlers = function () { // bind DOM element handlers if (config.updateOnResize) { dom.window.on('resize', refresh); } if (config.scrollX !== 'none') { // scrollbar clicks dom.sliderX.on('click', stop); dom.barX.on('click', clickBarX); if (isTouchDevice) { // content touch/drag dom.el.on('touchstart', onMouseDownX); dom.el.on('touchmove', onMouseMoveX); dom.el.on('touchend', onMouseUpX); } else { // slider drag dom.sliderX.on('mousedown', onMouseDownX); $document.on('mousemove', onMouseMoveX); $document.on('mouseup', onMouseUpX); } } if (config.scrollY !== 'none') { // scrollbar clicks dom.sliderY.on('click', stop); dom.barY.on('click', clickBarY); if (isTouchDevice) { // content touch/drag dom.el.on('touchstart', onMouseDownY); dom.el.on('touchmove', onMouseMoveY); dom.el.on('touchend', onMouseUpY); } else { // slider drag dom.sliderY.on('mousedown', onMouseDownY); $document.on('mousemove', onMouseMoveY); $document.on('mouseup', onMouseUpY); } } // mouse wheel if (!isTouchDevice) { dom.el.on('wheel', handleWheel); } // keyboard if (config.useKeyboard && !isTouchDevice) { dom.el.on('mouseenter', hoverOn); dom.el.on('mouseleave', hoverOff); $document.on('keydown', handleKey); } }, unregisterHandlers = function () { if (config.updateOnResize) { dom.window.off('resize', refresh); } dom.sliderX.off('click', stop); dom.barX.off('click', clickBarX); dom.sliderY.off('click', stop); dom.barY.off('click', clickBarY); // touch if (isTouchDevice) { dom.el.off('touchstart', onMouseDownX); dom.el.off('touchmove', onMouseMoveX); dom.el.off('touchend', onMouseUpX); dom.el.off('touchstart', onMouseDownY); dom.el.off('touchmove', onMouseMoveY); dom.el.off('touchend', onMouseUpY); } else { // slider drag dom.sliderX.off('mousedown', onMouseDownX); $document.off('mousemove', onMouseMoveX); $document.off('mouseup', onMouseUpX); dom.sliderY.off('mousedown', onMouseDownY); $document.off('mousemove', onMouseMoveY); $document.off('mouseup', onMouseUpY); // keyboard if (config.useKeyboard) { // mouse hovering activates keyboard capture dom.el.off('mouseenter', hoverOn); dom.el.off('mouseleave', hoverOff); $document.off('keydown', handleKey); } // mouse wheel dom.el.off('wheel', handleWheel); } }; $scope.$on('content.reload', function (e, noNotify) { // try unregistering event handlers unregisterHandlers(); // defer to next digest $timeout(function () { // update DOM node reference (because ui-view replaces nodes) dom.el = element(elem.children()[0]); dom.content = element(dom.el.children()[0]); // register handlers registerHandlers(); // refresh scrollbars refresh(e, noNotify); }); }); // sent by controllers of transcluded content on change $scope.$on('content.changed', function (e, wait, noNotify) { // ms to wait before refresh wait = wait || 100; // defer to next digest $timeout(function () { // refresh scrollbars refresh(e, noNotify); }, wait); e.preventDefault(); }); // may be broadcast from outside to scroll to content edges $scope.$on('scrollable.scroll.left', function () { // defer to next digest $scope.$applyAsync(function () { scrollX(0); }); }); $scope.$on('scrollable.scroll.right', function () { // defer to next digest $scope.$applyAsync(function () { scrollX(contentWidth); }); }); $scope.$on('scrollable.scroll.top', function () { // defer to next digest $scope.$applyAsync(function () { scrollY(0); }); }); $scope.$on('scrollable.scroll.bottom', function () { // defer to next digest $scope.$applyAsync(function () { scrollY(contentHeight); }); }); // (un)register event handlers on scope destroy $scope.$on('$destroy', function () { $timeout.cancel(activeTimeout); unregisterHandlers(); }); // init registerHandlers(); refresh(); // watch and set spy attribute value expressions angular.forEach(['spyX', 'spyY', 'spyCustomContentHeight', 'spyCustomContentWidth'], function (attr) { if (attrs[attr]) { // keep a setter to the spy expression (if settable) spySetter[attr] = $parse(attrs[attr]).assign; // watch the spy expression $scope.$watch(attrs[attr], function (val) { switch (attr) { case 'spyX' : scrollX(val); break; case 'spyY' : scrollY(val); break; case 'spyCustomContentHeight' : customContentHeight = val; refresh(null, null); break; case 'spyCustomContentWidth' : customContentWidth = val; refresh(null, null); break; } }); } }); } }; } ]);
/* global jasmine, describe, beforeEach, it, expect, require */ define(["wall"], function(wall) { describe("Wall ViewModel definitions.", function() { "use strict"; var a = wall; describe("Wall definitions.", function() { it("should define requests", function() { expect(a.requests).toBeDefined(); expect(a.requests).toEqual(jasmine.any(Array)); }); it("should define primus", function() { expect(a.primus).toBeDefined(); }); it("should define isConnected", function() { expect(a.isConnected).toBeDefined(); }); it("should define isMeetingActive", function() { expect(a.isMeetingActive).toBeDefined(); }); it("should define activate as a Function", function() { expect(a.activate).toBeDefined(); expect(a.activate).toEqual(jasmine.any(Function)); }); it("should define initializeMessage as a Function", function() { expect(a.initializeMessage).toBeDefined(); expect(a.initializeMessage).toEqual(jasmine.any(Function)); }); it("should define meetingMessage as a Function", function() { expect(a.meetingMessage).toBeDefined(); expect(a.meetingMessage).toEqual(jasmine.any(Function)); }); it("should define refreshMessage as a Function", function() { expect(a.refreshMessage).toBeDefined(); expect(a.refreshMessage).toEqual(jasmine.any(Function)); }); }); }); });
'use strict'; module.exports = { db: 'mongodb://localhost/mean-test-dev', app: { title: 'mean-test - Development Environment' }, facebook: { clientID: process.env.FACEBOOK_ID || 'APP_ID', clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET', callbackURL: '/auth/facebook/callback' }, twitter: { clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY', clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET', callbackURL: '/auth/twitter/callback' }, google: { clientID: process.env.GOOGLE_ID || 'APP_ID', clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET', callbackURL: '/auth/google/callback' }, linkedin: { clientID: process.env.LINKEDIN_ID || 'APP_ID', clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET', callbackURL: '/auth/linkedin/callback' }, github: { clientID: process.env.GITHUB_ID || 'APP_ID', clientSecret: process.env.GITHUB_SECRET || 'APP_SECRET', callbackURL: '/auth/github/callback' }, mailer: { from: process.env.MAILER_FROM || 'MAILER_FROM', options: { service: process.env.MAILER_SERVICE_PROVIDER || 'MAILER_SERVICE_PROVIDER', auth: { user: process.env.MAILER_EMAIL_ID || 'MAILER_EMAIL_ID', pass: process.env.MAILER_PASSWORD || 'MAILER_PASSWORD' } } } };
app.controller('UserController', ['$scope', '$rootScope', '$timeout', '$http', '$cookieStore', 'ServiceConfig', 'MenuSelect', function($scope, $rootScope, $timeout, $http, $cookieStore, ServiceConfig, MenuSelect) { var user = $cookieStore.get('user'); var width = window.innerWidth; MenuSelect.setSelected('select_user'); //分页 $scope.mySelections = []; $scope.filterOptions = { filterText: "", useExternalFilter: true }; $scope.totalServerItems = 0; $scope.pagingOptions = { pageSizes: [10, 15, 30], pageSize: 10, currentPage: 1 }; $scope.setPagingData = function(data, page, pageSize){ var pagedData = data.slice((page - 1) * pageSize, page * pageSize); $scope.myData = pagedData; $scope.totalServerItems = data.length; if (!$scope.$$phase) { $scope.$apply(); } }; $scope.getPagedDataAsync = function (pageSize, page) { setTimeout(function () { $http.get(ServiceConfig.user_getAll + '?token=' + user.token).success(function (data) { if(data.status){ $scope.setPagingData(data.items, page, pageSize); } }); }, 100); }; $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage); $scope.$watch('pagingOptions', function (newVal, oldVal) { if (newVal !== oldVal && newVal.currentPage !== oldVal.currentPage) { $scope.getPagedDataAsync($scope.pagingOptions.pageSize, $scope.pagingOptions.currentPage); } }, true); $scope.$on('ngGridEventEndCellEdit', function(evt){ var obj = evt.targetScope.row.entity; var data = { userid: obj.userid, token: user.token, tag: obj.tag }; $http.post(ServiceConfig.user_updateTag, data).success(function(data){ if(!data.status){ Tip.setTip(250, (parseInt(width) - 240) / 2, null, null, 260, 80, '数据更新失败', 1); $timeout(Tip.hideTip, 3000); } }); }); $scope.removeRow = function(entity){ //确认提示框 //alert('确定删除'); var data = { token: user.token, userid: entity.userid }; console.log(ServiceConfig.user_delete); $http.post(ServiceConfig.user_delete, data).success(function(data){ if(data.status){ Tip.setTip(250, (parseInt(width) - 240) / 2, null, null, 260, 80, '删除成功......', 1); $timeout(Tip.hideTip, 3000); }else{ Tip.setTip(250, (parseInt(width) - 240) / 2, null, null, 260, 80, '删除失败......', 1); $timeout(Tip.hideTip, 3000); } }); }; $scope.gridOptions = { data: 'myData', enablePaging: true, showFooter: true, enableCellEdit: true, totalServerItems: 'totalServerItems', pagingOptions: $scope.pagingOptions, multiSelect: false, selectedItems: $scope.mySelections, columnDefs: [ {field:'userid', displayName:'用户ID'}, {field:'email', displayName:'邮箱'}, {field:'tag', displayName:'角色'}, {field:'nickname', displayName:'昵称'}, {field:'realname', displayName:'真实姓名'}, {field:'tel', displayName:'电话'}, { field: '慎重操作', cellTemplate: '<button class="user_btn" ng-click="removeRow(row.entity)">删除</button>' } ] }; //搜索 $scope.Search = function($event, choose, keywords){ if($event.keyCode === 13 || $event.which === 32){ var condition = '?token=' + user.token + '&'; var choose = choose || 'default'; switch(choose){ case 'email': condition = condition + 'email=' + keywords; break; case 'nickname': condition = condition + 'nickname=' + keywords; break; case 'realname': condition = condition + 'realname=' + keywords; break; default: console.log(keywords); condition = condition + 'email=' + keywords; break; } $http.get(ServiceConfig.user_getUserByCondition + condition).success(function(data){ if(data.status){ $scope.mySelections = data.items; //后期做一个弹出框,让用户自己选择查询到的用户,然后进行显示 //或者展示出所有的用户信息 }else{ } }); } }; }]);
angular .module('starter') .controller('settings', function ($scope, $http, Weather, WeatherData, Settings, LocalStorage) { $scope.scale = !localStorage.scale ? Settings.scale : localStorage.scale $scope.precision = !localStorage.precision ? Settings.precision : localStorage.precision $scope.randomScale = function () { $ionicLoading.show({ template: '<img src="img/whathappening.gif">', duration: 5000 }) } $scope.precisionChanged = function () { console.log($scope.precision) } $scope.$watch('scale', function() { LocalStorage.storeScale($scope.scale) }) $scope.$watch('precision', function() { LocalStorage.storePrecision($scope.precision) }) })
async (x = function f(x = class { [await] }){}) => {}
import * as d3 from 'd3'; import jquery from 'jquery'; import moment from 'moment'; window.d3 = d3; var windowWidth = window.innerWidth, windowHeight = window.innerHeight; var container = d3.select("#background-shapes"); var mouse = [windowWidth/2, windowHeight/2]; var total = 20; var colorScale = d3.scaleLinear() .domain([0, total]).range([.3, 1]); var color = (index) => { console.log('color ', index, d3.interpolateRainbow(colorScale(index))); return d3.interpolateRainbow(colorScale(index)); }; // var color = d3.scaleLinear() // .domain([0, total]) // .range(["blue", "orange"]); var pathColorScale = d3.scaleLinear().domain([total, 0]).range([.3, 1]); var pathColor = (index) => { return d3.interpolateRainbow(pathColorScale(index)); }; // var pathColor = d3.scaleLinear() // .domain([total, 0]) // .range(["blue", "orange"]); var tileSize = 100; var svgWrappers = container.selectAll("div") .data(d3.range(total)) .enter().append("div") .attr('class', 'svg-wrapper'); var svgs = svgWrappers.append("svg") .attr('viewBox', '0 0 100 100') // .attr("width", tileSize) // .attr("height", tileSize) .attr("transform", function(d, i) { return `translate(${mouse})`; }) var center = tileSize / 2; svgs.append("g") // .style("fill", (d, i) => { return color(i); }) var g = svgs.selectAll('g'); g.append("rect") .attr("x", 0) .attr("y", 0) .attr("width", tileSize) .attr("height", tileSize) .style("fill", (d, i) => { return color(d); }) // .style('fill', '#fff'); g.datum(function(d) { return { center: mouse.slice(), angle: 0}; }); var pointOptions = [0, tileSize/2, tileSize]; var getRandomPointValue = function(){ var rand = Math.random(); rand *= pointOptions.length; rand = Math.floor(rand); return pointOptions[rand]; } var lineData = []; for (var i = 0; i < total; i++){ var point1 = [getRandomPointValue(), getRandomPointValue()], point2 = [getRandomPointValue(), getRandomPointValue()], point3 = [getRandomPointValue(), getRandomPointValue()]; lineData.push([ point1, point2, point3 ]); } var line = d3.line() .curve(d3.curveCatmullRom.alpha(0.5)) console.log('range', d3.range(total)); var pathCounter = -1; g.append('path') .data(d3.range(total)) .attr("d", function(d, i){ var point1 = [getRandomPointValue(), getRandomPointValue()], point2 = [getRandomPointValue(), getRandomPointValue()], point3 = [getRandomPointValue(), getRandomPointValue()], point4 = [getRandomPointValue(), getRandomPointValue()]; var d = [ point1, point2, point3, // point4 ]; return line(d); }) .style("fill", (d, i) => { console.log('line d, i', d, i); pathCounter++; return pathColor(pathCounter); }) // .style('fill', '#fff'); container.on("mousemove", function() { mouse = d3.mouse(this); }); d3.timer(function() { // g.attr("transform", function(d, i) { // d.center[0] += (mouse[0] - d.center[0]) / (i + 5); // d.center[1] += (mouse[1] - d.center[1]) / (i + 5); // return "translate(" + d.center + ")"; // }); });
(function () { var Ext = window.Ext4 || window.Ext; Ext.define('Rally.apps.common.PortfolioItemsGridBoardApp', { extend: 'Rally.app.GridBoardApp', requires: [ 'Rally.data.Ranker', 'Rally.ui.cardboard.plugin.CollapsibleColumns', 'Rally.ui.cardboard.plugin.FixedHeader', 'Rally.ui.gridboard.plugin.GridBoardInlineFilterControl', 'Rally.ui.gridboard.plugin.GridBoardSharedViewControl', 'Rally.ui.notify.Notifier' ], constructor: function(config){ var defaultConfig = { piTypePickerConfig: { renderInGridHeader: false } }; this.callParent([Ext.Object.merge(defaultConfig, config)]); }, initComponent: function(){ this.callParent(arguments); this.addCls('portfolio-items-grid-board-app'); }, getAddNewConfig: function () { var config = {}; if (this.getContext().isFeatureEnabled('S105843_UPGRADE_TO_NEWEST_FILTERING_SHARED_VIEWS_ON_PORTFOLIO_ITEMS_AND_KANBAN')) { config.margin = 0; } return _.merge(this.callParent(arguments), config); }, addGridBoard: function(){ if (this.gridboard && this.piTypePicker && this.piTypePicker.rendered) { var parent = this.piTypePicker.up(); if(parent && parent.remove){ parent.remove(this.piTypePicker, false); } } this.callParent(arguments); }, launch: function () { if (Rally.environment.getContext().getSubscription().isModuleEnabled('Rally Portfolio Manager')) { this.callParent(arguments); } else { this.add({ xtype: 'container', html: '<div class="rpm-turned-off" style="padding: 50px; text-align: center;">You do not have RPM enabled for your subscription</div>' }); this.publishComponentReady(); } }, loadModelNames: function () { return this._createPITypePicker().then({ success: function (selectedType) { this.currentType = selectedType; return [selectedType.get('TypePath')]; }, scope: this }); }, getGridBoardCustomFilterControlConfig: function () { var context = this.getContext(), skinnyFilter = !!context.isFeatureEnabled('F10466_INLINE_FILTER_UI_ENHANCEMENTS'); if (context.isFeatureEnabled('S105843_UPGRADE_TO_NEWEST_FILTERING_SHARED_VIEWS_ON_PORTFOLIO_ITEMS_AND_KANBAN')) { return { ptype: 'rallygridboardinlinefiltercontrol', inline: skinnyFilter, skinny: skinnyFilter, inlineFilterButtonConfig: { stateful: true, stateId: context.getScopedStateId('portfolio-items-inline-filter'), legacyStateIds: [ this.getScopedStateId('owner-filter'), this.getScopedStateId('custom-filter-button') ], filterChildren: true, modelNames: this.modelNames, inlineFilterPanelConfig: { quickFilterPanelConfig: { defaultFields: [ 'ArtifactSearch', 'Owner' ], addQuickFilterConfig: { blackListFields: ['PortfolioItemType', 'ModelType'], whiteListFields: ['Milestones', 'Tags'] } }, advancedFilterPanelConfig: { advancedFilterRowsConfig: { propertyFieldConfig: { blackListFields: ['PortfolioItemType'], whiteListFields: ['Milestones', 'Tags'] } } } } } }; } return { blackListFields: ['PortfolioItemType'], whiteListFields: ['Milestones'] }; }, getSharedViewConfig: function() { var context = this.getContext(); if (context.isFeatureEnabled('S105843_UPGRADE_TO_NEWEST_FILTERING_SHARED_VIEWS_ON_PORTFOLIO_ITEMS_AND_KANBAN')) { return { ptype: 'rallygridboardsharedviewcontrol', sharedViewConfig: { stateful: true, stateId: this.getContext().getScopedStateId('portfolio-items-shared-view'), defaultViews: _.map(this._getDefaultViews(), function (view) { Ext.apply(view, { Value: Ext.JSON.encode(view.Value, true) }); return view; }, this), enableUrlSharing: this.isFullPageApp !== false, suppressViewNotFoundNotification: this._suppressViewNotFoundNotification }, additionalFilters: [{ property: 'Value', operator: 'contains', value: '"piTypePicker":"' + this.piTypePicker.getRecord().get('_refObjectUUID') + '"' }] }; } return {}; }, getFieldPickerConfig: function () { return _.merge(this.callParent(arguments), { boardFieldBlackList: ['Predecessors', 'Successors'] }); }, getGridBoardConfig: function () { return _.merge(this.callParent(arguments), { listeners: { viewchange: this._onViewChange, scope: this }, sharedViewAdditionalCmps: [this.piTypePicker] }); }, getCardBoardColumns: function () { return this._getStates().then({ success: function (states) { return this._buildColumns(states); }, scope: this }); }, _buildColumns: function (states) { if (!states.length) { return undefined; } var columns = [ { columnHeaderConfig: { headerTpl: 'No Entry' }, value: null, plugins: ['rallycardboardcollapsiblecolumns'].concat(this.getCardBoardColumnPlugins(null)) } ]; return columns.concat(_.map(states, function (state) { return { value: state.get('_ref'), wipLimit: state.get('WIPLimit'), enableWipLimit: true, columnHeaderConfig: { record: state, fieldToDisplay: 'Name', editable: false }, plugins: ['rallycardboardcollapsiblecolumns'].concat(this.getCardBoardColumnPlugins(state)) }; }, this)); }, _getStates: function () { var deferred = new Deft.Deferred(); Ext.create('Rally.data.wsapi.Store', { model: Ext.identityFn('State'), context: this.getContext().getDataContext(), autoLoad: true, fetch: ['Name', 'WIPLimit', 'Description'], filters: [ { property: 'TypeDef', value: this.currentType.get('_ref') }, { property: 'Enabled', value: true } ], sorters: [ { property: 'OrderIndex', direction: 'ASC' } ], listeners: { load: function (store, records) { deferred.resolve(records); } } }); return deferred.promise; }, _getDefaultViews: function() { if (this.toggleState === 'grid'){ var rankColumnDataIndex = this.getContext().getWorkspace().WorkspaceConfiguration.DragDropRankingEnabled ? Rally.data.Ranker.RANK_FIELDS.DND : Rally.data.Ranker.RANK_FIELDS.MANUAL, defaultViewName = this.piTypePicker.getRawValue() + ' Default', columns = [ { dataIndex: rankColumnDataIndex}, { dataIndex: 'Name'}, { dataIndex: 'State'}, { dataIndex: 'PercentDoneByStoryCount'}, { dataIndex: 'PlannedStartDate'}, { dataIndex: 'PlannedEndDate'}, { dataIndex: 'Project'} ], ordinalValue = this.piTypePicker.getRecord().get('Ordinal') + 1; if (ordinalValue === 1) { columns.push({ dataIndex: 'Release'}); } return [{ Name: defaultViewName, identifier: ordinalValue, Value: { toggleState: 'grid', columns: columns, sorters:[{ property: rankColumnDataIndex, direction: 'ASC'}] } }]; } return []; }, getCardBoardColumnPlugins: function (state) { return []; }, getCardConfig: function () { return {}; }, getCardBoardConfig: function (options) { options = options || {}; var currentTypePath = this.currentType.get('TypePath'); var filters = []; if (this.getSetting('query')) { try { filters.push(Rally.data.QueryFilter.fromQueryString(this.getSetting('query'))); } catch (e) { Rally.ui.notify.Notifier.showError({ message: e.message }); } } return { attribute: 'State', cardConfig: _.merge({ editable: true, showColorIcon: true }, this.getCardConfig()), columnConfig: { xtype: 'rallycardboardcolumn', enableWipLimit: true, fields: (this.getSetting('fields') || '').split(',') }, columns: options.columns, ddGroup: currentTypePath, listeners: { load: this.publishComponentReady, cardupdated: this._publishContentUpdatedNoDashboardLayout, scope: this }, plugins: [{ ptype: 'rallyfixedheadercardboard' }], storeConfig: { filters: filters, context: this.getContext().getDataContext() } }; }, getGridStoreConfig: function () { return _.merge({}, this.gridStoreConfig, { models: this.piTypePicker.getAllTypeNames() }); }, _createPITypePicker: function () { if (this.piTypePicker && this.piTypePicker.destroy) { this.piTypePicker.destroy(); } var deferred = new Deft.Deferred(); var piTypePickerConfig = { preferenceName: this.getStateId('typepicker'), fieldLabel: '', // delete this when removing PORTFOLIO_ITEM_TREE_GRID_PAGE_OPT_IN toggle. Can't delete these from PI Combobox right now or GUI tests fail in old PI page labelWidth: 0, // delete this when removing PORTFOLIO_ITEM_TREE_GRID_PAGE_OPT_IN toggle. Can't delete these from PI Combobox right now or GUI tests fail in old PI page value: this.getSetting('type'), context: this.getContext(), listeners: { change: this._onTypeChange, ready: { fn: function (picker) { deferred.resolve(picker.getSelectedType()); }, single: true }, scope: this } }; if(!this.config.piTypePickerConfig.renderInGridHeader){ piTypePickerConfig.renderTo = Ext.query('#content .titlebar .dashboard-timebox-container')[0]; } this.piTypePicker = Ext.create('Rally.ui.combobox.PortfolioItemTypeComboBox', piTypePickerConfig); if(this.config.piTypePickerConfig.renderInGridHeader){ this.on('gridboardadded', function() { var headerContainer = this.gridboard.getHeader().getLeft(); headerContainer.add(this.piTypePicker); }); } return deferred.promise; }, _onTypeChange: function (picker) { Rally.ui.notify.Notifier.hide(); var newType = picker.getSelectedType(); if (this._pickerTypeChanged(picker)) { this._suppressViewNotFoundNotificationWhenPiTypeChanges(); this.currentType = newType; this.modelNames = [newType.get('TypePath')]; this.gridboard.fireEvent('modeltypeschange', this.gridboard, [newType]); } }, _suppressViewNotFoundNotificationWhenPiTypeChanges: function() { var plugin = _.find(this.gridboard.plugins, {ptype: 'rallygridboardsharedviewcontrol'}); if (plugin && plugin.controlCmp && plugin.controlCmp.getSharedViewParam()){ this._suppressViewNotFoundNotification = true; } }, _onViewChange: function() { Rally.ui.notify.Notifier.hide(); this.loadGridBoard(); }, _pickerTypeChanged: function(picker){ var newType = picker.getSelectedType(); return newType && this.currentType && newType.get('_ref') !== this.currentType.get('_ref'); }, _publishContentUpdatedNoDashboardLayout: function () { this.fireEvent('contentupdated', { dashboardLayout: false }); }, onDestroy: function() { this.callParent(arguments); if(this.piTypePicker) { this.piTypePicker.destroy(); delete this.piTypePicker; } } }); })();
import { Observable } from 'rxjs'; import { bufferToggle } from '../../operator/bufferToggle'; Observable.prototype.bufferToggle = bufferToggle; //# sourceMappingURL=bufferToggle.js.map
define( 'amd/combineplugin/cat', function ( require ) { return { name: 'amd/combineplugin/cat' }; } ); define( 'plugin/html2', { load: function ( resourceId, req, load, config ) { var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { load( xhr.responseText ); } }; xhr.open('GET', req.toUrl( resourceId + '.html' ), true); xhr.send(null); } } ); define( 'amd/combineplugin/index', ['amd/combineplugin/cat', 'amd/combineplugin/cat!plugin/resource'], function ( cat, resource ) { return { name: 'amd/combineplugin/index', check: function () { var valid = cat.name == 'amd/combineplugin/cat' && resource == 'plugin/html!plugin/resource' return valid; } }; } );
{ "AD" : "n. e", "Africa/Abidjan_Z_abbreviated" : "(CI)", "Africa/Abidjan_Z_short" : "GMT", "Africa/Accra_Z_abbreviated" : "(GH)", "Africa/Accra_Z_short" : "GMT", "Africa/Addis_Ababa_Z_abbreviated" : "(ET)", "Africa/Addis_Ababa_Z_short" : "EAT", "Africa/Algiers_Z_abbreviated" : "(DZ)", "Africa/Algiers_Z_short" : "WET", "Africa/Asmara_Z_abbreviated" : "(ER)", "Africa/Asmara_Z_short" : "EAT", "Africa/Bamako_Z_abbreviated" : "(ML)", "Africa/Bamako_Z_short" : "GMT", "Africa/Bangui_Z_abbreviated" : "(CF)", "Africa/Bangui_Z_short" : "WAT", "Africa/Banjul_Z_abbreviated" : "(GM)", "Africa/Banjul_Z_short" : "GMT", "Africa/Bissau_Z_abbreviated" : "(GW)", "Africa/Bissau_Z_short" : "GMT-0100", "Africa/Blantyre_Z_abbreviated" : "(MW)", "Africa/Blantyre_Z_short" : "CAT", "Africa/Brazzaville_Z_abbreviated" : "(CG)", "Africa/Brazzaville_Z_short" : "WAT", "Africa/Bujumbura_Z_abbreviated" : "(BI)", "Africa/Bujumbura_Z_short" : "CAT", "Africa/Cairo_Z_abbreviated" : "(EG)", "Africa/Cairo_Z_short" : "EET", "Africa/Casablanca_Z_abbreviated" : "(MA)", "Africa/Casablanca_Z_short" : "WET", "Africa/Conakry_Z_abbreviated" : "(GN)", "Africa/Conakry_Z_short" : "GMT", "Africa/Dakar_Z_abbreviated" : "(SN)", "Africa/Dakar_Z_short" : "GMT", "Africa/Dar_es_Salaam_Z_abbreviated" : "(TZ)", "Africa/Dar_es_Salaam_Z_short" : "EAT", "Africa/Djibouti_Z_abbreviated" : "(DJ)", "Africa/Djibouti_Z_short" : "EAT", "Africa/Douala_Z_abbreviated" : "(CM)", "Africa/Douala_Z_short" : "WAT", "Africa/El_Aaiun_Z_abbreviated" : "(EH)", "Africa/El_Aaiun_Z_short" : "GMT-0100", "Africa/Freetown_Z_abbreviated" : "(SL)", "Africa/Freetown_Z_short" : "GMT", "Africa/Gaborone_Z_abbreviated" : "(BW)", "Africa/Gaborone_Z_short" : "CAT", "Africa/Harare_Z_abbreviated" : "(ZW)", "Africa/Harare_Z_short" : "CAT", "Africa/Johannesburg_Z_abbreviated" : "(ZA)", "Africa/Johannesburg_Z_short" : "SAST", "Africa/Juba_Z_abbreviated" : "(SD)", "Africa/Juba_Z_short" : "CAT", "Africa/Kampala_Z_abbreviated" : "(UG)", "Africa/Kampala_Z_short" : "EAT", "Africa/Khartoum_Z_abbreviated" : "(SD)", "Africa/Khartoum_Z_short" : "CAT", "Africa/Kigali_Z_abbreviated" : "(RW)", "Africa/Kigali_Z_short" : "CAT", "Africa/Kinshasa_Z_abbreviated" : "CD (Kinšasa)", "Africa/Kinshasa_Z_short" : "WAT", "Africa/Lagos_Z_abbreviated" : "(NG)", "Africa/Lagos_Z_short" : "WAT", "Africa/Libreville_Z_abbreviated" : "(GA)", "Africa/Libreville_Z_short" : "WAT", "Africa/Lome_Z_abbreviated" : "(TG)", "Africa/Lome_Z_short" : "GMT", "Africa/Luanda_Z_abbreviated" : "(AO)", "Africa/Luanda_Z_short" : "WAT", "Africa/Lusaka_Z_abbreviated" : "(ZM)", "Africa/Lusaka_Z_short" : "CAT", "Africa/Malabo_Z_abbreviated" : "(GQ)", "Africa/Malabo_Z_short" : "WAT", "Africa/Maputo_Z_abbreviated" : "(MZ)", "Africa/Maputo_Z_short" : "CAT", "Africa/Maseru_Z_abbreviated" : "(LS)", "Africa/Maseru_Z_short" : "SAST", "Africa/Mbabane_Z_abbreviated" : "(SZ)", "Africa/Mbabane_Z_short" : "SAST", "Africa/Mogadishu_Z_abbreviated" : "(SO)", "Africa/Mogadishu_Z_short" : "EAT", "Africa/Monrovia_Z_abbreviated" : "(LR)", "Africa/Monrovia_Z_short" : "GMT-004430", "Africa/Nairobi_Z_abbreviated" : "(KE)", "Africa/Nairobi_Z_short" : "EAT", "Africa/Ndjamena_Z_abbreviated" : "(TD)", "Africa/Ndjamena_Z_short" : "WAT", "Africa/Niamey_Z_abbreviated" : "(NE)", "Africa/Niamey_Z_short" : "WAT", "Africa/Nouakchott_Z_abbreviated" : "(MR)", "Africa/Nouakchott_Z_short" : "GMT", "Africa/Ouagadougou_Z_abbreviated" : "(BF)", "Africa/Ouagadougou_Z_short" : "GMT", "Africa/Porto-Novo_Z_abbreviated" : "(BJ)", "Africa/Porto-Novo_Z_short" : "WAT", "Africa/Sao_Tome_Z_abbreviated" : "(ST)", "Africa/Sao_Tome_Z_short" : "GMT", "Africa/Tripoli_Z_abbreviated" : "(LY)", "Africa/Tripoli_Z_short" : "EET", "Africa/Tunis_Z_abbreviated" : "(TN)", "Africa/Tunis_Z_short" : "CET", "Africa/Windhoek_Z_abbreviated" : "(NA)", "Africa/Windhoek_Z_short" : "SAST", "America/Anguilla_Z_abbreviated" : "(AI)", "America/Anguilla_Z_short" : "AST", "America/Antigua_Z_abbreviated" : "(AG)", "America/Antigua_Z_short" : "AST", "America/Araguaina_Z_abbreviated" : "BR (Aragvajana)", "America/Araguaina_Z_short" : "BRT", "America/Argentina/Buenos_Aires_Z_abbreviated" : "AR (Buenos Aires)", "America/Argentina/Buenos_Aires_Z_short" : "ART", "America/Argentina/Catamarca_Z_abbreviated" : "AR (Katamarka (Argentina))", "America/Argentina/Catamarca_Z_short" : "ART", "America/Argentina/Cordoba_Z_abbreviated" : "AR (Kordoba (Argentina))", "America/Argentina/Cordoba_Z_short" : "ART", "America/Argentina/Jujuy_Z_abbreviated" : "AR (Jujui)", "America/Argentina/Jujuy_Z_short" : "ART", "America/Argentina/La_Rioja_Z_abbreviated" : "AR (La Rioja)", "America/Argentina/La_Rioja_Z_short" : "ART", "America/Argentina/Mendoza_Z_abbreviated" : "AR (Mendoza (Argentina))", "America/Argentina/Mendoza_Z_short" : "ART", "America/Argentina/Rio_Gallegos_Z_abbreviated" : "AR (Rio galegos)", "America/Argentina/Rio_Gallegos_Z_short" : "ART", "America/Argentina/Salta_Z_abbreviated" : "AR (Salta)", "America/Argentina/Salta_Z_short" : "ART", "America/Argentina/San_Juan_Z_abbreviated" : "AR (San Huan (Argentina))", "America/Argentina/San_Juan_Z_short" : "ART", "America/Argentina/San_Luis_Z_abbreviated" : "AR (San Luis)", "America/Argentina/San_Luis_Z_short" : "ART", "America/Argentina/Tucuman_Z_abbreviated" : "AR (Tukuman)", "America/Argentina/Tucuman_Z_short" : "ART", "America/Argentina/Ushuaia_Z_abbreviated" : "AR (Ušuaia)", "America/Argentina/Ushuaia_Z_short" : "ART", "America/Aruba_Z_abbreviated" : "(AW)", "America/Aruba_Z_short" : "AST", "America/Asuncion_Z_abbreviated" : "(PY)", "America/Asuncion_Z_short" : "PYT", "America/Bahia_Banderas_Z_abbreviated" : "MX (Bahia Banderas)", "America/Bahia_Banderas_Z_short" : "PST (SAD)", "America/Bahia_Z_abbreviated" : "BR (Bahia (Brazil))", "America/Bahia_Z_short" : "BRT", "America/Barbados_Z_abbreviated" : "(BB)", "America/Barbados_Z_short" : "AST", "America/Belem_Z_abbreviated" : "BR (Belem)", "America/Belem_Z_short" : "BRT", "America/Belize_Z_abbreviated" : "(BZ)", "America/Belize_Z_short" : "CST (SAD)", "America/Blanc-Sablon_Z_abbreviated" : "CA (Blanc-Sejblon (kanada))", "America/Blanc-Sablon_Z_short" : "AST", "America/Boa_Vista_Z_abbreviated" : "BR (Boa Vista)", "America/Boa_Vista_Z_short" : "AMT", "America/Bogota_Z_abbreviated" : "(CO)", "America/Bogota_Z_short" : "COT", "America/Boise_Z_abbreviated" : "US (Bojzi (SAD))", "America/Boise_Z_short" : "MST (SAD)", "America/Cambridge_Bay_Z_abbreviated" : "CA (Kembridž Bej (Kanada))", "America/Cambridge_Bay_Z_short" : "MST (SAD)", "America/Campo_Grande_Z_abbreviated" : "BR (Kampo Grande)", "America/Campo_Grande_Z_short" : "AMT", "America/Cancun_Z_abbreviated" : "MX (Kankun (Meksiko))", "America/Cancun_Z_short" : "CST (SAD)", "America/Caracas_Z_abbreviated" : "(VE)", "America/Caracas_Z_short" : "VET", "America/Cayenne_Z_abbreviated" : "(GF)", "America/Cayenne_Z_short" : "GFT", "America/Cayman_Z_abbreviated" : "(KY)", "America/Cayman_Z_short" : "EST (SAD)", "America/Chicago_Z_abbreviated" : "US (Čikago (SAD))", "America/Chicago_Z_short" : "CST (SAD)", "America/Chihuahua_Z_abbreviated" : "MX (Čihuahua (Meksiko))", "America/Chihuahua_Z_short" : "CST (SAD)", "America/Costa_Rica_Z_abbreviated" : "(CR)", "America/Costa_Rica_Z_short" : "CST (SAD)", "America/Cuiaba_Z_abbreviated" : "BR (Kuiaba)", "America/Cuiaba_Z_short" : "AMT", "America/Curacao_Z_abbreviated" : "(AN)", "America/Curacao_Z_short" : "AST", "America/Danmarkshavn_Z_abbreviated" : "GL (Danmarkšavn)", "America/Danmarkshavn_Z_short" : "WGT", "America/Denver_Z_abbreviated" : "US (Denver (SAD))", "America/Denver_Z_short" : "MST (SAD)", "America/Detroit_Z_abbreviated" : "US (Detroit (SAD))", "America/Detroit_Z_short" : "EST (SAD)", "America/Dominica_Z_abbreviated" : "(DM)", "America/Dominica_Z_short" : "AST", "America/Edmonton_Z_abbreviated" : "CA (Edmonton (Kanada))", "America/Edmonton_Z_short" : "MST (SAD)", "America/Eirunepe_Z_abbreviated" : "BR (Eirunepe (Brazil))", "America/Eirunepe_Z_short" : "ACT (Acre)", "America/El_Salvador_Z_abbreviated" : "(SV)", "America/El_Salvador_Z_short" : "CST (SAD)", "America/Fortaleza_Z_abbreviated" : "BR (Fortaleza)", "America/Fortaleza_Z_short" : "BRT", "America/Goose_Bay_Z_abbreviated" : "CA (Gus Bej (Kanada))", "America/Goose_Bay_Z_short" : "AST", "America/Grand_Turk_Z_abbreviated" : "(TC)", "America/Grand_Turk_Z_short" : "EST (SAD)", "America/Grenada_Z_abbreviated" : "(GD)", "America/Grenada_Z_short" : "AST", "America/Guadeloupe_Z_abbreviated" : "(GP)", "America/Guadeloupe_Z_short" : "AST", "America/Guatemala_Z_abbreviated" : "(GT)", "America/Guatemala_Z_short" : "CST (SAD)", "America/Guayaquil_Z_abbreviated" : "EC (Gvajakil)", "America/Guayaquil_Z_short" : "ECT", "America/Guyana_Z_abbreviated" : "(GY)", "America/Guyana_Z_short" : "GYT", "America/Halifax_Z_abbreviated" : "CA (Halifaks (kanada))", "America/Halifax_Z_short" : "AST", "America/Havana_Z_abbreviated" : "(CU)", "America/Havana_Z_short" : "CST (CU)", "America/Hermosillo_Z_abbreviated" : "MX (Hermosiljo (Meksiko))", "America/Hermosillo_Z_short" : "PST (SAD)", "America/Indiana/Indianapolis_Z_abbreviated" : "US (Indianapolis (SAD))", "America/Indiana/Indianapolis_Z_short" : "EST (SAD)", "America/Indiana/Knox_Z_abbreviated" : "US (Konks (SAD))", "America/Indiana/Knox_Z_short" : "CST (SAD)", "America/Indiana/Marengo_Z_abbreviated" : "US (Marengo (SAD))", "America/Indiana/Marengo_Z_short" : "EST (SAD)", "America/Indiana/Petersburg_Z_abbreviated" : "US (Petesburg (SAD))", "America/Indiana/Petersburg_Z_short" : "CST (SAD)", "America/Indiana/Tell_City_Z_abbreviated" : "US (Tel Siti (SAD))", "America/Indiana/Tell_City_Z_short" : "EST (SAD)", "America/Indiana/Vevay_Z_abbreviated" : "US (Vevej, Indijana)", "America/Indiana/Vevay_Z_short" : "EST (SAD)", "America/Indiana/Vincennes_Z_abbreviated" : "US (Vincenis, Indijana)", "America/Indiana/Vincennes_Z_short" : "EST (SAD)", "America/Indiana/Winamac_Z_abbreviated" : "US (Vinamak, Indijana)", "America/Indiana/Winamac_Z_short" : "EST (SAD)", "America/Iqaluit_Z_abbreviated" : "CA (Ikaluit)", "America/Iqaluit_Z_short" : "EST (SAD)", "America/Jamaica_Z_abbreviated" : "(JM)", "America/Jamaica_Z_short" : "EST (SAD)", "America/Juneau_Z_abbreviated" : "US (Žano)", "America/Juneau_Z_short" : "PST (SAD)", "America/Kentucky/Louisville_Z_abbreviated" : "US (Luivil (SAD))", "America/Kentucky/Louisville_Z_short" : "EST (SAD)", "America/Kentucky/Monticello_Z_abbreviated" : "US (Montičelo (SAD))", "America/Kentucky/Monticello_Z_short" : "CST (SAD)", "America/La_Paz_Z_abbreviated" : "(BO)", "America/La_Paz_Z_short" : "BOT", "America/Lima_Z_abbreviated" : "(PE)", "America/Lima_Z_short" : "PET", "America/Los_Angeles_Z_abbreviated" : "US (Los Anđeles (SAD))", "America/Los_Angeles_Z_short" : "PST (SAD)", "America/Maceio_Z_abbreviated" : "BR (Masejo)", "America/Maceio_Z_short" : "BRT", "America/Managua_Z_abbreviated" : "(NI)", "America/Managua_Z_short" : "CST (SAD)", "America/Manaus_Z_abbreviated" : "BR (Manaus)", "America/Manaus_Z_short" : "AMT", "America/Martinique_Z_abbreviated" : "(MQ)", "America/Martinique_Z_short" : "AST", "America/Matamoros_Z_abbreviated" : "MX (Matamoros)", "America/Matamoros_Z_short" : "CST (SAD)", "America/Mazatlan_Z_abbreviated" : "MX (Mazatlan (Meksiko))", "America/Mazatlan_Z_short" : "PST (SAD)", "America/Menominee_Z_abbreviated" : "US (Menomine)", "America/Menominee_Z_short" : "EST (SAD)", "America/Merida_Z_abbreviated" : "MX (Merida (Meksika))", "America/Merida_Z_short" : "CST (SAD)", "America/Mexico_City_Z_abbreviated" : "MX (Meksiko siti (Meksiko))", "America/Mexico_City_Z_short" : "CST (SAD)", "America/Miquelon_Z_abbreviated" : "(PM)", "America/Miquelon_Z_short" : "AST", "America/Moncton_Z_abbreviated" : "CA (Monkton)", "America/Moncton_Z_short" : "AST", "America/Monterrey_Z_abbreviated" : "MX (Montrej (Meksiko))", "America/Monterrey_Z_short" : "CST (SAD)", "America/Montevideo_Z_abbreviated" : "(UY)", "America/Montevideo_Z_short" : "UYT", "America/Montserrat_Z_abbreviated" : "(MS)", "America/Montserrat_Z_short" : "AST", "America/Nassau_Z_abbreviated" : "(BS)", "America/Nassau_Z_short" : "EST (SAD)", "America/New_York_Z_abbreviated" : "US (Njujork (SAD))", "America/New_York_Z_short" : "EST (SAD)", "America/Noronha_Z_abbreviated" : "BR (Noronja)", "America/Noronha_Z_short" : "FNT", "America/North_Dakota/Beulah_Z_abbreviated" : "US (Beulah)", "America/North_Dakota/Beulah_Z_short" : "MST (SAD)", "America/North_Dakota/Center_Z_abbreviated" : "US (Centar, Severna Dakota (SAD))", "America/North_Dakota/Center_Z_short" : "MST (SAD)", "America/North_Dakota/New_Salem_Z_abbreviated" : "US (Novi Salem, Severna Dakota (SAD))", "America/North_Dakota/New_Salem_Z_short" : "MST (SAD)", "America/Ojinaga_Z_abbreviated" : "MX (Ojinaga)", "America/Ojinaga_Z_short" : "CST (SAD)", "America/Panama_Z_abbreviated" : "(PA)", "America/Panama_Z_short" : "EST (SAD)", "America/Pangnirtung_Z_abbreviated" : "CA (Pangnirtung)", "America/Pangnirtung_Z_short" : "AST", "America/Paramaribo_Z_abbreviated" : "(SR)", "America/Paramaribo_Z_short" : "NEGT", "America/Phoenix_Z_abbreviated" : "US (Feniks (SAD))", "America/Phoenix_Z_short" : "MST (SAD)", "America/Port-au-Prince_Z_abbreviated" : "(HT)", "America/Port-au-Prince_Z_short" : "EST (SAD)", "America/Port_of_Spain_Z_abbreviated" : "(TT)", "America/Port_of_Spain_Z_short" : "AST", "America/Porto_Velho_Z_abbreviated" : "BR (Porto Veljo)", "America/Porto_Velho_Z_short" : "AMT", "America/Puerto_Rico_Z_abbreviated" : "(PR)", "America/Puerto_Rico_Z_short" : "AST", "America/Rankin_Inlet_Z_abbreviated" : "CA (Rankin Inlet)", "America/Rankin_Inlet_Z_short" : "CST (SAD)", "America/Recife_Z_abbreviated" : "BR (Resife)", "America/Recife_Z_short" : "BRT", "America/Regina_Z_abbreviated" : "CA (Regina)", "America/Regina_Z_short" : "CST (SAD)", "America/Resolute_Z_abbreviated" : "CA (Rezolut)", "America/Resolute_Z_short" : "CST (SAD)", "America/Rio_Branco_Z_abbreviated" : "BR (Rio Branko)", "America/Rio_Branco_Z_short" : "ACT (Acre)", "America/Santa_Isabel_Z_abbreviated" : "MX (Santa Isabel)", "America/Santa_Isabel_Z_short" : "PST (SAD)", "America/Santarem_Z_abbreviated" : "BR (Santarem)", "America/Santarem_Z_short" : "AMT", "America/Santiago_Z_abbreviated" : "CL (Santijago)", "America/Santiago_Z_short" : "CLST", "America/Santo_Domingo_Z_abbreviated" : "(DO)", "America/Santo_Domingo_Z_short" : "GMT-0430", "America/Sao_Paulo_Z_abbreviated" : "BR (Sao Paolo)", "America/Sao_Paulo_Z_short" : "BRT", "America/St_Johns_Z_abbreviated" : "CA (Sv. Džon (Kanada))", "America/St_Johns_Z_short" : "NST", "America/St_Kitts_Z_abbreviated" : "(KN)", "America/St_Kitts_Z_short" : "AST", "America/St_Lucia_Z_abbreviated" : "(LC)", "America/St_Lucia_Z_short" : "AST", "America/St_Thomas_Z_abbreviated" : "(VI)", "America/St_Thomas_Z_short" : "AST", "America/St_Vincent_Z_abbreviated" : "(VC)", "America/St_Vincent_Z_short" : "AST", "America/Tegucigalpa_Z_abbreviated" : "(HN)", "America/Tegucigalpa_Z_short" : "CST (SAD)", "America/Tijuana_Z_abbreviated" : "MX (Tihuana (Meksiko))", "America/Tijuana_Z_short" : "PST (SAD)", "America/Toronto_Z_abbreviated" : "CA (Toronto (Kanada))", "America/Toronto_Z_short" : "EST (SAD)", "America/Tortola_Z_abbreviated" : "(VG)", "America/Tortola_Z_short" : "AST", "America/Vancouver_Z_abbreviated" : "CA (Vankuver (kanada))", "America/Vancouver_Z_short" : "PST (SAD)", "America/Winnipeg_Z_abbreviated" : "CA (Vinipeg (Kanada))", "America/Winnipeg_Z_short" : "CST (SAD)", "Antarctica/Casey_Z_abbreviated" : "AQ (Kasej)", "Antarctica/Casey_Z_short" : "AWST", "Antarctica/Davis_Z_abbreviated" : "AQ (Dejvis)", "Antarctica/Davis_Z_short" : "DAVT", "Antarctica/DumontDUrville_Z_abbreviated" : "AQ (Dimon d’Urvil)", "Antarctica/DumontDUrville_Z_short" : "DDUT", "Antarctica/Macquarie_Z_abbreviated" : "AQ (Macquarie)", "Antarctica/Macquarie_Z_short" : "AEDT", "Antarctica/McMurdo_Z_abbreviated" : "AQ (MakMurdo)", "Antarctica/McMurdo_Z_short" : "NZST", "Antarctica/Palmer_Z_abbreviated" : "AQ (Palmer)", "Antarctica/Palmer_Z_short" : "ART", "Antarctica/Rothera_Z_abbreviated" : "AQ (Rotera)", "Antarctica/Rothera_Z_short" : "ROTT", "Antarctica/Syowa_Z_abbreviated" : "AQ (Šova)", "Antarctica/Syowa_Z_short" : "SYOT", "Antarctica/Vostok_Z_abbreviated" : "AQ (Vostok)", "Antarctica/Vostok_Z_short" : "VOST", "Asia/Aden_Z_abbreviated" : "(YE)", "Asia/Aden_Z_short" : "AST (Arabija)", "Asia/Almaty_Z_abbreviated" : "KZ (Almati (Kazahstan))", "Asia/Almaty_Z_short" : "ALMT", "Asia/Amman_Z_abbreviated" : "(JO)", "Asia/Amman_Z_short" : "EET", "Asia/Anadyr_Z_abbreviated" : "RU (Anadir)", "Asia/Anadyr_Z_short" : "ANAT", "Asia/Aqtau_Z_abbreviated" : "KZ (Aktau)", "Asia/Aqtau_Z_short" : "SHET", "Asia/Aqtobe_Z_abbreviated" : "KZ (Akutobe)", "Asia/Aqtobe_Z_short" : "AKTT", "Asia/Ashgabat_Z_abbreviated" : "(TM)", "Asia/Ashgabat_Z_short" : "ASHT", "Asia/Baghdad_Z_abbreviated" : "(IQ)", "Asia/Baghdad_Z_short" : "AST (Arabija)", "Asia/Bahrain_Z_abbreviated" : "(BH)", "Asia/Bahrain_Z_short" : "GST", "Asia/Baku_Z_abbreviated" : "(AZ)", "Asia/Baku_Z_short" : "BAKT", "Asia/Bangkok_Z_abbreviated" : "(TH)", "Asia/Bangkok_Z_short" : "ICT", "Asia/Beirut_Z_abbreviated" : "(LB)", "Asia/Beirut_Z_short" : "EET", "Asia/Bishkek_Z_abbreviated" : "(KG)", "Asia/Bishkek_Z_short" : "FRUT", "Asia/Brunei_Z_abbreviated" : "(BN)", "Asia/Brunei_Z_short" : "BNT", "Asia/Choibalsan_Z_abbreviated" : "MN (Čojbalsan)", "Asia/Choibalsan_Z_short" : "ULAT", "Asia/Chongqing_Z_abbreviated" : "CN (Čongking (Kina))", "Asia/Chongqing_Z_short" : "LONT", "Asia/Colombo_Z_abbreviated" : "(LK)", "Asia/Colombo_Z_short" : "IST", "Asia/Damascus_Z_abbreviated" : "(SY)", "Asia/Damascus_Z_short" : "EET", "Asia/Dhaka_Z_abbreviated" : "(BD)", "Asia/Dhaka_Z_short" : "DACT", "Asia/Dili_Z_abbreviated" : "(TL)", "Asia/Dili_Z_short" : "TLT", "Asia/Dubai_Z_abbreviated" : "(AE)", "Asia/Dubai_Z_short" : "GST", "Asia/Dushanbe_Z_abbreviated" : "(TJ)", "Asia/Dushanbe_Z_short" : "DUST", "Asia/Gaza_Z_abbreviated" : "(PS)", "Asia/Gaza_Z_short" : "IST (IL)", "Asia/Harbin_Z_abbreviated" : "CN (Harbin (Kina))", "Asia/Harbin_Z_short" : "CHAT", "Asia/Hebron_Z_abbreviated" : "(PS)", "Asia/Hebron_Z_short" : "IST (IL)", "Asia/Ho_Chi_Minh_Z_abbreviated" : "(VN)", "Asia/Ho_Chi_Minh_Z_short" : "ICT", "Asia/Hong_Kong_Z_abbreviated" : "(HK)", "Asia/Hong_Kong_Z_short" : "HKT", "Asia/Hovd_Z_abbreviated" : "MN (Hovd)", "Asia/Hovd_Z_short" : "HOVT", "Asia/Irkutsk_Z_abbreviated" : "RU (Irkuck (Rusija))", "Asia/Irkutsk_Z_short" : "IRKT", "Asia/Jakarta_Z_abbreviated" : "ID (Džakarta)", "Asia/Jakarta_Z_short" : "WIT", "Asia/Jerusalem_Z_abbreviated" : "(IL)", "Asia/Jerusalem_Z_short" : "IST (IL)", "Asia/Kabul_Z_abbreviated" : "(AF)", "Asia/Kabul_Z_short" : "AFT", "Asia/Kamchatka_Z_abbreviated" : "RU (Kamčatka)", "Asia/Kamchatka_Z_short" : "PETT", "Asia/Karachi_Z_abbreviated" : "(PK)", "Asia/Karachi_Z_short" : "KART", "Asia/Kashgar_Z_abbreviated" : "CN (Kašgar (Kina))", "Asia/Kashgar_Z_short" : "KAST", "Asia/Kathmandu_Z_abbreviated" : "(NP)", "Asia/Kathmandu_Z_short" : "NPT", "Asia/Kolkata_Z_abbreviated" : "(IN)", "Asia/Kolkata_Z_short" : "IST", "Asia/Krasnoyarsk_Z_abbreviated" : "RU (Krasnojarsk)", "Asia/Krasnoyarsk_Z_short" : "KRAT", "Asia/Kuala_Lumpur_Z_abbreviated" : "MY (Kuala Lumpur)", "Asia/Kuala_Lumpur_Z_short" : "MALT", "Asia/Kuching_Z_abbreviated" : "MY (Kučing)", "Asia/Kuching_Z_short" : "BORT", "Asia/Kuwait_Z_abbreviated" : "(KW)", "Asia/Kuwait_Z_short" : "AST (Arabija)", "Asia/Macau_Z_abbreviated" : "(MO)", "Asia/Macau_Z_short" : "MOT", "Asia/Magadan_Z_abbreviated" : "RU (Magadan (Rusija))", "Asia/Magadan_Z_short" : "MAGT", "Asia/Manila_Z_abbreviated" : "(PH)", "Asia/Manila_Z_short" : "PHT", "Asia/Muscat_Z_abbreviated" : "(OM)", "Asia/Muscat_Z_short" : "GST", "Asia/Nicosia_Z_abbreviated" : "(CY)", "Asia/Nicosia_Z_short" : "EET", "Asia/Novokuznetsk_Z_abbreviated" : "RU (Novokuznetsk)", "Asia/Novokuznetsk_Z_short" : "KRAT", "Asia/Novosibirsk_Z_abbreviated" : "RU (Novosibirsk (Rusija))", "Asia/Novosibirsk_Z_short" : "NOVT", "Asia/Omsk_Z_abbreviated" : "RU (Omsk (Rusija))", "Asia/Omsk_Z_short" : "OMST", "Asia/Oral_Z_abbreviated" : "KZ (Oral (Kazakhstan))", "Asia/Oral_Z_short" : "URAT", "Asia/Phnom_Penh_Z_abbreviated" : "(KH)", "Asia/Phnom_Penh_Z_short" : "ICT", "Asia/Pontianak_Z_abbreviated" : "ID (Pontianak)", "Asia/Pontianak_Z_short" : "CIT", "Asia/Qatar_Z_abbreviated" : "(QA)", "Asia/Qatar_Z_short" : "GST", "Asia/Qyzylorda_Z_abbreviated" : "KZ (Kizilorda)", "Asia/Qyzylorda_Z_short" : "KIZT", "Asia/Rangoon_Z_abbreviated" : "(MM)", "Asia/Rangoon_Z_short" : "MMT", "Asia/Riyadh87_Z_abbreviated" : "(Asia/Riyadh87)", "Asia/Riyadh87_Z_short" : "GMT+030704", "Asia/Riyadh88_Z_abbreviated" : "(Asia/Riyadh88)", "Asia/Riyadh88_Z_short" : "GMT+030704", "Asia/Riyadh89_Z_abbreviated" : "(Asia/Riyadh89)", "Asia/Riyadh89_Z_short" : "GMT+030704", "Asia/Riyadh_Z_abbreviated" : "(SA)", "Asia/Riyadh_Z_short" : "AST (Arabija)", "Asia/Sakhalin_Z_abbreviated" : "RU (Sahalin (Rusija))", "Asia/Sakhalin_Z_short" : "SAKT", "Asia/Samarkand_Z_abbreviated" : "UZ (Samarkand (Uzbekistan))", "Asia/Samarkand_Z_short" : "SAMT (Samarkand)", "Asia/Seoul_Z_abbreviated" : "(KR)", "Asia/Seoul_Z_short" : "KST", "Asia/Shanghai_Z_abbreviated" : "CN (Šangaj)", "Asia/Shanghai_Z_short" : "CST (Kina)", "Asia/Singapore_Z_abbreviated" : "(SG)", "Asia/Singapore_Z_short" : "SGT", "Asia/Taipei_Z_abbreviated" : "(TW)", "Asia/Taipei_Z_short" : "CST (TW)", "Asia/Tbilisi_Z_abbreviated" : "(GE)", "Asia/Tbilisi_Z_short" : "TBIT", "Asia/Tehran_Z_abbreviated" : "(IR)", "Asia/Tehran_Z_short" : "IRST", "Asia/Thimphu_Z_abbreviated" : "(BT)", "Asia/Thimphu_Z_short" : "IST", "Asia/Tokyo_Z_abbreviated" : "(JP)", "Asia/Tokyo_Z_short" : "JST", "Asia/Ulaanbaatar_Z_abbreviated" : "MN (Ulan Bator)", "Asia/Ulaanbaatar_Z_short" : "ULAT", "Asia/Urumqi_Z_abbreviated" : "CN (Urumki)", "Asia/Urumqi_Z_short" : "URUT", "Asia/Vientiane_Z_abbreviated" : "(LA)", "Asia/Vientiane_Z_short" : "ICT", "Asia/Vladivostok_Z_abbreviated" : "RU (Vladivostok (Rusija))", "Asia/Vladivostok_Z_short" : "VLAT", "Asia/Yakutsk_Z_abbreviated" : "RU (Jakutsk (Rusija))", "Asia/Yakutsk_Z_short" : "YAKT", "Asia/Yekaterinburg_Z_abbreviated" : "RU (Jekatepinburg (Rusija))", "Asia/Yekaterinburg_Z_short" : "SVET", "Asia/Yerevan_Z_abbreviated" : "(AM)", "Asia/Yerevan_Z_short" : "YERT", "Atlantic/Bermuda_Z_abbreviated" : "(BM)", "Atlantic/Bermuda_Z_short" : "AST", "Atlantic/Cape_Verde_Z_abbreviated" : "(CV)", "Atlantic/Cape_Verde_Z_short" : "CVT", "Atlantic/Reykjavik_Z_abbreviated" : "(IS)", "Atlantic/Reykjavik_Z_short" : "GMT", "Atlantic/South_Georgia_Z_abbreviated" : "(GS)", "Atlantic/South_Georgia_Z_short" : "GST (Sv. Džordžija)", "Atlantic/St_Helena_Z_abbreviated" : "(SH)", "Atlantic/St_Helena_Z_short" : "GMT", "Atlantic/Stanley_Z_abbreviated" : "(FK)", "Atlantic/Stanley_Z_short" : "FKT", "Australia/Adelaide_Z_abbreviated" : "AU (Adelaida (Australija))", "Australia/Adelaide_Z_short" : "ACST", "Australia/Brisbane_Z_abbreviated" : "AU (Brizbejn (Australija))", "Australia/Brisbane_Z_short" : "AEST", "Australia/Darwin_Z_abbreviated" : "AU (Darvin (Australija))", "Australia/Darwin_Z_short" : "ACST", "Australia/Hobart_Z_abbreviated" : "AU (Horbat (Australija))", "Australia/Hobart_Z_short" : "AEDT", "Australia/Lord_Howe_Z_abbreviated" : "AU (Lord Hov)", "Australia/Lord_Howe_Z_short" : "AEST", "Australia/Melbourne_Z_abbreviated" : "AU (Melburn (Australija))", "Australia/Melbourne_Z_short" : "AEST", "Australia/Perth_Z_abbreviated" : "AU (Pert (Australija))", "Australia/Perth_Z_short" : "AWST", "Australia/Sydney_Z_abbreviated" : "AU (Sidnej (Australija))", "Australia/Sydney_Z_short" : "AEST", "BC" : "p. n. e.", "DateTimeCombination" : "{1} {0}", "DateTimeTimezoneCombination" : "{1} {0} {2}", "DateTimezoneCombination" : "{1} {2}", "EST_Z_abbreviated" : "GMT-0500", "EST_Z_short" : "GMT-0500", "Etc/GMT-14_Z_abbreviated" : "GMT+1400", "Etc/GMT-14_Z_short" : "GMT+1400", "Etc/GMT_Z_abbreviated" : "GMT+0000", "Etc/GMT_Z_short" : "GMT+0000", "Europe/Amsterdam_Z_abbreviated" : "(NL)", "Europe/Amsterdam_Z_short" : "CET", "Europe/Andorra_Z_abbreviated" : "(AD)", "Europe/Andorra_Z_short" : "CET", "Europe/Athens_Z_abbreviated" : "(GR)", "Europe/Athens_Z_short" : "EET", "Europe/Belgrade_Z_abbreviated" : "(RS)", "Europe/Belgrade_Z_short" : "CET", "Europe/Berlin_Z_abbreviated" : "(DE)", "Europe/Berlin_Z_short" : "CET", "Europe/Brussels_Z_abbreviated" : "(BE)", "Europe/Brussels_Z_short" : "CET", "Europe/Bucharest_Z_abbreviated" : "(RO)", "Europe/Bucharest_Z_short" : "EET", "Europe/Budapest_Z_abbreviated" : "(HU)", "Europe/Budapest_Z_short" : "CET", "Europe/Chisinau_Z_abbreviated" : "(MD)", "Europe/Chisinau_Z_short" : "MSK", "Europe/Copenhagen_Z_abbreviated" : "(DK)", "Europe/Copenhagen_Z_short" : "CET", "Europe/Gibraltar_Z_abbreviated" : "(GI)", "Europe/Gibraltar_Z_short" : "CET", "Europe/Helsinki_Z_abbreviated" : "(FI)", "Europe/Helsinki_Z_short" : "EET", "Europe/Istanbul_Z_abbreviated" : "(TR)", "Europe/Istanbul_Z_short" : "EET", "Europe/Kaliningrad_Z_abbreviated" : "RU (Kaliningrad)", "Europe/Kaliningrad_Z_short" : "MSK", "Europe/Kiev_Z_abbreviated" : "UA (Kijev)", "Europe/Kiev_Z_short" : "MSK", "Europe/Lisbon_Z_abbreviated" : "PT (Lisbon)", "Europe/Lisbon_Z_short" : "CET", "Europe/London_Z_abbreviated" : "(GB)", "Europe/London_Z_short" : "GMT+0100", "Europe/Luxembourg_Z_abbreviated" : "(LU)", "Europe/Luxembourg_Z_short" : "CET", "Europe/Madrid_Z_abbreviated" : "ES (Madrid)", "Europe/Madrid_Z_short" : "CET", "Europe/Malta_Z_abbreviated" : "(MT)", "Europe/Malta_Z_short" : "CET", "Europe/Minsk_Z_abbreviated" : "(BY)", "Europe/Minsk_Z_short" : "MSK", "Europe/Monaco_Z_abbreviated" : "(MC)", "Europe/Monaco_Z_short" : "CET", "Europe/Moscow_Z_abbreviated" : "RU (Moskva)", "Europe/Moscow_Z_short" : "MSK", "Europe/Oslo_Z_abbreviated" : "(NO)", "Europe/Oslo_Z_short" : "CET", "Europe/Paris_Z_abbreviated" : "(FR)", "Europe/Paris_Z_short" : "CET", "Europe/Prague_Z_abbreviated" : "(CZ)", "Europe/Prague_Z_short" : "CET", "Europe/Riga_Z_abbreviated" : "(LV)", "Europe/Riga_Z_short" : "MSK", "Europe/Rome_Z_abbreviated" : "(IT)", "Europe/Rome_Z_short" : "CET", "Europe/Samara_Z_abbreviated" : "RU (Samara (Rusija))", "Europe/Samara_Z_short" : "KUYT", "Europe/Simferopol_Z_abbreviated" : "UA (Simferopol)", "Europe/Simferopol_Z_short" : "MSK", "Europe/Sofia_Z_abbreviated" : "(BG)", "Europe/Sofia_Z_short" : "EET", "Europe/Stockholm_Z_abbreviated" : "(SE)", "Europe/Stockholm_Z_short" : "CET", "Europe/Tallinn_Z_abbreviated" : "(EE)", "Europe/Tallinn_Z_short" : "MSK", "Europe/Tirane_Z_abbreviated" : "(AL)", "Europe/Tirane_Z_short" : "CET", "Europe/Uzhgorod_Z_abbreviated" : "UA (Užgorod)", "Europe/Uzhgorod_Z_short" : "MSK", "Europe/Vaduz_Z_abbreviated" : "(LI)", "Europe/Vaduz_Z_short" : "CET", "Europe/Vienna_Z_abbreviated" : "(AT)", "Europe/Vienna_Z_short" : "CET", "Europe/Vilnius_Z_abbreviated" : "(LT)", "Europe/Vilnius_Z_short" : "MSK", "Europe/Volgograd_Z_abbreviated" : "RU (Volgograd (Rusija))", "Europe/Volgograd_Z_short" : "VOLT", "Europe/Warsaw_Z_abbreviated" : "(PL)", "Europe/Warsaw_Z_short" : "CET", "Europe/Zaporozhye_Z_abbreviated" : "UA (Zaporožje)", "Europe/Zaporozhye_Z_short" : "MSK", "Europe/Zurich_Z_abbreviated" : "(CH)", "Europe/Zurich_Z_short" : "CET", "HMS_long" : "{0} {1} {2}", "HMS_short" : "{0}:{1}:{2}", "HM_abbreviated" : "h:mm a", "HM_short" : "hh.mm a", "H_abbreviated" : "h a", "Indian/Antananarivo_Z_abbreviated" : "(MG)", "Indian/Antananarivo_Z_short" : "EAT", "Indian/Chagos_Z_abbreviated" : "(IO)", "Indian/Chagos_Z_short" : "IOT", "Indian/Christmas_Z_abbreviated" : "(CX)", "Indian/Christmas_Z_short" : "CXT", "Indian/Cocos_Z_abbreviated" : "(CC)", "Indian/Cocos_Z_short" : "CCT", "Indian/Comoro_Z_abbreviated" : "(KM)", "Indian/Comoro_Z_short" : "EAT", "Indian/Kerguelen_Z_abbreviated" : "(TF)", "Indian/Kerguelen_Z_short" : "TFT", "Indian/Mahe_Z_abbreviated" : "(SC)", "Indian/Mahe_Z_short" : "SCT", "Indian/Maldives_Z_abbreviated" : "(MV)", "Indian/Maldives_Z_short" : "MVT", "Indian/Mauritius_Z_abbreviated" : "(MU)", "Indian/Mauritius_Z_short" : "MUT", "Indian/Mayotte_Z_abbreviated" : "(YT)", "Indian/Mayotte_Z_short" : "EAT", "Indian/Reunion_Z_abbreviated" : "(RE)", "Indian/Reunion_Z_short" : "RET", "MD_abbreviated" : "MMM d.", "MD_long" : "MMMM d.", "MD_short" : "M-d", "M_abbreviated" : "MMM", "M_long" : "MMMM", "Pacific/Apia_Z_abbreviated" : "(WS)", "Pacific/Apia_Z_short" : "BST (Беринг)", "Pacific/Auckland_Z_abbreviated" : "NZ (Auckland)", "Pacific/Auckland_Z_short" : "NZST", "Pacific/Chuuk_Z_abbreviated" : "FM (Truk)", "Pacific/Chuuk_Z_short" : "TRUT", "Pacific/Efate_Z_abbreviated" : "(VU)", "Pacific/Efate_Z_short" : "VUT", "Pacific/Fakaofo_Z_abbreviated" : "(TK)", "Pacific/Fakaofo_Z_short" : "TKT", "Pacific/Fiji_Z_abbreviated" : "(FJ)", "Pacific/Fiji_Z_short" : "FJT", "Pacific/Funafuti_Z_abbreviated" : "(TV)", "Pacific/Funafuti_Z_short" : "TVT", "Pacific/Gambier_Z_abbreviated" : "PF (Gambije)", "Pacific/Gambier_Z_short" : "GAMT", "Pacific/Guadalcanal_Z_abbreviated" : "(SB)", "Pacific/Guadalcanal_Z_short" : "SBT", "Pacific/Guam_Z_abbreviated" : "(GU)", "Pacific/Guam_Z_short" : "GST (Гуам)", "Pacific/Honolulu_Z_abbreviated" : "US (Honolulu (SAD))", "Pacific/Honolulu_Z_short" : "AHST", "Pacific/Johnston_Z_abbreviated" : "UM (Džonston)", "Pacific/Johnston_Z_short" : "AHST", "Pacific/Majuro_Z_abbreviated" : "MH (Majuro)", "Pacific/Majuro_Z_short" : "MHT", "Pacific/Midway_Z_abbreviated" : "UM (Midvej)", "Pacific/Midway_Z_short" : "BST (Беринг)", "Pacific/Nauru_Z_abbreviated" : "(NR)", "Pacific/Nauru_Z_short" : "NRT", "Pacific/Niue_Z_abbreviated" : "(NU)", "Pacific/Niue_Z_short" : "NUT", "Pacific/Norfolk_Z_abbreviated" : "(NF)", "Pacific/Norfolk_Z_short" : "NFT", "Pacific/Noumea_Z_abbreviated" : "(NC)", "Pacific/Noumea_Z_short" : "NCT", "Pacific/Pago_Pago_Z_abbreviated" : "(AS)", "Pacific/Pago_Pago_Z_short" : "BST (Беринг)", "Pacific/Palau_Z_abbreviated" : "(PW)", "Pacific/Palau_Z_short" : "PWT", "Pacific/Pitcairn_Z_abbreviated" : "(PN)", "Pacific/Pitcairn_Z_short" : "PNT", "Pacific/Port_Moresby_Z_abbreviated" : "(PG)", "Pacific/Port_Moresby_Z_short" : "PGT", "Pacific/Rarotonga_Z_abbreviated" : "(CK)", "Pacific/Rarotonga_Z_short" : "CKT", "Pacific/Saipan_Z_abbreviated" : "(MP)", "Pacific/Saipan_Z_short" : "MPT", "Pacific/Tarawa_Z_abbreviated" : "KI (Tarava)", "Pacific/Tarawa_Z_short" : "GILT", "Pacific/Tongatapu_Z_abbreviated" : "(TO)", "Pacific/Tongatapu_Z_short" : "TOT", "Pacific/Wake_Z_abbreviated" : "UM (Vake)", "Pacific/Wake_Z_short" : "WAKT", "Pacific/Wallis_Z_abbreviated" : "(WF)", "Pacific/Wallis_Z_short" : "WFT", "RelativeTime/oneUnit" : "{0} ago", "RelativeTime/twoUnits" : "{0} {1} ago", "TimeTimezoneCombination" : "{0} {2}", "WET_Z_abbreviated" : "GMT+0000", "WET_Z_short" : "GMT+0000", "WMD_abbreviated" : "E d. MMM", "WMD_long" : "EEEE, MMMM d", "WMD_short" : "E, M-d", "WYMD_abbreviated" : "EEE, d. MMM y.", "WYMD_long" : "EEEE, dd. MMMM y.", "WYMD_short" : "EEE, M/d/yy", "W_abbreviated" : "EEE", "W_long" : "EEEE", "YMD_abbreviated" : "MMM d, y", "YMD_full" : "d.M.yy.", "YMD_long" : "dd. MMMM y.", "YMD_short" : "d.M.yy.", "YM_long" : "y MMMM", "currencyFormat" : "#,##0.00 ¤", "currencyPatternPlural" : "{0} {1}", "currencyPatternSingular" : "{0} {1}", "day" : "dan", "day_abbr" : "dan", "dayperiod" : "pre podne/ popodne", "days" : "dana", "days_abbr" : "dana", "decimalFormat" : "#,##0.###", "decimalSeparator" : ".", "defaultCurrency" : "YUM", "exponentialSymbol" : "E", "groupingSeparator" : ",", "hour" : "sat", "hour_abbr" : "sat", "hours" : "sata", "hours_abbr" : "sata", "infinitySign" : "∞", "listPatternEnd" : "{0} i {1}", "listPatternTwo" : "{0} i {1}", "minusSign" : "-", "minute" : "minut", "minute_abbr" : "min", "minutes" : "minute", "minutes_abbr" : "min", "month" : "mesec", "monthAprLong" : "april", "monthAprMedium" : "apr", "monthAugLong" : "avgust", "monthAugMedium" : "avg", "monthDecLong" : "decembar", "monthDecMedium" : "dec", "monthFebLong" : "februar", "monthFebMedium" : "feb", "monthJanLong" : "januar", "monthJanMedium" : "jan", "monthJulLong" : "jul", "monthJulMedium" : "jul", "monthJunLong" : "jun", "monthJunMedium" : "jun", "monthMarLong" : "mart", "monthMarMedium" : "mar", "monthMayLong" : "maj", "monthMayMedium" : "maj", "monthNovLong" : "novembar", "monthNovMedium" : "nov", "monthOctLong" : "oktobar", "monthOctMedium" : "okt", "monthSepLong" : "septembar", "monthSepMedium" : "sep", "month_abbr" : "mes", "months" : "meseca", "months_abbr" : "mes", "nanSymbol" : "NaN", "numberZero" : "0", "perMilleSign" : "‰", "percentFormat" : "#,##0%", "percentSign" : "%", "periodAm" : "pre podne", "periodPm" : " popodne", "pluralRule" : "set11", "plusSign" : "+", "scientificFormat" : "#E0", "second" : "sekunda", "second_abbr" : "sek", "seconds" : "sekunde", "seconds_abbr" : "sek", "today" : "danas", "tomorrow" : "sutra", "weekdayFriLong" : "petak", "weekdayFriMedium" : "pet", "weekdayMonLong" : "ponedeljak", "weekdayMonMedium" : "pon", "weekdaySatLong" : "subota", "weekdaySatMedium" : "sub", "weekdaySunLong" : "nedelja", "weekdaySunMedium" : "ned", "weekdayThuLong" : "četvrtak", "weekdayThuMedium" : "čet", "weekdayTueLong" : "utorak", "weekdayTueMedium" : "uto", "weekdayWedLong" : "sreda", "weekdayWedMedium" : "sre", "year" : "godina", "year_abbr" : "god", "years" : "godine", "years_abbr" : "god", "yesterday" : "juče" }
/**! * Exame Informática Reader Tools * https://github.com/pedrofsantoscom/exame-informatica-reader-tools * * Copyright 2015 Pedro F. Santos, http://pedrofsantos.com, me@pedrofsantos.com * Released under the MIT license * http://en.wikipedia.org/wiki/MIT_License * * Version: 2015.09.22 */ var EIReaderTools = { version: "2015.09.22", options: { fullscreen: { icon: { on: "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgBAMAAACBVGfHAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAABVQTFRFAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgEApAAAAAZ0Uk5TAA+fz9/vpTOW9gAAAJNJREFUKM/NkkEKwyAUBSeeQOoFDAX3duERcoQcQJN3/yN08RVLUui2fyE4Ph/IyPLiY56eoDj3TpmiOkFSI2lEPE6qtgSA3A+TtBaA9pAq4KRTANr77SQZUO93E1j9sg9wegDCTGQAygTN80fz+3FsAxx8T1w7nHQY2CySpJgAqpMq3QVANA3mwo/6eld5k339Dm89PDdxiEGVaQAAAABJRU5ErkJggg==", off: "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAI1JREFUeNrsV0EOwCAI6w/8/6lP8gk8ZTuPLUoirltCEy8mpY0iIAAcg0WsgxONreIRE4+bhnzYr05AkgO2wQQHV3wxwAmBieJe6xY8w0Q0BlcDZHOngXqA1zPziE68BTjNmWDGM4qKexNEoVAoJPVzWSGSlmJpM3q1HcsHEvlI9omhtL5m9TWT5cApwAD/IigEZttSgAAAAABJRU5ErkJggg==" } }, // backup of the original functions savedFunctions: { "ResizeViewer": { "orig": ResizeViewer, "mod": function() { var b = Math.max(400, document.documentElement.clientHeight), a = Math.round(pw * b / ph); ResizeMenu(); if (zoom) { a = Math.max(1000, Math.min(1502, document.documentElement.clientWidth)); $("#bvdPage div.pages").width(a).height(b).children(".panviewport").width(a).height(b) } if ((zoom || crop != null)) { return; } RszImgs(a, b) }, }, "CancelZoom": { "orig": CancelZoom, "mod": function(e) { var $this = $(this).find("img"); $("#bvdMenu").show(); $this.css("transform", ""); EIReaderTools.options.savedFunctions.CancelZoom.orig(); }, }, "PageChange": { "orig": PageChange, "mod": function() { CancelCut(); Tag(); TagAd(); if (!smode) $(window).trigger("resize"); if (player) $("#jqp").jPlayer("play"); // custom event: before sending request $(document).trigger("endPageChanged.eirt"); $("#ctl00_cph_viewer1_bvdPages").append($("<div>").addClass("eirt-loading")); } } }, }, // highlight current page on the side menu highlightSidePage: function() { var currPage = GetPage().p; var $container = $('#bvdMenuInner'); var $imgs = $("#bvdMenuImg img").removeClass("eirt-highlight"); var $el = $imgs.eq(currPage); $el.addClass("eirt-highlight"); $imgs.eq(currPage + ((currPage % 2 == 0) ? 1 : -1)).addClass("eirt-highlight"); $container.stop().animate( { scrollTop: parseInt(currPage / 2) * 98 }, 1000); }, // activates custom loading for the page "start ajax request" requestPageLoading: function(e) { e = e || {type: "click", target: $(".crn.topright")[0]}; var containers = $("#bvNav td.bvNavLinkSec, #bvdMenuImg img, .crn.topleft, .crn.topright"); var loading = $(".eirt-loading"); if ((e.type === "click" && containers.find(e.target).length || containers.is(e.target)) && loading.css("display") === "none") { loading.css("display", "block"); $(document).one("endPageChanged.eirt", function() { $(".eirt-loading").remove(); }); } }, // "jump to page" init method initPagination: function() { var el = $("<div>", {id: "eirt-pag-cont"}) .css( { "display": "inline-block", "color": "#000", "position": "relative", "padding": "0 2px", "border-left": "1px solid hsl(0, 0%, 70%)", "border-right": "1px solid hsl(0, 0%, 70%)", }) .insertAfter($("#eirt-state")); // jump to page event handler var goToPage = function(e) { e.stopPropagation(); e.preventDefault(); if (e.type !== "click") { var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode !== 13 || e.type !== "keyup") return false; } var $this = $(this); var input = $this; if ($this.siblings('#eirt-pag-input').length > 0) input = $this.siblings('#eirt-pag-input'); var inputVal = input.val(); var imgs = $("#bvdMenuImg img[onclick]"); input.val(""); var specialPages = { "i": 2, "inicio": 0, "fim": imgs.length - 1 }; var specialPagesEN = { "i": 2, "begin": 0, "end": imgs.length - 1 }; if (specialPages[inputVal] != null || specialPagesEN[inputVal] != null) { $(imgs[specialPages[inputVal] || specialPagesEN[inputVal]]).click(); return; } var num = parseInt(inputVal); if (num == null || num === NaN) return; var numLimited = Math.max(Math.min(num, imgs.length), 0); $(imgs[numLimited]).click(); EIReaderTools.requestPageLoading(); }; // shortcut to focus the input box, event handler var focusInput = function(e) { if (e.which == 80 && e.altKey) $("#eirt-pag-input").focus(); }; var focusOutInput = function() // input got focus { $(this).on("keyup.esc.eirt", function(e) // wait for esc key to unfocus { var $this = $(this); if (e.which === 27 && $this.is(":focus")) { document.getElementByTagName().blur(); return false; } }).one("blur.esc.eirt", function() // on focus out, remove above event { $(this).off("keyup.esc.eirt"); }); }; $("<input>", { id: "eirt-pag-input", type: "text", placeholder: "Página" }) .css( { "width": "40px", "height": "14px", "margin": "0px 3px 0 5px", }) .appendTo(el); $(document) .on("keyup.eirt", focusInput) .on("keyup.eirt", "#eirt-pag-input", goToPage) .on("focus.eirt", "#eirt-pag-input", focusOutInput) .on("click.eirt", "#eirt-pag-acc", goToPage); }, // "previous (left arrow) and next (right arrow) page" init method initNavigation: function() { $(document).on("keyup.eirt", function(e) { var imgs = $("#bvdMenuImg img[onclick]"); var $handlerL = $(".page.fleft"); var $handlerR = $(".page.fright"); // right arrow if (e.which === 39) { if ($handlerR.length === 0) $handlerR = $(".page:visible"); var src = $handlerR.attr("src"); var page = +src.split("/")[3].replace("f", ""); if (page < imgs.length - 1) $(".crn.topright").click(); } // left arrow else if (e.which === 37) { if ($handlerL.length === 0) $handlerL = $(".page:visible"); var src = $handlerL.attr("src"); var page = +src.split("/")[3].replace("f", ""); if (page > 1) $(".crn.topleft").click(); } else return; EIReaderTools.requestPageLoading(); }); }, // overriding the default mousewheel action to // zoom in and out the page initZoom: function() { var mathLimit = function(value, min, max) { return Math.max(Math.min(value, max), min); }; // catch mousewheel action event handler $(document).on("mousewheel.eirt", ".panviewport", function(e) { //$(this).css("overflow", "hidden"); var $this = $(this).find("img:visible"); var deltaY = -e.originalEvent.deltaY; /* var imgW = $this.width(); var imgH = $this.height(); var mouseX = mathLimit(e.clientX - $this.offset().left, 0, imgW); var mouseY = mathLimit(e.clientY - $this.offset().top, 0, imgH); var pointX = Math.abs(mouseX * 100 / imgW); var pointY = Math.abs(mouseY * 100 / imgH); */ var scaleValue = $this.data("scale") || 1; var scale = mathLimit((deltaY / 1000) + scaleValue, 0.1, 1); var transform = "scale("+scale+")".replace("@par", scale); /* var transformOrigin = mathLimit(pointX, 0, 100)+"% "+mathLimit(pointY, 0, 100)+"%"; */ // save scale value and apply transform to .panviewport $this.data("scale", scale) .css( { "transform": transform, //"transform-origin": transformOrigin, }); e.preventDefault(); }); }, // inits the fullscreen functionality initFullscreen: function() { var icons = EIReaderTools.options.fullscreen.icon; // fullscreen icon click, event handler // toggles fullscreen on and off var toggleFullscreen = function(e) { var $this = $(this); // redefine $this when using ESC key if (e.type === "keyup") $this = $("#eirt-fs"); // keyup event triggered but not ESC key if ((e.which !== 27 && e.type === "keyup") || e.which === 27 && !$this.data("mode")) return; e.data = e.data || {}; e.data.modeOverride = (e.data) ? e.data.modeOverride : null; var mode = (e.data.modeOverride != null) ? e.data.modeOverride : !$this.data("mode"); var bgcolor = 'url("data:image/png;base64,'+icons.off+'")'; var fsLeft = "50%"; var fsTransform = "-219%"; var fsTop = "6px"; var func = "orig"; var holder = $("#zahirad192"); $("#bvdPage_css").remove(); // turn on fullscreen else the default is turn off if (mode) { $("<style>", {id: "bvdPage_css"}).html( "#bvdPage\ {\ position: absolute;\ top: 0;\ right: 0;\ left: 0;\ bottom: 0;\ margin: 0;\ z-index: 1000;\ background-color: #F5F5F5;\ }").appendTo($("head")); func = "mod" bgcolor = 'url("data:image/png;base64,'+icons.on+'")'; holder = $("body"); fsPosition = "absolute"; fsTop = "0"; fsLeft = "0"; fsTransform = "0%"; } var style = $("#eirt-container") .css( { "left": fsLeft, "top": fsTop, }) .attr("style"); $("#eirt-container").attr("style", style+";transform: translateX("+fsTransform+");"); $this.css("background-image", bgcolor); $this.data("mode", mode); ResizeViewer = EIReaderTools.options.savedFunctions["ResizeViewer"][func]; $(window).trigger("resize"); }; // fullscreen ui element var $fs = $("<div>", {id: "eirt-fs"}) .css( { "display": "inline-block", "width": "15px", "height": "15px", "background-image": 'url("data:image/png;base64,'+icons.off+'")', "margin-left": "5px", "position": "relative", "top": "3px", "background-size": "100%", }) .data("mode", false) .click(toggleFullscreen) .insertAfter($("#eirt-pag-cont")); $(document).on("keyup.fullscreen.eirt", {modeOverride: false}, toggleFullscreen); }, // entry point for the tool init: function() { // remove EIRT if already exists EIReaderTools.reset(); // watch for specific elements clicks to trigger custom loading $(document).on("click.eirt.requestStarted", EIReaderTools.requestPageLoading); // ui container $("<div>", {id: "eirt-container"}) .css( { "position": "absolute", "left": "50%", "transform": "translateX(-219%)", "top": "5px", "z-index": "1010", "background": "#fff", "padding": "4px", "border-right": "1px solid hsl(0, 0%, 70%)", "border-bottom": "1px solid hsl(0, 0%, 70%)", }) .appendTo($("body")); // tool loading state and its name $("<span>", {id: "eirt-state"}) .text("EIReaderTools") .css( { "color": "#f00", "margin-right": "5px", "position": "relative", "top": "-4px", }).appendTo($("#eirt-container")); // $("head").append($("<style>", {id: "eirt-style"}) .text( '#eirt-state:after{'+ 'content: "v'+EIReaderTools.version+'";'+ 'color: black;'+ 'font-size: 8px;'+ 'position: absolute;'+ 'left: 0;'+ 'bottom: -8px;'+ 'margin-left: 32px;}'+ '#bvdMenuImg img.eirt-highlight{'+ 'border: 4px solid rgb(0, 173, 239);'+ 'margin: 0;}'+ // http://stephanwagner.me/only-css-loading-spinner '@keyframes loading{'+ 'to {transform: rotate(360deg);}}'+ '@-webkit-keyframes loading{'+ 'to {-webkit-transform: rotate(360deg);}}'+ '.eirt-loading{'+ 'display: none;'+ 'min-width: 100%;'+ 'min-height: 100%;'+ 'position: absolute;'+ 'background-color: hsla(100, 0%, 0%, 0.5);}'+ '.eirt-loading:before{'+ 'content: "A carregar...";'+ 'position: absolute;'+ 'top: 50%;'+ 'left: 50%;'+ 'width: 150px;'+ 'height: 150px;'+ 'margin-top: -75px;'+ 'margin-left: -75px;}'+ '.eirt-loading:not(:required):before{'+ 'content: "";'+ 'border-radius: 50%;'+ 'border-top: 10px solid #03ade0;'+ 'border-right: 0px solid transparent;'+ 'animation: loading 1s linear infinite;'+ '-webkit-animation: loading 1s linear infinite;}' ) ); $("#ctl00_cph_viewer1_bvdPages").append($("<div>").addClass("eirt-loading")); $(document).on("endPageChanged.eirt", EIReaderTools.highlightSidePage); // apply a moded function CancelZoom = EIReaderTools.options.savedFunctions.CancelZoom.mod; PageChange = EIReaderTools.options.savedFunctions.PageChange.mod; EIReaderTools.initPagination(); EIReaderTools.initNavigation(); EIReaderTools.initFullscreen(); EIReaderTools.initZoom(); EIReaderTools.highlightSidePage(); // load success, change color of #eirt-state $("#eirt-state").css("color", "#32CD32"); }, // remove the EIRT reset: function() { // remove the ui elements $("#eirt-container,#eirt-style").remove(); $("#bvdMenuImg img").removeClass("eirt-highlight") // set the original functions in place ResizeViewer = EIReaderTools.options.savedFunctions.ResizeViewer.orig; CancelZoom = EIReaderTools.options.savedFunctions.CancelZoom.orig; PageChange = EIReaderTools.options.savedFunctions.PageChange.orig; // unbind events $(document) .off("click.eirt.requestStarted") .off("click.eirt") .off("dblclick.eirt") .off("mousewheel.eirt") .off("keyup.eirt") .off("keyup.fullscreen.eirt") .off("endPageChanged.eirt"); }, } $(document).ready(EIReaderTools.init);
var PHPGettextParser = require("./parsers/PHPGettextParser"); var WordpressParser = require("./parsers/WordpressParser"); var AngularTranslateParser = require("./parsers/AngularTranslateParser"); var ParserList = { gettextPHP: function () { return new PHPGettextParser(); }, wordpress: function () { return new WordpressParser(); }, angularTranslate: function () { return new AngularTranslateParser(); } }; module.exports = ParserList;
require("ember-data/system/record_arrays/record_array"); /** @module data @submodule data-record-array */ var get = Ember.get, set = Ember.set; var map = Ember.EnumerableUtils.map; /** A ManyArray is a RecordArray that represents the contents of a has-many relationship. The ManyArray is instantiated lazily the first time the relationship is requested. ### Inverses Often, the relationships in Ember Data applications will have an inverse. For example, imagine the following models are defined: App.Post = DS.Model.extend({ comments: DS.hasMany('App.Comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('App.Post') }); If you created a new instance of `App.Post` and added a `App.Comment` record to its `comments` has-many relationship, you would expect the comment's `post` property to be set to the post that contained the has-many. We call the record to which a relationship belongs the relationship's _owner_. @class ManyArray @namespace DS @extends DS.RecordArray @constructor */ DS.ManyArray = DS.RecordArray.extend({ init: function() { this._super.apply(this, arguments); this._changesToSync = Ember.OrderedSet.create(); }, /** @private The record to which this relationship belongs. @property {DS.Model} */ owner: null, /** @private `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} */ isPolymorphic: false, // LOADING STATE isLoaded: false, loadingRecordsCount: function(count) { this.loadingRecordsCount = count; }, loadedRecord: function() { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { set(this, 'isLoaded', true); this.trigger('didLoad'); } }, fetch: function() { var references = get(this, 'content'), store = get(this, 'store'), owner = get(this, 'owner'); store.fetchUnloadedReferences(references, owner); }, // Overrides Ember.Array's replace method to implement replaceContent: function(index, removed, added) { // Map the array of record objects into an array of client ids. added = map(added, function(record) { Ember.assert("You can only add records of " + (get(this, 'type') && get(this, 'type').toString()) + " to this relationship.", !get(this, 'type') || (get(this, 'type').detectInstance(record)) ); return get(record, '_reference'); }, this); this._super(index, removed, added); }, arrangedContentDidChange: function() { this.fetch(); }, arrayContentWillChange: function(index, removed, added) { var owner = get(this, 'owner'), name = get(this, 'name'); if (!owner._suspendedRelationships) { // This code is the first half of code that continues inside // of arrayContentDidChange. It gets or creates a change from // the child object, adds the current owner as the old // parent if this is the first time the object was removed // from a ManyArray, and sets `newParent` to null. // // Later, if the object is added to another ManyArray, // the `arrayContentDidChange` will set `newParent` on // the change. for (var i=index; i<index+removed; i++) { var reference = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner.get('_reference'), reference, get(this, 'store'), { parentType: owner.constructor, changeType: "remove", kind: "hasMany", key: name }); this._changesToSync.add(change); } } return this._super.apply(this, arguments); }, arrayContentDidChange: function(index, removed, added) { this._super.apply(this, arguments); var owner = get(this, 'owner'), name = get(this, 'name'), store = get(this, 'store'); if (!owner._suspendedRelationships) { // This code is the second half of code that started in // `arrayContentWillChange`. It gets or creates a change // from the child object, and adds the current owner as // the new parent. for (var i=index; i<index+added; i++) { var reference = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner.get('_reference'), reference, store, { parentType: owner.constructor, changeType: "add", kind:"hasMany", key: name }); change.hasManyName = name; this._changesToSync.add(change); } // We wait until the array has finished being // mutated before syncing the OneToManyChanges created // in arrayContentWillChange, so that the array // membership test in the sync() logic operates // on the final results. this._changesToSync.forEach(function(change) { change.sync(); }); DS.OneToManyChange.ensureSameTransaction(this._changesToSync, store); this._changesToSync.clear(); } }, // Create a child record within the owner createRecord: function(hash, transaction) { var owner = get(this, 'owner'), store = get(owner, 'store'), type = get(this, 'type'), record; Ember.assert("You can not create records of " + (get(this, 'type') && get(this, 'type').toString()) + " on this polymorphic relationship.", !get(this, 'isPolymorphic')); transaction = transaction || get(owner, 'transaction'); record = store.createRecord.call(store, type, hash, transaction); this.pushObject(record); return record; } });
////////////////////////////////////////////////////////////////////////// // Javascript file for system R500 // ////////////////////////////////////////////////////////////////////////// function exportCsv(){ // some data to export var data = [ {"subject": "ECON 101", "startDate": "01/12/15", "startTime": "11:00:00 AM", "endDate": "01/12/15", "endTime": "11:50:00 AM", "location": "TBD"}, {"subject": "INFAS 131", "startDate": "01/12/15", "startTime": "11:00:00 AM", "endDate": "01/12/15", "endTime": "11:50:00 AM", "location": "TBD"}, {"subject": "ACCT 284", "startDate": "01/13/15", "startTime": "12:40:00 PM", "endDate": "01/13/15", "endTime": "02:00:00 PM", "location": "TBD"} ]; // prepare CSV data var csvData = new Array(); csvData.push('"Subject","Start Date","Start Time","End Date","End Time","Location"'); data.forEach(function(item, index, array) { csvData.push('"' + item.subject + '","' + item.startDate + '","' + item.startTime + '","' + item.endDate + '","' + item.endTime + '","' + item.location + '"'); }); // download stuff var fileName = "Calendar.csv"; var buffer = csvData.join("\n"); var blob = new Blob([buffer], { "type": "text/csv;charset=utf8;" }); var link = document.createElement("a"); if(link.download !== undefined) { // feature detection // Browsers that support HTML5 download attribute link.setAttribute("href", window.URL.createObjectURL(blob)); link.setAttribute("download", fileName); } else if(navigator.msSaveBlob) { // IE 10+ link.setAttribute("href", "#"); link.addEventListener("click", function(event) { navigator.msSaveBlob(blob, fileName); }, false); } link.innerHTML = "Export to CSV"; document.body.appendChild(link); link.click(); document.body.removeChild(link); return; } function downloadSchedule(){ exportCsv(); //var x = exportCsv(); //alert(x); // saveAs(x,"Calendar.csv"); //location.href='data:application/download,' + encodeURIComponent(x); return; } function getCourseMsg(which, year){ var html = "<iframe src=/R209/R2197.jsp?code=" + which + "&edition=" + year + " onMouseWheel=return(false) onMouseScroll=return(false) style=margin:0;padding:0;width:100%;height:100%; scrolling=no frameborder=0 marginwidth=0 marginheight=0></iframe>"; return html; } function showCourse(domobj, which, year, archivepath) { if (typeof coursebubblewidth == "undefined") { if(typeof bubblewidth == "undefined") var coursebubblewidth = 400; else var coursebubblewidth = bubblewidth; } function showCourseReady(req) { if($(req).find("course").length) { var html = $(req).find("course").text(); } else { var html = "<p>Course information cannot be found. This course may " + "no longer be offered. If you believe there is an error or " + "require more information, please contact the course " + "department.</p>"; } lfjs.bubble(domobj, html, {width:coursebubblewidth}); } function showCourseError(req) { var html = "<p>An error occurred trying to load course inormation. Please try your request again later. ( " + req.status + " - " + req.statusText + ")</p>"; lfjs.bubble(domobj, html, { width: coursebubblewidth }); } domobj.blur(); var gcurl = "proxy.jsp?code=" + encodeURIComponent(which); //if there is an archivepath var and an edition var defined, use that in the getCourse call if(typeof year != "undefined" && typeof archivepath != "undefined") { gcurl += "&edition=" + encodeURIComponent(year); } $.ajax({ url:gcurl, success:showCourseReady, error:showCourseError }); lfjs.bubble(domobj, "Loading course description...", {width:coursebubblewidth}); return false; } var lfjs = new Object; // Utility functions lfjs.isdocumentready = false; lfjs.path = ""; $(function() { lfjs.isdocumentready = true; lfjs.path = $("script[src$='lfjs.js']:first").attr("src").replace(/\/[^\/]*$/, ""); }); lfjs.rfcdate2jsdate = function(in_date) { var work_arr = in_date.split(' '); var ret_date = new Date(work_arr[2] + " " + work_arr[1] + ", " + work_arr[3] + " " + work_arr[4]); ret_date.setHours(ret_date.getHours() - ret_date.getTimezoneOffset() / 60); return ret_date; }; lfjs.displayDate = function(in_date, format) { var month_arr = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; if (!in_date) return ""; var showtime = true; if(format == "notime") showtime = false; var work_str = ""; if (format && format == "nice") { return month_arr[in_date.getMonth()] + " " + in_date.getDate() + ", " + in_date.getFullYear() + " " + (in_date.getHours() % 12 == 0 ? "12" : in_date.getHours() % 12) + ":" + (100 + in_date.getMinutes()).toString().substring(1) + (in_date.getHours() < 12 ? "am" : "pm"); } //support for any format containing %y,%Y,%m, and %d (i.e. %m/%d/%Y or %Y-%m-%d), %F (full date %Y-%m-%d), // %D (full date %m/%d/%y), %H (hour 00-23), %I (hour 01-12), %k (hour 0-23), %l (hour 1-12), // %M (minute 00-59), %S (seconds 00-60), %p (AM or PM), %P (am or pm); if(format && /\%[yYmdFDHIklM]{1}/.test(format)) { var shortmonth, shortday, shorthour, hour12hr, shorthour12hr, shortmin; var year = in_date.getFullYear(); var shortyear = (year + "").replace(/.*(\d{2})$/, "$1"); var month = shortmonth = in_date.getMonth() + 1; var hour = shorthout = hour12hr = shorthour12hr = in_date.getHours(); var minutes = in_date.getMinutes(); var secs = in_date.getSeconds(); if(hour < 12) var ampm = "AM"; else var ampm = "PM" if(hour % 12 == 0) var hour12hr = shorthour12hr = 12; else var hour12hr = shorthour12hr = hour % 12; if(hour12hr < 10) hour12hr = "0" + hour12hr; if(month < 10) month = "0" + month; var day = shortday = in_date.getDate(); if(day < 10) day = "0" + day; if(hour < 10) hour = "0" + hour; if (minutes < 10) minutes = "0" + minutes; if(secs < 10) secs = "0" + secs; var retval = format; retval = retval.replace(/%F/g, year + "-" + month + "-" + day).replace(/%D/g, month + "/" + day + "/" + shortyear); retval = retval.replace(/%Y/g, year).replace(/%y/g, shortyear).replace(/%m/g, month).replace(/%d/g, day); retval = retval.replace(/%H/g, hour).replace(/%I/g, hour12hr).replace(/%k/g, shorthour).replace(/%l/g, shorthour12hr); retval = retval.replace(/%M/g, minutes).replace(/%M/g, minutes).replace(/%S/g, secs); retval = retval.replace(/%p/g, ampm).replace(/%P/g, ampm.toLowerCase()); return retval; } var now = new Date(); var hours_old = Math.abs((now - in_date.getTime()) / 1000 / 60 / 60); if ((hours_old < 9 || (hours_old < 24 && now.getDate() == in_date.getDate())) && showtime) { if (in_date.getHours() % 12 == 0) work_str += "12"; else work_str += in_date.getHours() % 12; work_str += ":" + (100 + in_date.getMinutes()).toString().substring(1); if (in_date.getHours() < 12) work_str += "am"; else work_str += "pm"; } else if (hours_old > (24*30*6) && !showtime) { work_str += month_arr[in_date.getMonth()] + " " + in_date.getFullYear(); } else { work_str += month_arr[in_date.getMonth()] + " " + in_date.getDate(); } return work_str; }; lfjs.toDate = function(in_datestr) { // yyyy-mm-dd var format1 = /^(\d{4})\-(\d{1,2})\-(\d{1,2})$/; // mm/dd/yyyy var format2 = /^(\d{1,2})\/(\d{1,2})\/(\d{2,4})$/; if(format1.test(in_datestr)) { var res = format1.exec(in_datestr); return new Date(parseInt(res[1],10), (parseInt(res[2],10)-1), parseInt(res[3], 10)); } else if(format2.test(in_datestr)) { var res = format2.exec(in_datestr); var thisyear = new Date().getFullYear() + ""; var year = res[3]; if(year.length == 2) { //use this year as a cutoff for 2000 vs. 1900 var test = parseInt(thisyear.replace(/.*(\d{2})$/, "$1"),10); if(parseInt(year,10) <= test) year = "20" + year; else year = "19" + year; } else if (year.length != 4) { year = thisyear; } return new Date(parseInt(year,10), (parseInt(res[1],10)-1), parseInt(res[2], 10)); } return new Date(in_datestr); }; lfjs.makeTextDiv = function(in_contents, in_class) { var div = document.createElement("div"); if (in_class && in_class.length) div.className = in_class; div.appendChild(document.createTextNode(in_contents)); return div; } lfjs.cleanHTML = function(in_str) { return in_str.replace(/&/g, "&amp;").replace(/</g, "&lt;"); }; lfjs.addEvent = function(el, evname, func) { if (typeof el.addEventListener == "function") { el.addEventListener(evname, func, true); } else { el.attachEvent("on" + evname, func); } }; lfjs.removeEvent = function(el, evname, func) { if (typeof el.removeEventListener == "function") { el.removeEventListener(evname, func, true); } else { el.detachEvent("on" + evname, func); } }; lfjs.scrollToShow = function(selEl, parentEl) { //Only works in FF if position is set to "relative" of "absolute" if(typeof selEl == "string") selEl = document.getElementById(selEl); var scrollGap = selEl.clientHeight / 2; if(typeof parentEl == "undefined") { // Find the first parent who has overflow set to "scroll" for (parentEl = selEl.parentNode; parentEl.tagName.toLowerCase() != "body"; parentEl = parentEl.parentNode) { if (parentEl.style.overflow.indexOf("scroll") >= 0 || parentEl.style.overflow.indexOf("auto") >= 0) { break; } } } else if(typeof parentEl == "string") parentEl = document.getElementById(parentEl); if(selEl.offsetTop + selEl.offsetHeight > parentEl.scrollTop + parentEl.clientHeight) { parentEl.scrollTop = selEl.offsetTop + selEl.offsetHeight - parentEl.clientHeight + scrollGap; return; // top takes priority over the bottom } if(selEl.offsetTop < parentEl.scrollTop) { parentEl.scrollTop = selEl.offsetTop - scrollGap; } }; lfjs.setSelectedIndex = function(domobj, value) { for (var i=0; i < domobj.options.length; i++) { if (domobj.options[i].value == value) { domobj.selectedIndex = i; return true; } } return false; } // Base64 Encoding and decoding lfjs.base64 = { chararr: ['A','B','C','D','E','F','G','H', 'I','J','K','L', 'M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z', 'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p', 'q','r','s','t','u','v','w','x','y','z', '0','1','2','3','4','5','6','7','8','9','*','/'], decode: function(which) { var binary = new String(); var result = new String(); for (var i = 0; i < which.length; i++) { for (var j = 0; j < lfjs.base64.chararr.length; j++) { if(which.charAt(i) == lfjs.base64.chararr[j]) { binary += String("000000" + j.toString(2)). substring(j.toString(2).length); } } } for (var i = 0; i < binary.length; i+=8) { var number = new Number(); var counter = new Number(); for (var j = 0; j < binary.substring(i, i+8).length; j++) { for (var k = 128; k >= 1; k-=(k/2)) { if (binary.substring(i, i+8).charAt(counter++) == "1") number += k; } } if (number > 0) result += String.fromCharCode(number); } return result; }, encode: function(which) { var binary = new String(); var result = new String(); for(i = 0; i < which.length; i++) { binary += String("00000000" + which.charCodeAt(i). toString(2)).substring(which.charCodeAt(i). toString(2).length); } for(i = 0; i < binary.length; i+=6) { var number = new Number(); var counter = new Number(); for(j = 0; j < binary.substring(i, i+6).length; j++) { for(k = 32; k >= 1; k-=(k/2)) { if(binary.substring(i, i+6).charAt(counter++) == "1") { number += k; } } } result += lfjs.base64.chararr[number]; } return result; } }; // lfjs.keypress.installhandler(func) // lfjs.keypress.stuff(keystring) lfjs.keypress = { installhandler: function(func) { var oldhandler; if (document.onkeypress) { var tmpfunc = document.onkeypress; oldhandler = tmpfunc("GETFUNC"); } if (!func) { document.onkeypress = null; if (document.all) document.onkeydown = null; return oldhandler; } var keyhandler = func; document.onkeypress = function(in_key) { if (in_key && in_key == "GETFUNC") return keyhandler; return lfjs.keypress.keypresshandler(in_key, keyhandler); }; if (document.all) { document.onkeydown = function(in_key) { return lfjs.keypress.keydownhandler(in_key, keyhandler); }; } return oldhandler; }, stuff: function(keystr) { if (document.onkeypress) { var handler = document.onkeypress; return handler(keystr); } else { return false; } }, // Remaining functions are private getNonPrintableChar: function(event) { var keyCode = event.keyCode; var keyStr = ""; switch (keyCode) { case 112: keyStr += "F1"; break; case 113: keyStr += "F2"; break; case 114: keyStr += "F3"; break; case 115: keyStr += "F4"; break; case 116: keyStr += "F5"; break; case 117: keyStr += "F6"; break; case 118: keyStr += "F7"; break; case 119: keyStr += "F8"; break; case 120: keyStr += "F9"; break; case 121: keyStr += "F10"; break; case 122: keyStr += "F11"; break; case 123: keyStr += "F12"; break; case 38: keyStr += "UP"; break; case 40: keyStr += "DOWN"; break; case 37: keyStr += "LEFT"; break; case 39: keyStr += "RIGHT"; break; case 33: keyStr += "PGUP"; break; case 34: keyStr += "PGDN"; break; case 36: keyStr += "HOME"; break; case 35: keyStr += "END"; break; case 13: keyStr += "ENTER"; break; case 9: keyStr += "TAB"; break; case 27: keyStr += "ESC"; break; case 8: keyStr += "BACKSPACE"; break; case 46: keyStr += "DEL"; break; //ignore these here case 16: //shift case 17: //ctrl case 18: //alt case 20: //caps lock keyStr = ""; break; } if(keyStr != "") { if(event.shiftKey) keyStr = "Shift+" + keyStr; if(event.ctrlKey || event.ctrlLeft) keyStr = "Ctrl+" + keyStr; if(event.altKey || event.altLeft) keyStr = "Alt+" + keyStr; } return keyStr; }, keystring: function(in_key) { if (typeof in_key == "string") return in_key; if (typeof in_key == "undefined") in_key = window.event; var keyStr = ""; var key_code = in_key.keyCode; if (!key_code) key_code = in_key.charCode; if (typeof in_key.charCode == "undefined") in_key.charCode = in_key.keyCode; if (in_key.charCode != null && in_key.charCode != 0 && key_code > 30) { if (in_key.ctrlKey || in_key.ctrlLeft || in_key.metaKey) keyStr += "Ctrl+"; if (in_key.altKey || in_key.altLeft) keyStr += "Alt+"; keyStr += String.fromCharCode(key_code); } else { keyStr += lfjs.keypress.getNonPrintableChar(in_key); } return keyStr; }, keydownhandler: function(event, funcname) { // IE uses keydown to catch unprintable characters; ignore the // function if keydown was not unprintable if (typeof event == "undefined") event = window.event; var which = lfjs.keypress.getNonPrintableChar(event); if (which.length && !funcname(which)) { event.returnValue = false; event.cancelBubble = true; event.keyCode = 0; return false; } return true; }, keypresshandler: function(in_key, funcname) { // Check to see if keypress was lfjs.keypress.stuff'd if (typeof in_key == "string") return funcname(in_key); // Mozilla and IE (for regular keys) use keypress if (!funcname(lfjs.keypress.keystring(in_key))) { if (!in_key) { in_key = window.event; in_key.returnValue = false; in_key.cancelBubble = true; in_key.keyCode = 0; } if (in_key.stopPropagation) in_key.stopPropagation(); if (in_key.preventDefault) in_key.preventDefault(); in_key.returnValue = false; return false; } return true; } }; lfjs.window = function(domobj) { domobj.mvc = this; domobj.activate = function (a) { return this.mvc.activate(a); }; domobj.deactivate = function () { return this.mvc.deactivate(); }; $(domobj).addClass("inactivescreen"); this.win = domobj; document.body.appendChild(domobj.parentNode.removeChild(domobj)); } lfjs.window.stack = new Array(); lfjs.window.zcounter = 100; lfjs.window.prototype.activate = function(args) { if (lfjs.window.stack.length > 0) { var last_win = lfjs.window.stack[lfjs.window.stack.length-1].win; $(last_win).removeClass("activescreen"); $(last_win).addClass("inactivescreen"); } else { // Make the body an inactive screen $(document.body).addClass("inactivescreen"); } $(this.win).removeClass("inactivescreen"); $(this.win).addClass("activescreen"); if (args && args.title) { var titlediv = $(this.win).find('.screentitle'); if (titlediv.size() > 0) { titlediv.text(args.title); } else { var title = lfjs.makeTextDiv(args.title, "screentitle"); this.win.insertBefore(title, this.win.firstChild); new lfjs.dragable(title); } } if (args && args.onactivate) this.win.onactivate = args.onactivate; if ($(this.win).css("visibility") == "hidden" || $(this.win).css("display") == "none") { $(this.win).css("visibility", "hidden"); $(this.win).css("display", "block"); var screensize = new Object; if (window.innerWidth) { screensize.width = window.innerWidth; screensize.height = window.innerHeight; } else { //size appropriately for IE for Quirks vs. Standards mode if (document.documentElement && document.documentElement.clientHeight) { screensize.width = document.documentElement.clientWidth; screensize.height = document.documentElement.clientHeight; } else { screensize.width = document.body.clientWidth; screensize.height = document.body.clientHeight; } } //Position appropriately for IE for Quirks vs. Standards mode var scroll = document.body.scrollTop; if (!scroll && document.documentElement && document.documentElement.scrollTop) scroll = document.documentElement.scrollTop; $(this.win).css({ left: $(this.win).width() > screensize.width ? 0 : parseInt((screensize.width - $(this.win).width()) / 2), top: $(this.win).height() > screensize.height ? scroll : parseInt((screensize.height - $(this.win).height()) / 3) + scroll }); } // size and activate the modallayer if (!lfjs.window.modaldiv) { lfjs.window.modaldiv = document.createElement("div"); //$(lfjs.window.modaldiv).text("modal"); //document.body.insertBefore(lfjs.window.modaldiv, null); document.body.appendChild(lfjs.window.modaldiv); lfjs.window.modaldiv.id = "lfjs_modaldiv"; $(lfjs.window.modaldiv).css( {position:"absolute", top:"0px", left:"0px" }); lfjs.window.modaldiv.onclick = function() { return false; }; lfjs.addEvent(window, "resize", lfjs.window.resizeModalDiv); } lfjs.window.resizeModalDiv(); $(lfjs.window.modaldiv).css( {visibility:"visible", display:"block", zIndex:lfjs.window.zcounter++}); if ((args && args.keyhandler) || this.win.keyhandler) { // Don't save prior key handler if activate is called because a // window on top was deactivated if (!this.lastkeyhandler) { this.lastkeyhandler = lfjs.keypress.installhandler((args && args.keyhandler) ? args.keyhandler : this.win.keyhandler); } else { lfjs.keypress.installhandler((args && args.keyhandler) ? args.keyhandler : this.win.keyhandler); } } $(this.win).css("zIndex", lfjs.window.zcounter++); $(this.win).css("visibility", "visible"); lfjs.window.stack[lfjs.window.stack.length] = { win: this.win, args: args }; if (this.win.onactivate) this.win.onactivate(); } lfjs.window.prototype.deactivate = function(args) { if (lfjs.window.stack.length < 1) return; $(this.win).removeClass("activescreen"); $(this.win).addClass("inactivescreen"); $(this.win).css("display", "none"); var ourargs = lfjs.window.stack[lfjs.window.stack.length-1].args; if (this.lastkeyhandler) { lfjs.keypress.installhandler(this.lastkeyhandler); this.lastkeyhandler = null; } else if (ourargs && ourargs.keyhandler) { lfjs.keypress.installhandler(null); } lfjs.window.stack.length--; if (lfjs.window.stack.length > 0) { var prior = lfjs.window.stack[lfjs.window.stack.length-1]; lfjs.window.stack.length--; prior.win.activate(prior.args); } else { $(document.body).removeClass("inactivescreen"); $(lfjs.window.modaldiv).css("display", "none"); lfjs.removeEvent(window, "resize", lfjs.window.resizeModalDiv); } } // Static methods lfjs.window.wait = function() { if (!lfjs.window.waitdiv) { lfjs.window.waitdiv = document.createElement("div"); document.body.appendChild(lfjs.window.waitdiv); lfjs.window.waitdiv.id = "lfjs_waitdiv"; $(lfjs.window.waitdiv).css( {position:"absolute", top:"0px", left:"0px", cursor:"wait" }); lfjs.window.waitdiv.onclick = function() { return false; }; if (lfjs.window.stack.length == 0) lfjs.addEvent(window, "resize", lfjs.window.resizeWaitDiv); } lfjs.window.resizeWaitDiv(); $(lfjs.window.waitdiv).css( {visibility:"visible", display:"block", zIndex:lfjs.window.zcounter++}); lfjs.window.waitpriorhandler = lfjs.keypress.installhandler(lfjs.window.waitkeyhandler); } lfjs.window.nowait = function() { $(lfjs.window.waitdiv).css("display", "none"); if (lfjs.window.stack.length == 0) lfjs.removeEvent(window, "resize", lfjs.window.resizeWaitDiv); if (lfjs.window.waitpriorhandler) lfjs.keypress.installhandler(lfjs.window.waitpriorhandler); } // Internal static functions lfjs.window.resizeFullDiv = function(which) { // Remove div to let body size be what it wants var div = $(which); div.css({display:"none"}); if(document.compatMode && document.compatMode == "CSS1Compat") var refEl = document.documentElement; else var refEl = document.body; if (refEl.scrollHeight > $(window).height()) div.css( {height:refEl.scrollHeight, width: "100%" } ); else div.css( { height:$(window).height(), width: "100%" } ); div.css({display:"block"}); } lfjs.window.resizeModalDiv = function() { lfjs.window.resizeFullDiv(lfjs.window.modaldiv); } lfjs.window.resizeWaitDiv = function() { lfjs.window.resizeFullDiv(lfjs.window.waitdiv); } lfjs.window.waitkeyhandler = function(in_key) { if (in_key == "TAB" || (in_key.length == 1 && in_key >= ' ' && in_key <= '~')) return false; // Ignore al-nums; allow control keys return true; } // Initialize code $(function() { $('.screen').each(function(i) { new lfjs.window(this); }); $('.screentitle').each(function(i) { if (!$(this).hasClass("dragable")) { new lfjs.dragable(this); } }); }); // automatically turn any div of type "selectgrid" into a selectgrid object // functions: addrow, removerow, getselected, empty // addRow(id, cols[html], args{}) // ondblclick: function(id) // onclick: function(id) (default: select current row) // classname: classname // title: title lfjs.grid = function(domobj) { this.div = domobj; this.allowHTML = true; domobj.mvc = this; domobj.addRow = function (a, b, c) { return this.mvc.addRow(a, b, c); }; domobj.setHeaders = function (a) { return this.mvc.setHeaders(a); }; domobj.removeRow = function (a) { return this.mvc.removeRow(a); }; domobj.empty = function () { return this.mvc.empty(); }; domobj.getSelectedTR = function() { return this.mvc.getSelectedTR(); } domobj.getSelectedIndex = function() { return this.mvc.getSelectedIndex(); } domobj.getSelectedId = function() { return this.mvc.getSelectedId(); } domobj.getSelectedData = function() { return this.mvc.getSelectedData(); } domobj.selectRow = function(inrow) { return this.mvc.selectRow(inrow); } domobj.selectNext = function(dir) { return this.mvc.selectNext(dir); } domobj.setData = function(a, b) { return this.mvc.setData(a, b); } domobj.pause = function(a) { return this.mvc.pause(a); } domobj.setColWidths = function(a, b) { return this.mvc.setColWidths(a, b); } if ($(domobj).find("table").size() < 1) { this.table = document.createElement("table"); domobj.appendChild(this.table); } else { this.table = $(domobj).find("table")[0]; } this.table.width = "100%"; this.table.cellSpacing = 0; if ($(domobj).find("colgroup").size() < 1) { this.colgroup = document.createElement("colgroup"); this.table.appendChild(this.colgroup); } if ($(domobj).find("tbody").size() < 1) { this.tbody = document.createElement("tbody"); this.table.appendChild(this.tbody); } else { this.tbody = $(domobj).find("tbody")[0]; } if ($(domobj).find("thead").size() < 1) { this.thead = document.createElement("thead"); this.table.insertBefore(this.thead, this.tbody); } else { this.thead= $(domobj).find("thead")[0]; } } // Times: 11/51 (createElement, .append()) lfjs.grid.prototype.addRow = function(id, cols, args) { var tr = null, doappend = true; if (!args || !args.fastadd) { $(this.tbody).children().each(function (i) { if (this.selectid == id) { tr = this; doappend = false; $(this).empty(); return false; } }); } if (!tr) { tr = document.createElement("tr"); if (!(this.tbody.childNodes.length % 2)) tr.className = "odd"; } tr.selectid = id; tr.gridobj = this; var gridobj = this; if (args && args.data) tr.data = args.data; if (args && args.classname) $(tr).addClass(args.classname); if (args && args.onclick) { var clickfunc = args.onclick; tr.onclickfunc = clickfunc; tr.onclick = function() { var funcval = clickfunc(this.selectid, this); if (typeof funcval == "undefined" || funcval) gridobj.selectRow(this); }; } else { tr.onclick = function() { gridobj.selectRow(this); }; } if (args && args.ondblclick) { var dblfunc = args.ondblclick; tr.ondblclick = function() { dblfunc(this.selectid, this); }; } if (args && args.title) tr.title = args.title; for (var i=0; i < cols.length; i++) { var td = document.createElement("td"); if (!i && cols.length == 1) td.className = "firstcolumn lastcolumn"; else if (!i) td.className = "firstcolumn"; else if (i == cols.length - 1) td.className = "lastcolumn"; if(args && args.html) td.innerHTML = cols[i]; else td.appendChild(document.createTextNode(cols[i])); tr.appendChild(td); } if (doappend) this.tbody.appendChild(tr); return tr; } lfjs.grid.prototype.setHeaders = function(colobjs, args) { $(this.thead).empty(); tr = document.createElement("tr"); $(this.thead).append(tr); for (var i=0; i < colobjs.length; i++) { var th = $(document.createElement("th")); th.text(colobjs[i].name); if (colobjs[i].classname) th.addClass(colobjs[i].classname); if (colobjs[i].onclick) { lfjs.grid.setClickFunc(th[0], colobjs[i].onclick, colobjs[i].id ? colobjs[i].id : colobjs[i].name, i, colobjs[i].name, this.div); } if (colobjs[i].title) th[0].title = colobjs[i].title; $(tr).append(th); } } // Private function; used to get enclosures inside of loops lfjs.grid.setClickFunc = function(in_obj, in_func, in_id, in_index, in_name, in_divobj) { var func = in_func; var id = in_id; var index = in_index; var name = in_name; var divobj = in_divobj; var obj = in_obj; obj.onclick = function() { func(id, index, name, obj, divobj) }; } lfjs.grid.prototype.removeRow = function(which) { var thisobj = this; $(this.tbody).children().each(function(i) { if (this.selectid == which) { if ($(this).hasClass("selected")) thisobj.selectNext(); this.parentNode.removeChild(this); return false; } }); } lfjs.grid.prototype.empty = function() { //$(this.tbody).html(""); // This was very slow; so was ".empty()" while (this.tbody.lastChild) this.tbody.removeChild(this.tbody.lastChild); this.div.data = null; } lfjs.grid.prototype.selectRow = function(which) { if (!which) { $(this.tbody).children().removeClass("selected"); return; } if (typeof which != "object") { // Find the row with this ID var trobj = null; $(this.div).find("tr").each( function(i) { if (this.selectid == which) { trobj = this; return false; } }); if (!trobj) return; which = trobj; } var row = $(which); // Shortcut to the data block this.div.data = row[0].data; row.siblings().removeClass("selected"); row.addClass("selected"); // Scroll up to keep header in view if (!which.previousSibling && this.thead.firstChild) which = this.thead.firstChild; lfjs.scrollToShow(which, this.div); } lfjs.grid.prototype.getSelectedAttribute = function(which) { var selrow = $(this.tbody).children().filter(".selected"); if (selrow.size() == 1) return selrow[0][which]; else return null; } lfjs.grid.prototype.getSelectedTR = function() { var selrow = $(this.tbody).children().filter("TR.selected"); if (selrow.size() == 1) return selrow[0]; else return null; } lfjs.grid.prototype.getSelectedIndex = function() { return $(this.tbody).children("tr").index($(this.tbody).children("tr.selected:first")[0]); } lfjs.grid.prototype.getSelectedId = function() { return this.getSelectedAttribute("selectid"); } lfjs.grid.prototype.getSelectedData = function() { return this.getSelectedAttribute("data"); } lfjs.grid.prototype.selectNext = function(direction) { var rows = $(this.tbody).children(); if (rows.size() == 0) // Nothing to select return false; if (rows.size() == 1) { if (rows[0].onclickfunc) { var clickfunc = rows[0].onclickfunc; clickfunc(rows[0].selectid, rows[0]); } this.selectRow(rows[0]); return true; } var newrow = null; rows.each(function(i) { if ($(this).hasClass("selected")) { if (!direction || direction > 0) i++; else i--; if (i < 0) i = 0; if (i >= rows.size()) i = rows.size() - 1; newrow = rows[i]; return false; } }); if (!newrow && (!direction || direction > 0)) newrow = rows[0]; else if (!newrow) newrow = rows[rows.size()-1]; this.selectRow(newrow); if (newrow.onclickfunc) { var clickfunc = newrow.onclickfunc; clickfunc(newrow.selectid, newrow); } return true; } lfjs.grid.prototype.setColWidths = function(widths, args) { if (args && args.runonce && $(this.colgroup).children().size() > 0) return; $(this.colgroup).empty(); for (var i=0; i < widths.length; i++) { var newcol = document.createElement("col"); newcol.width = widths[i]; $(this.colgroup).append(newcol); } } lfjs.grid.generation_counter = 0; lfjs.grid.prototype.setData = function(rows, args) { // If there is a "setinfo", then we let that timer do our work var skipcall = true; if (!this.setinfo) skipcall = false; if (!args) args = new Object(); this.setinfo = { rows: rows, insfunc: args.insfunc, donefunc: args.donefunc, offset: 0, fetchoffset:0, fetchurl: args.fetchurl, fetchdisplay:args.fetchdisplay, started: new Date() }; if (!args.append) this.empty(); if (args.fetchurl && args.fetchurl.length && !rows.length) { if (!args.fetchoffset) this.setinfo.fetchoffset = 0; delete this.setinfo.rows; this.setinfo.fetch_generation = ++lfjs.grid.generation_counter; this.setDataFetch(); } else if (!skipcall) { this.setDataWork(); } } lfjs.grid.prototype.pause = function(dopause) { if (!this.setinfo) return false; var retval = this.setinfo.paused; if (!dopause && (typeof dopause != "undefined" || this.setinfo.paused)) delete this.setinfo.paused; else this.setinfo.paused = true; if (!this.setinfo.paused && this.setinfo.rows) this.setDataWork(); return retval; } lfjs.grid.prototype.setDataFetch = function() { var me = this; var locgen = this.setinfo.fetch_generation; this.setinfo.httpreq = $.ajax({url:this.setinfo.fetchurl + "&offset=" + this.setinfo.fetchoffset, success:function(req) { me.setDataFetched(req, locgen); } }); } lfjs.grid.prototype.setDataFetched_delayed = function(req, genid) { var me = this, locreq = req, locgen=genid; setTimeout(function() { me.setDataFetched_real(locreq, locgen); }, 3000); } lfjs.grid.prototype.setDataFetched = function(req, genid) { // Check to see if this data request is from the currently pending request if (!this.setinfo || this.setinfo.fetch_generation != genid) return; delete this.setinfo.httpreq; this.setinfo.fetchoffset = parseInt($(req).find("fetchbatch").attr("next")); var currrows = $(req).find(this.setinfo.fetchdisplay); if (!this.setinfo.rows) { // Show this and fetch a new batch this.setinfo.rows = currrows; this.setinfo.offset = 0; if (this.setinfo.fetchoffset) this.setDataFetch(); this.setDataWork(); } else { // Save this batch until we are done showing the prior batch this.setinfo.nextrows = currrows; } } lfjs.grid.showthreadsize = 50; lfjs.grid.showthreadpause = 25; lfjs.grid.prototype.setDataWork = function() { if (!this.setinfo || this.setinfo.paused || !this.setinfo.rows) return; var maxrows = lfjs.grid.showthreadsize; var stoprow = this.setinfo.offset + maxrows; if (stoprow > this.setinfo.rows.length) stoprow = this.setinfo.rows.length; var i; for (i=this.setinfo.offset; i < stoprow; i++) { if (this.setinfo.insfunc) this.setinfo.insfunc(this, this.setinfo.rows, i); else this.addRow(0, this.setinfo.rows[i], {fastadd:true}); } if (stoprow < this.setinfo.rows.length) { // More to show in this set this.setinfo.offset = stoprow; var where = this; setTimeout(function() { where.setDataWork() }, lfjs.grid.showthreadpause); return true; } if (this.setinfo.fetchurl && this.setinfo.nextrows) { // More to show in next set this.setinfo.rows = this.setinfo.nextrows; this.setinfo.offset = 0; delete this.setinfo.nextrows; if (this.setinfo.fetchoffset) this.setDataFetch(); this.setDataWork(); // Show next batch } else if (!this.setinfo.fetchurl || !this.setinfo.httpreq) { if (this.setinfo.donefunc) { var oldsetinfo = this.setinfo; delete this.setinfo; oldsetinfo.donefunc(this.div, "done", oldsetinfo); } else { delete this.setinfo; } } else { delete this.setinfo.rows; } } // Initialize code $(function() { $('.selectgrid').each(function(i) { new lfjs.grid(this); this.onselectstart = function() { return false; } }); }); // Synchronize form fields with data from an XML document lfjs.dbForm = function(viewdefs, xmldoc, args) { this.viewdefs = viewdefs; this.show(xmldoc); } lfjs.dbForm.prototype.show = function(in_xml) { var warnings = []; if (in_xml) this.xmldoc = in_xml; for (var i=0; i < this.viewdefs.length; i++) { var val = this.getFieldVal(i); if(this.viewdefs[i].dom.indexOf("[") != -1) var dom = $(this.viewdefs[i].dom. substr(1, this.viewdefs[i].dom.length-2)); else var dom = $('#' + this.viewdefs[i].dom); if (dom.size() < 1) { warnings.push("cannot find dom:" + this.viewdefs[i].dom); continue; } switch (dom[0].nodeName.toLowerCase()) { case "select": var vals = val.split(","); if(vals.length == 1) lfjs.setSelectedIndex(dom[0], val); else { var searchstr = "," + vals.join(",") + ","; for (var j=0; j < dom[0].options.length; j++) { if (searchstr.indexOf("," + dom[0].options[j].value + ",") >= 0) { dom[0].options[j].selected = true; } else dom[0].options[j].selected = false; } } break; case "textarea": dom[0].value = val; break; case "input": switch (dom[0].type) { case "text": case "password": case "hidden": dom[0].value = val; break; case "checkbox": case "radio": if(dom.length == 1) { if (val.length > 0) dom[0].checked = true; else dom[0].checked = false; } else { var vals = val.split(","); dom.each(function() { this.checked = false; }); for(var j=0; j < vals.length; j++) { var el = dom.filter("[value='" + vals[j] + "']"); if(el.length == 1) el[0].checked = true; } } break; default: warnings.push("unknown field type: " + dom[0].type); } break; default: dom.text(val); break; } } if (warnings.length && typeof(console) != "undefined") { for (var i=0; i < warnings; i++) console.log("dbform.show: " + warnings[i]); } return warnings; } lfjs.dbForm.prototype.clear = function(in_xml) { this.xmldoc = null; this.show(); } lfjs.dbForm.prototype.gather = function(args) { var retobj = new Object; for (var i=0; i < this.viewdefs.length; i++) { var oldval = this.getFieldVal(i); if(this.viewdefs[i].dom.indexOf("[") != -1) var dom = $(this.viewdefs[i].dom. substr(1, this.viewdefs[i].dom.length-2)); else var dom = $('#' + this.viewdefs[i].dom); if(dom.length < 1) continue; var newval = ""; switch (dom[0].nodeName.toLowerCase()) { case "select": if (dom[0].selectedIndex >= 0) { //newval = dom[0].options[dom[0].selectedIndex].value; var items = dom.val(); if(typeof items == "string") newval = items; else newval = items.join(","); } break; case "textarea": newval = dom[0].value.replace(/\r\n/g, "\n"); break; case "input": switch (dom[0].type) { case "text": case "password": case "hidden": newval = dom[0].value; break; case "checkbox": case "radio": // How do we handle "hasno"? if(dom.length == 1) { if (dom[0].checked) { var hasstr = this.viewdefs[i].xml; if (hasstr.indexOf(" has ") >= 0) newval = hasstr.substr(hasstr.indexOf(" has ")+5); else if (hasstr.indexOf(" hasno ") >= 0) newval = ""; else if (dom[0].value.length) newval = dom[0].value; else newval = "true"; } } else { var vals = []; dom.each(function() { if(this.checked) vals[vals.length] = this.value; }); newval = vals.sort().join(","); if (args && args.changedonly && oldval.split(',').sort().join(",") == newval) newval = oldval; } break; default: newval = oldval; if (typeof(console) != "undefined") console.log("dbForm.gather: unknown field type: " + dom[0].type + "; setting to " + newval); } break; default: newval = dom.text(); break; } if (newval != oldval || !args || !args.changedonly) { if (this.viewdefs[i].gatherVal) newval = this.viewdefs[i].gatherVal(this.viewdefs[i].dom, newval); var domname = this.viewdefs[i].dom; if (this.viewdefs[i].gatherName) { domname = this.viewdefs[i].gatherName; } else { if (args && args.domprefix && args.domprefix.length > 0 && domname.indexOf(args.domprefix) == 0) domname = domname.substr(args.domprefix.length); if (args && args.formprefix && args.formprefix.length > 0) domname = args.formprefix + domname; } if (!retobj[domname]) { retobj[domname] = newval; } else { if (typeof retobj[domname] != "array") retobj[domname] = [retobj[domname]]; retobj[domname][retobj[domname].length] = newval; } if (args && args.firstonly) return retobj; } } return retobj; } lfjs.dbForm.prototype.hasChanges = function() { var changes = this.gather({firstonly:true, changedonly:true}); for (change in changes) return true; return false; } // Private functions lfjs.dbForm.prototype.getFieldVal = function(offset) { var val = ""; var xmlfunc; if (this.xmldoc && this.viewdefs[offset].xml) { var xmlname = this.viewdefs[offset].xml; var xmlattr; if (xmlname.indexOf(' ') > 0) { xmlfunc = xmlname.substr(xmlname.indexOf(' ')+1); xmlname = xmlname.substr(xmlname, xmlname.indexOf(' ')); } if (xmlname.indexOf('.') > 0) { xmlattr = xmlname.substr(xmlname.indexOf('.')+1); xmlname = xmlname.substr(xmlname, xmlname.indexOf('.')); } if (xmlname == "this") xmlnode = $(this.xmldoc); else if (xmlname.indexOf("[") == 0) xmlnode = $(this.xmldoc).find(xmlname); else xmlnode = $(this.xmldoc).children(xmlname); if (xmlattr && xmlnode.size() > 0) { val = xmlnode[0].getAttribute(xmlattr); if (!val) val = ""; } else { val = xmlnode.text(); } } // TODO: make this word-boundary matching if (this.viewdefs[offset].showVal) { val = this.viewdefs[offset]. showVal(this.viewdefs[offset].dom, val, xmlfunc); } else if (xmlfunc && xmlfunc.indexOf("has ") == 0) { if (RegExp("\\b" + xmlfunc.substr(4) + "\\b").test(val)) val = xmlfunc.substr(4); else val = ""; } else if (xmlfunc && xmlfunc.indexOf("hasno ") == 0) { if (RegExp("\\b" + xmlfunc.substr(4) + "\\b").test(val)) val = ""; else val = xmlfunc.substr(4); } return val; } lfjs.dragable = function(in_domobj) { var domobj = in_domobj; domobj.mvc = this; this.div = domobj; this.container = domobj.parentNode; lfjs.dragable.activedrag = {}; domobj.dragStart = function(ev) { return domobj.mvc.dragStart(ev); }; lfjs.addEvent(domobj, "mousedown", domobj.dragStart); } lfjs.dragable.prototype.dragStart = function(event) { var el, evObj; var left, top; lfjs.dragable.activedrag = {}; evObj = (typeof window.event == "undefined") ? event : window.event; lfjs.dragable.activedrag.dragEl = this.container; this.container.style.cursor = "move"; // Get cursor position with respect to the page. if (typeof evObj.clientX != "undefined" && typeof document.body.scrollLeft != "undefined") { left = evObj.clientX + document.body.scrollLeft; top = evObj.clientY + document.body.scrollTop; } else if (typeof winodw.scrollX != "undefined") { left = evObj.clientX + window.scrollX; top = evObj.clientY + window.scrollY; } else { return; } // Save starting positions of cursor and element. lfjs.dragable.activedrag.startCursX = left; lfjs.dragable.activedrag.startCursY = top; if(lfjs.dragable.activedrag.dragEl.style.left == "") { if (document.defaultView && document.defaultView.getComputedStyle) { lfjs.dragable.activedrag.dragEl.style.left = parseInt( document.defaultView.getComputedStyle( lfjs.dragable.activedrag.dragEl, '').getPropertyValue('left')); } else if(document.all && document.getElementById && lfjs.dragable.activedrag.dragEl.currentStyle) { var elLeft = lfjs.dragable.activedrag.dragEl.currentStyle.left; if(elLeft == "auto") { lfjs.dragable.activedrag.dragEl.style.left = lfjs.dragable.activedrag.dragEl.offsetLeft; } else lfjs.dragable.activedrag.dragEl.style.left = parseInt( lfjs.dragable.activedrag.dragEl.currentStyle.left); } } lfjs.dragable.activedrag.elStartLeft = (typeof lfjs.dragable.activedrag.dragEl.style.left != "number") ? parseInt(lfjs.dragable.activedrag.dragEl.style.left) : 0; if(lfjs.dragable.activedrag.dragEl.style.top == "") { if (document.defaultView && document.defaultView.getComputedStyle) { lfjs.dragable.activedrag.dragEl.style.top = parseInt( document.defaultView.getComputedStyle( lfjs.dragable.activedrag.dragEl, '').getPropertyValue('top')); } else if(document.all && document.getElementById && lfjs.dragable.activedrag.dragEl.currentStyle) { var elTop = lfjs.dragable.activedrag.dragEl.currentStyle.top; if(elTop == "auto") { lfjs.dragable.activedrag.dragEl.style.top = lfjs.dragable.activedrag.dragEl.offsetTop; } else lfjs.dragable.activedrag.dragEl.style.top = parseInt(lfjs.dragable.activedrag.dragEl.currentStyle.top); } } lfjs.dragable.activedrag.elStartTop = (typeof lfjs.dragable.activedrag.dragEl.style.top != "number") ? parseInt(lfjs.dragable.activedrag.dragEl.style.top) : 0; // Capture mousemove and mouseup events on the page. lfjs.addEvent(document, "mousemove", lfjs.dragable.dragMove); lfjs.addEvent(document, "mouseup", lfjs.dragable.dragEnd); if (typeof evObj.preventDefault == "function") { evObj.preventDefault(); } else { evObj.cancelBubble = true; evObj.returnValue = false; } } lfjs.dragable.dragMove = function(ev) { var left, top, evObj; evObj = (typeof window.event == "undefined") ? ev : window.event; //only for Firefox - make sure draggable obj stays in window // NOTE: IE seems to handle this fine if(window.innerWidth) { if((evObj.clientX < 3) || (evObj.clientX > (window.innerWidth -20))) return; if((evObj.clientY < 3) || (evObj.clientY > (window.innerHeight-20))) return; } // Get cursor position with respect to the page. if (typeof evObj.clientX != "undefined" && typeof document.body.scrollLeft != "undefined") { left = evObj.clientX + document.body.scrollLeft; top = evObj.clientY + document.body.scrollTop; } else if (typeof winodw.scrollX != "undefined") { left = evObj.clientX + window.scrollX; top = evObj.clientY + window.scrollY; } // Move drag element by the same amount the cursor has moved. var tmpEl = lfjs.dragable.activedrag.dragEl; lfjs.dragable.activedrag.dragEl.style.left = (lfjs.dragable.activedrag.elStartLeft + left - lfjs.dragable.activedrag.startCursX) + "px"; lfjs.dragable.activedrag.dragEl.style.top = (lfjs.dragable.activedrag.elStartTop + top - lfjs.dragable.activedrag.startCursY) + "px"; if (typeof(tmpEl.drag_minleft) != "undefined" && parseInt(tmpEl.style.left) < tmpEl.drag_minleft) tmpEl.style.left = tmpEl.drag_minleft + "px"; if (typeof(tmpEl.drag_maxleft) != "undefined" && parseInt(tmpEl.style.left) > tmpEl.drag_maxleft) tmpEl.style.left = tmpEl.drag_maxleft + "px"; if (typeof(tmpEl.drag_mintop) != "undefined" && parseInt(tmpEl.style.top) < tmpEl.drag_mintop) tmpEl.style.top = tmpEl.drag_mintop + "px"; if (typeof(tmpEl.drag_maxtop) != "undefined" && parseInt(tmpEl.style.top) > tmpEl.drag_maxtop) tmpEl.style.top = tmpEl.drag_maxtop + "px"; if (typeof evObj.preventDefault == "function") { evObj.preventDefault(); } else { evObj.cancelBubble = true; evObj.returnValue = false; } } lfjs.dragable.dragEnd = function(ev) { lfjs.dragable.activedrag.dragEl.style.cursor = "default"; // Stop capturing mousemove and mouseup events. lfjs.removeEvent(document, "mousemove", lfjs.dragable.dragMove); lfjs.removeEvent(document, "mouseup", lfjs.dragable.dragEnd); } // Initialize code $(function() { $('.dragable').each(function(i) { new lfjs.dragable(this); }); }); lfjs.prompt = function(prompt, func, args) { if (!lfjs.prompt.win && $('#promptwin').size() > 0) lfjs.prompt.win = $('#promptwin')[0]; if (!lfjs.prompt.win) { // Create a prompt window lfjs.prompt.win = document.createElement("div"); lfjs.prompt.win.id = "promptwin"; lfjs.prompt.win.className = "screen"; document.body.appendChild(lfjs.prompt.win); new lfjs.window(lfjs.prompt.win); var html = "<div class=\"prompt\">Enter value:</div>" + "<input id=\"prompt_input\" type=\"text\""; if(args && args.maxlength) html += " maxlength=\"" + args.maxlength + "\""; html += " /><br>" + "<div class=\"buttonbar\">" + "<a href=\"#\" class=\"button\" onClick=\"lfjs.keypress.stuff(" + "'CTRL+ENTER'); return false;\"> OK </a>&nbsp; " + " <a href=\"#\" class=\"button\" onClick=\"lfjs.keypress.stuff(" + "'ESC'); return false;\">Cancel</a>" + "</div>"; $(lfjs.prompt.win).html(html); } lfjs.prompt.func = func; var title = prompt; if (args && args.title) title = args.title; $(lfjs.prompt.win).find(".prompt").text(prompt); if (args && args.defaultvalue) $(lfjs.prompt.win).find("input")[0].value = args.defaultvalue; else $(lfjs.prompt.win).find("input")[0].value = ""; lfjs.prompt.win.activate( { title: title, keyhandler: lfjs.prompt.keyhandler }); var inpval = $(lfjs.prompt.win).find("input")[0]; inpval.select(); inpval.focus(); } lfjs.prompt.keyhandler = function(in_key) { if (in_key == "ESC") { lfjs.prompt.win.deactivate(); lfjs.prompt.func(); return false; } else if (in_key == "CTRL+ENTER" || in_key == "ENTER") { var val = $(lfjs.prompt.win).find("input")[0].value; if (val && val.length > 0) { lfjs.prompt.win.deactivate(); lfjs.prompt.func(val); } return false; } return true; } lfjs.promptync = function(func, args) { if (!lfjs.promptync.win && $('#yncwin').size() > 0) lfjs.promptync.win = $('#yncwin')[0]; if (!lfjs.promptync.win) { // Create a ync window lfjs.promptync.win = document.createElement("div"); lfjs.promptync.win.id = "yncwin"; lfjs.promptync.win.className = "screen"; document.body.appendChild(lfjs.promptync.win); new lfjs.window(lfjs.promptync.win); $(lfjs.promptync.win).html( "<div class=\"ync\">Save changes?</div><div style=\"float:left\">" + "<a href=\"#no\" class=\"button\" onClick=\"" + "lfjs.keypress.stuff('n'); return false;\">No</a>" + "</div><div style=\"float:right\">" + "<a href=\"#cancel\" class=\"button\" onClick=\"" + "lfjs.keypress.stuff('ESC'); return false;\">Cancel</a>" + "<a href=\"#yes\" class=\"button\" onClick=\"" + "lfjs.keypress.stuff('CTRL+ENTER'); return false;\">Yes</a>" + "</div>" ); } lfjs.promptync.func = func; lfjs.promptync.yesfunc = args.yesfunc; lfjs.promptync.nofunc = args.nofunc; var title = (args.title ? args.title : (args.prompt ? args.prompt : "Confirm")); $(lfjs.promptync.win).find(".ync").text( args.prompt ? args.prompt : "Save changes?"); var buttons = $(lfjs.promptync.win).find(".button"); $(buttons[0]).text(args.noprompt ? args.noprompt : "No"); $(buttons[1]).text(args.cancelprompt ? args.cancelprompt : " Cancel "); $(buttons[2]).text(args.yesprompt ? args.yesprompt : " Yes "); lfjs.promptync.win.activate({ keyhandler: lfjs.promptync.keyhandler, title: title }); } lfjs.promptync.keyhandler = function(in_key) { if (in_key == "ESC") { lfjs.promptync.win.deactivate(); lfjs.promptync.func(); return false; } else if (in_key == "CTRL+ENTER" || in_key == "y" || in_key == "Y") { lfjs.promptync.win.deactivate(); if (lfjs.promptync.yesfunc) lfjs.promptync.yesfunc(); lfjs.promptync.func("yes"); } else if (in_key == "n" || in_key == "N") { lfjs.promptync.win.deactivate(); if (lfjs.promptync.nofunc) lfjs.promptync.nofunc(); lfjs.promptync.func("no"); } return true; } //----------------------------- // Tab Functions //----------------------------- $(function() { $('.tabset').each(function(i) { var args = {}; if($(this).find(".tabnav").length == 1 && $(this).find(".tabnav").find("a").length > 1) { args.tabnav = $(this).find(".tabnav")[0]; $(this).find(".tabnav").remove(); } var ts = new lfjs.tabset(this, args); var tabs = $(this).children(".tab"); tabs.each(function(i) { if($(this).next(".tabcontent")[0]) var content = $(this).next(".tabcontent")[0]; else var content = null; var targs = {}; if($(this).attr("id").length) targs["id"] = $(this).attr("id"); if(this.className.length) targs["classname"] = this.className; targs["contents"] = $(this).next(".tabcontent")[0]; var tab = ts.addTab($(this).html(), targs ); if($(this).hasClass("selected")) tab.show(); $(this).remove(); }); ts.displayTabNav(); //size content div appropriately if($(ts.mainContentEl).children().length) { var pad = parseInt($(ts.tabContainerEl).css("padding-top")); var height = $(ts.domobj).height() - $(ts.tabContainerEl).height(); if(!isNaN(pad)) height -= pad; height -= 3; $(ts.mainContentEl).height(height); } }); }); lfjs.tabset = function(domobj, args) { if(!args) var args = {}; var self = this; domobj.tabset = this; this.domobj = domobj; //internal array of all tab objects this.tabs = []; //variable to track the currently shown tab this.currActive; //array to track the previously shown tabs this.prevActive = []; //timerID used for scrolling using the arrows this.tabScrollTimer = 0; //create the container div for the actual tabs var container = document.createElement("div"); $(container).addClass('tabcontainer').css( { width: "100%"}); //add nobr element to avoid tabs breaking if window is shrunk var nobr = document.createElement("nobr"); //create a navigation div for scrolling tabs function end(event) { var el = event.target el.blur(); self.endScroll(); event.stopPropagation(); } //add the scroll navigation div and links if(args.tabnav && $(args.tabnav).children("a").length > 1) { var nav = args.tabnav; var left = $(args.tabnav).find("a")[0]; var right = $(args.tabnav).find("a")[1]; } else { var nav = document.createElement("div"); var left = document.createElement("a"); var lefthtml = "&laquo;"; $(left).html(lefthtml).attr("title", "Scroll Left"); var right = document.createElement("a"); var righthtml = "&raquo;"; $(right).html(righthtml).attr("title", "Scroll Right"); $(nav).append(left).append("&nbsp;").append(right); } $(nav).addClass("tabnav").css( { display: "none", float: "right" } ); $(left).addClass("left").attr( { href: "#" } ).mousedown( function(event) { self.scroll(-1); event.stopPropagation(); return false; } ).mouseup( function(event) { end(event); return false; } ).mouseout( function(event) { end(event); return false; } ).click( function(event) { end(event); return false; } ); $(right).addClass("right").attr( { href: "#" } ).mousedown( function(event) { self.scroll(1); event.stopPropagation(); return false; } ).mouseup( function(event) { end(event); return false; } ).mouseout( function(event) { end(event); return false; } ).click( function(event) { end(event); return false; } ); function resizeMe() { self.displayTabNav(); } //create the content div for the content of each tab var content = document.createElement("div"); $(content).addClass('tabcontents'); //add an event to handle displaying/hiding navigation on window resize //doesn't work right in IE, since IE fires multiple resize events, if fact // it crashes IE6 on Win@k in Quirks Mode if(!$.browser.msie) { $(window).resize(function() { resizeMe() }); } $(nobr).append(nav).append(container); $(domobj).append(nobr).append(content); //$(nobr).append(container); //$(domobj).append(nav).append(nobr).append(content); this.tabContainerEl = container; this.mainTabEl = domobj; this.mainContentEl = content; this.navEl = nav; //Add a scroll wheel handler (jQuery does not support teh mousewheel event, so add it old school) if (typeof this.tabContainerEl.addEventListener == "function") { this.tabContainerEl.addEventListener("DOMMouseScroll", function(event) { self.tabMouseWheel(event); }, true); } else { this.tabContainerEl.attachEvent("onmousewheel", function(event) { self.tabMouseWheel(event); }); } domobj.getTabs = function() { return this.tabset.getTabs(); }; domobj.getShownTab = function() { return this.tabset.getShownTab(); }; domobj.show = function(tab) { return this.tabset.show(tab); }; domobj.remove = function(tab) { return this.tabset.remove(tab); }; domobj.addTab = function(label, args) { return this.tabset.addTab(label, args); }; return this; //domobj.activate = function (a) { return this.mvc.activate(a); }; //domobj.deactivate = function () { return this.mvc.deactivate(); }; //$(domobj).addClass("inactivescreen"); } lfjs.tab = function(label, args) { if(!args) var args = {}; this.tabset; this.tabDiv = null; this.contents = null; this.label = label; this.canclose = false; this.canmove = false; this.isActive = false; //variable to remember the vertical scroll position for each tab this.scrollTop = 0; if(args.id) this.id = args.id; if(args.classname) this.classname = args.classname; if(args.showfunc) this.showfunc = args.showfunc; if(args.hidefunc) this.hidefunc = args.hidefunc; if(args.closefunc) this.closefunc = args.closefunc; if(args.dropfunc) this.dropfunc = args.dropfunc; if(args.canclose) this.canclose = args.canclose; if(args.data) this.data = args.data; if(args.canmove) this.canmove = args.canmove; if(args.contents) { if(typeof args.contents == "string" && $("#" + args.contents).length) this.contents = $("#" + args.contents)[0]; else if($(args.contents).length) { //this.contents = $(args.contents).remove().get(0); this.contents = args.contents; } $(this.contents).css({display: "none"}); } return this; } //create the actual tab element lfjs.tab.prototype.drawTab = function () { var self = this; if(this.tabDiv && $(this.tabDiv).length) { var tabDiv = $(this.tabDiv).empty().get(0); } else { var tabDiv = document.createElement("span"); this.tabDiv = tabDiv; $(this.tabset.tabContainerEl).append(tabDiv); $(tabDiv).css( { display: "inline" } ).addClass("tab").addClass((this.isActive) ? 'tabactive' : 'tabinactive').mouseover( function(event) { self.tabMouseOver(); } ).mouseout( function(event) { self.tabMouseOut(); } ).click( function(event) { self.show(); } ); if(this.id) $(tabDiv).attr("id", this.id) if(this.classname) $(tabDiv).addClass(this.classname) if(typeof tabDiv.onselectstart != "undefined") { //tabDiv.onselectstart = function() { return false; }; } } tabDiv.tab = this; $(tabDiv).html(this.label); if(this.canclose) { var close = document.createElement("span"); var a = document.createElement("a"); $(a).html("x").attr( {title: "Close Tab"} ).click( function() { self.remove(); } ); $(close).addClass('closetab').append(a); $(tabDiv).append(close); } if(this.isActive) { this.tabset.currActive = this; } } lfjs.tabset.prototype.addTab = function(label, args) { var tabObj = new lfjs.tab(label, args); tabObj.tabset = this; if(tabObj.contents) { if(tabObj.contents.parentNode) { var node = tabObj.contents.parentNode.removeChild(tabObj.contents); } else { var node = tabObj.contents; } $(this.mainContentEl).append(node); } tabObj.tabset.tabs[tabObj.tabset.tabs.length] = tabObj; tabObj.drawTab(); //show tab navigation, if necessary this.displayTabNav(); return tabObj; } lfjs.tab.prototype.updateArgs = function(args) { for(var i in args) { if(typeof this[i] != "undefined" && this[i] != null) { this[i] = args[i]; } } this.drawTab(); } lfjs.tabset.prototype.getTabs = function() { var tabs = []; for(var i=0; i < this.tabs.length; i++) { tabs[tabs.length] = this.tabs[i]; } return tabs; } lfjs.tabset.prototype.getShownTab = function() { if(this.currActive) return this.currActive; return null; } lfjs.tabset.prototype.show = function(tabObj) { tabObj.show(); } //show a tab lfjs.tab.prototype.show = function() { var content = this.tabset.mainContentEl; if(this == this.tabset.currActive) return; if(this.tabset.currActive) { if(this.tabset.currActive.hidefunc) { var ret = this.tabset.currActive.hidefunc(this.tabset.currActive); if(ret == false) return false; } this.tabset.prevActive[this.tabset.prevActive.length] = this.tabset.currActive; $(this.tabset.currActive.tabDiv).addClass('tabinactive').removeClass('tabactive'); } $(this.tabDiv).addClass('tabactive').removeClass('tabinactive'); var show = true; if(this.showfunc) { show = this.showfunc(this); } if(this.contents && show != false) { if(this.tabset.currActive && this.tabset.currActive.contents) { this.tabset.currActive.scrollTop = this.tabset.mainContentEl.scrollTop; $(this.tabset.currActive.contents).css( { display: "none" }); } $(this.contents).css( { display: "block" } ); this.tabset.mainContentEl.scrollTop = this.scrollTop; } //Set this as the currently active tab this.tabset.currActive = this; this.scrollToView(); } lfjs.tab.prototype.scrollToView = function() { //if it is scrolled out of view, scroll into view if(this.tabset.tabContainerEl.clientWidth < this.tabset.tabContainerEl.scrollWidth) { var offL = this.tabDiv.offsetLeft; var scrL = this.tabset.tabContainerEl.scrollLeft; var offR = this.tabDiv.offsetLeft + this.tabDiv.offsetWidth; var scrR = this.tabset.tabContainerEl.scrollLeft + this.tabset.tabContainerEl.clientWidth; if(offL < scrL) this.tabset.tabContainerEl.scrollLeft = offL - 8; else if (offR > scrR) this.tabset.tabContainerEl.scrollLeft = offR - this.tabset.tabContainerEl.clientWidth; } } lfjs.tabset.prototype.remove = function(tabObj) { tabObj.remove(); } lfjs.tab.prototype.remove = function(forceclose) { if(typeof forceclose == "undefined") var forceclose = false; var exists = false; if(this.tabset.tabs.length > 1 || forceclose) { for(var i=0; i < this.tabset.tabs.length; i++) { if(this.tabset.tabs[i] == this) { //check if it is the last tab, if it is, select the last tab // otherwise, select the next tab after removal if(i == (this.tabset.tabs.length-1)) var nextTab = i-1; else var nextTab = i; this.tabset.tabs.splice(i,1); exists = true; break; } } if(exists) { if(this.closefunc) { var ret = this.closefunc(this); if(ret == false) return false; } this.tabset.tabContainerEl.removeChild(this.tabDiv); var isCurrTab = false; if(this.tabset.currActive == this) { isCurrTab = true; this.tabset.currActive = null; } if(this.contents) { $(this.contents).remove(); } var next = this.tabset.currActive; //show the previously selected tab, if exists, otherwise select by proximity if(this.tabset.prevActive.length) { //remove references to the tab closing in prevActive for(var i=this.tabset.prevActive.length; i >= 0; i--) { if(this.tabset.prevActive[i] == this) this.tabset.prevActive.splice(i,1); } if(isCurrTab) { var next = this.tabset.prevActive.splice(this.tabset.prevActive.length-1, 1); next = next[0]; } } else if (isCurrTab) { next = this.tabset.tabs[nextTab]; } if(isCurrTab && next) next.show(); if(next) next.scrollToView(); //show tab navigation, if necessary this.tabset.displayTabNav(); } } } /////////////////////////////// // EVENT HANDLING FUNCTIONS ////////////////////////////// //called onClick to show the tab that was clicked on lfjs.tab.prototype.tabMouseOut = function() { $(this.tabDiv).removeClass('tabhover'); } lfjs.tab.prototype.tabMouseOver = function() { if(!(this == this.tabset.currActive)) $(this.tabDiv).addClass('tabhover'); } lfjs.tabset.prototype.tabMouseWheel = function(ev) { var delta = 0; if (!ev) ev = window.event; //IE and Opera if (ev.wheelDelta) { delta = ev.wheelDelta/120; // In Opera 9, delta differs in sign as compared to IE. if (window.opera) delta = -delta; // Firefox } else if (ev.detail) { // In Firefox, sign of delta is different than in IE. Also, delta is multiple of 3. delta = -ev.detail/3; } // If delta is nonzero, handle it. Basically, delta is now positive if wheel was scrolled up, // and negative, if wheel was scrolled down. if (delta) { var dis = delta * 20; this.tabContainerEl.scrollLeft -= dis; } if (ev.preventDefault) ev.preventDefault(); ev.returnValue = false; } lfjs.tabset.prototype.scroll = function(dir) { var self = this; var dir = dir; this.tabScrollTimer = setTimeout(function() { self.scroll(dir);}, 1); var dis = dir * 2; this.tabContainerEl.scrollLeft += dis; } lfjs.tabset.prototype.endScroll = function() { if(typeof this.tabScrollTimer == "number") clearTimeout(this.tabScrollTimer); return false; } //check to see if the tab navigation is required lfjs.tabset.prototype.displayTabNav = function() { var cliW = this.mainTabEl.clientWidth; var scrW = this.tabContainerEl.scrollWidth; //if no width is set on mainTabEl, IE reports clientWidth as 0 if(cliW == 0) { this.mainTabEl.style.width = "100%"; cliW = this.mainTabEl.clientWidth; this.mainTabEl.style.width = ""; } if(scrW > cliW) { this.navEl.style.display = "block"; this.tabContainerEl.style.width = (cliW - this.navEl.offsetWidth - 4) + "px"; this.tabContainerEl.style.overflowX = "hidden"; } else { this.navEl.style.display = "none"; this.tabContainerEl.style.width = "100%"; } //if scrollLeft + clientWidth > scrollWidth, then we need to snap the tabs to the right side if(this.tabContainerEl.scrollLeft + this.tabContainerEl.clientWidth > this.tabContainerEl.scrollWidth) this.tabContainerEl.scrollLeft = this.tabContainerEl.scrollWidth + this.tabContainerEl.clientWidth; } // Initialize code $(function() { $('.multiupload').each(function(i) { new lfjs.multiupload(this); }); }); lfjs.multiupload = function(domobj) { if(parseInt(lfjs.multiupload.flashVersion(), 10) < 9) { domobj.onclick(domobj); return; } var flashsrc = $("script[src$='swfupload.js']:first").attr("src").replace(/swfupload\.js$/, "swfupload.swf"); if(domobj.nodeType == 1 && (/(span|div|a|button|img)/.test(domobj.nodeName.toLowerCase()) || (domobj.nodeName.toLowerCase() == "input" && domobj.type == "button"))) { } else { if(window.console) console.log("MultiUpload element must be SPAN, DIV, A, IMG, BUTTON, or INPUT type=button."); return; } //console.log(domobj.nodeType + ' ' + domobj.nodeName + ' "' + domobj.id + '" - ' + $(domobj).width() + " x " + $(domobj).height()); //console.log(domobj.offsetWidth + " x " + domobj.offsetHeight); if(typeof SWFUpload == "function") { var placeholder = document.createElement("span"); var ts = new Date().valueOf() + ''; placeholder.id = "lfjsmu" + domobj.nodeName.toLowerCase() + ts.substring(Math.floor(Math.random()*ts.length)); $(domobj).css({zIndex: "1"}); var swfwidth = domobj.offsetWidth; // Broken: $(domobj).width(); var swfheight = domobj.offsetHeight; // Broken: $(domobj).height(); var washidden = false; if (swfwidth == 0 || swfwidth == 0) { washidden = true; //tweak any hidden parents so we can figure out where to put the button. var hiddenpar = $(domobj).parents(":hidden"); var currpos = hiddenpar.css("position"); hiddenpar.toggle().css({ visibility: "hidden", position:"absolute"}); swfwidth = domobj.offsetWidth; // Broken: $(domobj).width(); swfheight = domobj.offsetHeight; // Broken: $(domobj).height(); } if(/(input|button|img)/.test(domobj.nodeName.toLowerCase())) { var buttontext = domobj.value; var par = document.createElement("span"); $(par).addClass("swfuploadwrapper"); $(domobj).wrap(par).before(placeholder); //console.log("OW: " + domobj.offsetWidth + " - JQ Width: " + $(domobj).width()); if(domobj.offsetWidth) { //swfwidth = domobj.offsetWidth; //swfheight = domobj.offsetHeight; } } else { var buttontext = $(domobj).html(); $(domobj).prepend(placeholder); } if (washidden) hiddenpar.css({ visibility: "visible", position:currpos}).toggle(); var cursor = $(domobj).css("cursor").toLowerCase(); var swfcursor = SWFUpload.CURSOR.ARROW; if(cursor == "pointer" || cursor == "hand" || domobj.nodeName.toLowerCase() == "a") swfcursor = SWFUpload.CURSOR.HAND; this.settings = { }; domobj.uploadsettings = this.settings; if(domobj.onclick) { domobj.initfunc = domobj.onclick; domobj.initfunc(); domobj.onclick = function() { return false; }; //console.log(this.settings); } else domobj.initfunc = function() {}; var args = { button_placeholder_id: placeholder.id, flash_url: flashsrc, file_types: "*.*", file_types_description: "All Files", requeue_on_error: false, //button_text: buttontext, button_width: swfwidth, button_height: swfheight, button_action : SWFUpload.BUTTON_ACTION.SELECT_FILES, button_window_mode: SWFUpload.WINDOW_MODE.TRANSPARENT, button_cursor: swfcursor, use_query_string: false, debug: false } var swf = this; function addSetting(localsetting, swfsetting) { if(swf.settings[localsetting] && swf.settings[localsetting].length) args[swfsetting] = swf.settings[localsetting]; } addSetting("url", "upload_url"); addSetting("filetypes", "file_types"); addSetting("filetypesdesc", "file_types_description"); addSetting("filepostname", "file_post_name"); addSetting("postparams", "post_params"); addSetting("filepostname", "file_post_name"); addSetting("requeueonerror", "requeue_on_error"); addSetting("filesizelimit", "file_size_limit"); args["swfupload_loaded_handler"] = function() { swf.flashLoaded() }; args["file_dialog_start_handler"] = function() { swf.fileDialogStart() }; args["file_queued_handler"] = function(a) { swf.fileQueued(a) }; args["file_queue_error_handler"] = function(a, b, c) { swf.fileQueueError(a, b, c) }; args["file_dialog_complete_handler"] = function(a, b, c) { swf.fileDialogComplete(a, b, c) }; args["upload_start_handler"] = function(a) { return swf.uploadStart(a) }; args["upload_progress_handler"] = function(a, b, c) { swf.uploadProgress(a, b, c) }; args["upload_error_handler"] = function(a, b, c) { swf.uploadError(a, b, c) }; args["upload_success_handler"] = function(a, b) { swf.uploadSuccess(a, b) }; args["upload_complete_handler"] = function(a) { swf.uploadComplete(a) }; this.swfupload = new SWFUpload(args); $(".multiupload .swfupload, SPAN .swfupload").each(function() { $(this).css({position: "absolute", "z-index": "2"}) }); this.files = []; this.currupload = ""; this.queuelength = 0; this.currfilecnt = 0; this.domobj = domobj; domobj.mvc = this; domobj.startUpload = function (a) { return this.mvc.startUpload(a); }; domobj.cancelUpload = function (a) { return this.mvc.cancelUpload(a); }; domobj.stopUpload = function () { return this.mvc.stopUpload(); }; domobj.getFile = function (a) { return this.mvc.getFile(a); }; domobj.getFiles = function () { return this.mvc.getFiles(); }; domobj.setUploadURL = function (a) { return this.mvc.setUploadURL(a); }; domobj.setPostParams = function (a, b) { return this.mvc.setPostParams(a, b); }; domobj.setFilePostParams = function (a, b, c) { return this.mvc.setFilePostParams(a, b, c); }; domobj.isIdle = function () { return this.mvc.isIdle(); }; } else { if(window.console) console.log("Cannot find SWFUpload. Make sure js file is included"); } } lfjs.multiupload.prototype.flashLoaded = function() { $(".multiuploadnoinit").hide(); if(typeof lfjs.multiupload.onInit == "function") lfjs.multiupload.onInit(this.domobj); if (this.settings["flashLoaded"] && typeof this.settings["flashLoaded"] == "function") { this.settings["flashLoaded"](this.domobj); } } lfjs.multiupload.prototype.fileDialogStart = function() { //add/update swf setting here this.domobj.initfunc(); var swf = this; var swfu = this.swfupload; swfu.movieElement.blur(); function addSetting(localsetting, setfunc) { if(swf.settings[localsetting] && swf.settings[localsetting].length) setfunc(swf.settings[localsetting]); } if(swf.settings["url"] && swf.settings["url"].length) this.setUploadURL(swf.settings["url"]); if(swf.settings["filepostname"] && swf.settings["filepostname"].length) this.swfupload.setFilePostName(swf.settings["filepostname"]); if(swf.settings["filesizelimit"] && swf.settings["filesizelimit"].length) this.swfupload.setFileSizeLimit(swf.settings["filesizelimit"]); if(swf.settings["postparams"] && typeof swf.settings["postparams"] == "object") this.setPostParams(swf.settings["postparams"], true); if(swf.settings["filetypes"] && swf.settings["filetypes"].length) { var desc = "All Files"; if(swf.settings["filetypesdesc"] && swf.settings["filetypesdesc"].length) { var desc = swf.settings["filetypesdesc"]; } this.swfupload.setFileTypes(swf.settings["filetypes"], desc); } addSetting("requeueonerror", "requeue_on_error"); if (this.settings["fileSelectStart"] && typeof this.settings["fileSelectStart"] == "function") { this.settings["fileSelectStart"](this.domobj); } } lfjs.multiupload.prototype.fileQueued = function(file) { var ret = true; if (this.settings["fileQueued"] && typeof this.settings["fileQueued"] == "function") { ret = this.settings["fileQueued"](this.domobj, file); } if(ret == false) { this.swfupload.cancelUpload(file.id, false); } else { var idx = this.files.length; this.files[idx] = file; this.files[idx].serverdata = ""; } } lfjs.multiupload.prototype.fileQueueError = function(file, error, msg) { if (this.settings["fileQueueError"] && typeof this.settings["fileQueueError"] == "function") { var ret = this.settings["fileQueueError"](this.domobj, file, error, msg); } for(var i=0; i < this.files.length; i++) { if(this.files[i].id == file.id) { this.files.splice(i, 1); break; } } } lfjs.multiupload.prototype.fileDialogComplete = function(numselected, numqueued, totalqueue) { var ret = true; this.queuelength += numqueued; //Don't fire on a cancel if(numselected == 0) return; if (this.settings["fileSelectComplete"] && typeof this.settings["fileSelectComplete"] == "function") { var ret = this.settings["fileSelectComplete"](this.domobj, this.files, numselected, numqueued); } if(ret != false) { this.swfupload.startUpload(); } } lfjs.multiupload.prototype.uploadStart = function(file) { var ret = true; this.currfilecnt++; if (this.settings["uploadStart"] && typeof this.settings["uploadStart"] == "function") { var ret = this.settings["uploadStart"](this.domobj, file, this.currfilecnt, this.queuelength); } this.currupload = file.id; if(ret == false) return ret; } lfjs.multiupload.prototype.uploadProgress = function(file, complete, total) { if (this.settings["uploadProgress"] && typeof this.settings["uploadProgress"] == "function") { var ret = this.settings["uploadProgress"](this.domobj, file, complete, total); } if(complete == total) { if (this.settings["fileReceived"] && typeof this.settings["fileReceived"] == "function") { var ret = this.settings["fileReceived"](this.domobj, file); } } } lfjs.multiupload.prototype.uploadError = function(file, error, msg) { if (this.settings["uploadError"] && typeof this.settings["uploadError"] == "function") { var ret = this.settings["uploadError"](this.domobj, file, error, msg); } } lfjs.multiupload.prototype.uploadSuccess = function(file, data) { for(var i=0; i < this.files.length; i++) { if(this.files[i].id == file.id) { this.files[i].serverdata = data; break; } } } lfjs.multiupload.prototype.uploadComplete = function(file) { var ret = true; var data = ""; var delidx = -1; for(var i=0; i < this.files.length; i++) { if(this.files[i].id == file.id) { var data = this.files[i].serverdata; delidx = i; break; } } if (this.settings["uploadComplete"] && typeof this.settings["uploadComplete"] == "function") { var ret = this.settings["uploadComplete"](this.domobj, file, data); } if(delidx >= 0) this.files.splice(delidx, 1); this.currupload = ""; if(ret != false) this.swfupload.startUpload(); if(this.isIdle()) this.queueComplete(); } lfjs.multiupload.prototype.queueComplete = function() { this.queuelength = 0; this.currfilecnt = 0; if (this.settings["queueComplete"] && typeof this.settings["queueComplete"] == "function") { var ret = this.settings["queueComplete"](this.domobj); } } lfjs.multiupload.prototype.startUpload = function(fileid) { this.swfupload.startUpload(fileid); } lfjs.multiupload.prototype.cancelUpload = function(fileid, throwerror) { for(var i=0; i < this.files.length; i++) { if(this.files[i].id == fileid) { this.files.splice(i, 1); break; } } this.queuelength--; this.swfupload.cancelUpload(fileid, throwerror); } lfjs.multiupload.prototype.stopUpload = function() { this.swfupload.stopUpload(); } lfjs.multiupload.prototype.getFile = function(fileid) { for(var i=0; i < this.files.length; i++) { if(this.files[i].id == fileid || this.files[i].name == fileid) return this.files[i]; } return null; } lfjs.multiupload.prototype.getFiles = function() { return this.files; } lfjs.multiupload.prototype.setUploadURL = function(url) { this.swfupload.setUploadURL(url); } lfjs.multiupload.prototype.setPostParams = function(paramobj, addremove) { if(typeof addremove == "undefined" || addremove == null) { this.swfupload.setPostParams(paramobj); } else if (addremove == true) { for(var i in paramobj) { this.swfupload.addPostParam(i, paramobj[i]); } } else if (addremove == false) { for(var i in paramobj) { this.swfupload.removePostParam(i); } } } lfjs.multiupload.prototype.setFilePostParams = function(fileid, paramobj, addremove) { var file = this.getFile(fileid); if(typeof addremove == "undefined" || addremove == null) { var addremove = true; } if (addremove == true) { for(var i in paramobj) { this.swfupload.addFileParam(file.id, i, paramobj[i]); } } else if (addremove == false) { for(var i in paramobj) { this.swfupload.removeFileParam(file.id, i); } } } lfjs.multiupload.prototype.isIdle = function() { var stats = this.swfupload.getStats(); if(stats.in_progress == 0 && stats.files_queued == 0 && this.files.length == 0) return true; return false; } lfjs.multiupload.flashVersion = function() { var flashVer = -1; if (navigator.plugins != null && navigator.plugins.length > 0) { if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) { var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : ""; var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description; var descArray = flashDescription.split(" "); var tempArrayMajor = descArray[2].split("."); var versionMajor = tempArrayMajor[0]; var versionMinor = tempArrayMajor[1]; var versionRevision = descArray[3]; if (versionRevision == "") { versionRevision = descArray[4]; } if (versionRevision[0] == "d") { versionRevision = versionRevision.substring(1); } else if (versionRevision[0] == "r") { versionRevision = versionRevision.substring(1); if (versionRevision.indexOf("d") > 0) { versionRevision = versionRevision.substring(0, versionRevision.indexOf("d")); } } flashVer = versionMajor + "." + versionMinor + "." + versionRevision; } } else if ( window.ActiveXObject ) { // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry var version; try { // version will be set for 7.X or greater players axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7"); version = axo.GetVariable("$version"); } catch (e) { } if (!version) { try { // version will be set for 6.X players only axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6"); // installed player is some revision of 6.0 // GetVariable("$version") crashes for versions 6.0.22 through 6.0.29, // so we have to be careful. // default to the first public version version = "WIN 6,0,21,0"; // throws if AllowScripAccess does not exist (introduced in 6.0r47) axo.AllowScriptAccess = "always"; // safe to call for 6.0r47 or greater version = axo.GetVariable("$version"); } catch (e) { } } if (!version) { try { // version will be set for 4.X or 5.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); version = axo.GetVariable("$version"); } catch (e) { } } if (!version) { try { // version will be set for 3.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.3"); version = "WIN 3,0,18,0"; } catch (e) { } } if (!version) { try { // version will be set for 2.X player axo = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"); version = "WIN 2,0,0,11"; } catch (e) { version = -1; } } if(version != -1) version = version.replace(/^[^\d]*/, ""); flashVer = version; } if(flashVer != -1) flashVer = flashVer.replace(/,/g, "."); return flashVer; } $(function() { if ($(".bubble").length) { lfjs.bubble.createBubble(); $('.bubble').each(function(i){ var title = $(this).attr("title"); if(title) { $(this).attr("title", title.replace(/\<\/?[^\>]*\>/g, "")) args = {}; if($(this).attr("bubblewidth")) args.width = parseInt($(this).attr("bubblewidth"), 10) $(this).data("args", args).click(function(event) { //console.log($(this).data("args")) lfjs.bubble(this, title, $(this).data("args"), event); }) } }); } }); lfjs.bubble = function(domobj, message, args, event) { lfjs.bubble.hide(); if(typeof lfjs.path == "undefined") lfjs.path = $("script[src$='lfjs.js']:first").attr("src").replace(/\/[^\/]*$/, ""); if(typeof message == "undefiend" || message.length == 0) return; if(typeof args == "undefined") var args = {}; var closeimg = lfjs.path + "/lfjsimages/cancel.gif"; if(args.closeimg) closeimg = args.closeimg; if(typeof lfjs.bubble.domobj == "undefined") { lfjs.bubble.createBubble(); } var width = 225; if(typeof args.width != "undefined") width = args.width; $(lfjs.bubble.domobj).width(width) if(!$(lfjs.bubble.domobj).find(".lfjsbubble #lfjsbubbleclose").length) { var img = document.createElement("img"); $(img).attr({ id: "lfjsbubbleclose", title: "Close", src: closeimg }) .error(function() { $(this).hide() }).click(function() { lfjs.bubble.hide(); }) $(lfjs.bubble.domobj).prepend(img); } $(lfjs.bubble.domobj).find(".lfjsbubblecontent").html(message); if (domobj) { var off = $(domobj).offset(); var dw = $(domobj).width(); var w = $(lfjs.bubble.domobj).width(); var h = $(lfjs.bubble.domobj).height(); var top = off.top - h - 5; //center bubble tail overr domobj var left = off.left - ((width - 70) - (dw / 2)); var tail = $(".lfjsbubbletail"); tail.removeClass("top left"); if (left < 0) { var right = width - (off.left + 70) //console.log("Right: " + right + " - Width: " + w) if (right > (w / 2)) { tail.addClass("left") right += 35 } tail.css("right", right + "px") left = 0; } else { tail.css("right", "40px") } } $(lfjs.bubble.domobj).css({ position: "absolute", top: top, left: left}).show().click(function() { return false; }); $(lfjs.bubble.domobj).find("a, :input").click(function(event) { event.stopImmediatePropagation() return true; }); domobj.blur(); setTimeout(function() { $(document.body).bind("click.hidebubble", function(event) { lfjs.bubble.hide() }) }, 1) } lfjs.bubble.hide = function() { if (typeof lfjs.bubble.domobj != "undefined") { $(lfjs.bubble.domobj).hide(); } $(document.body).unbind("click.hidebubble") } lfjs.bubble.createBubble = function() { var div = document.createElement("div"); var html = '<div class="lfjsbubbletop"></div>'; html += '<div class="lfjsbubbletopright"></div>'; html += '<div class="lfjsbubblemainwrapper"><div class="lfjsbubblemain">'; html += '<div class="lfjsbubblecontent"></div></div></div>'; html += '<div class="lfjsbubblebottom"></div>'; html += '<div class="lfjsbubblebottomright"></div><div class="lfjsbubbletail"></div>'; $(div).addClass("lfjsbubble").html(html).hide().appendTo(document.body); lfjs.bubble.domobj = div; } /*! * jQuery JavaScript Library v1.4.2 * http://jquery.com/ * * Copyright 2010, John Resig * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * Includes Sizzle.js * http://sizzlejs.com/ * Copyright 2010, The Dojo Foundation * Released under the MIT, BSD, and GPL Licenses. * * Date: Sat Feb 13 22:33:48 2010 -0500 */ (function(A,w){function ma(){if(!c.isReady){try{s.documentElement.doScroll("left")}catch(a){setTimeout(ma,1);return}c.ready()}}function Qa(a,b){b.src?c.ajax({url:b.src,async:false,dataType:"script"}):c.globalEval(b.text||b.textContent||b.innerHTML||"");b.parentNode&&b.parentNode.removeChild(b)}function X(a,b,d,f,e,j){var i=a.length;if(typeof b==="object"){for(var o in b)X(a,o,b[o],f,e,d);return a}if(d!==w){f=!j&&f&&c.isFunction(d);for(o=0;o<i;o++)e(a[o],b,f?d.call(a[o],o,e(a[o],b)):d,j);return a}return i? e(a[0],b):w}function J(){return(new Date).getTime()}function Y(){return false}function Z(){return true}function na(a,b,d){d[0].type=a;return c.event.handle.apply(b,d)}function oa(a){var b,d=[],f=[],e=arguments,j,i,o,k,n,r;i=c.data(this,"events");if(!(a.liveFired===this||!i||!i.live||a.button&&a.type==="click")){a.liveFired=this;var u=i.live.slice(0);for(k=0;k<u.length;k++){i=u[k];i.origType.replace(O,"")===a.type?f.push(i.selector):u.splice(k--,1)}j=c(a.target).closest(f,a.currentTarget);n=0;for(r= j.length;n<r;n++)for(k=0;k<u.length;k++){i=u[k];if(j[n].selector===i.selector){o=j[n].elem;f=null;if(i.preType==="mouseenter"||i.preType==="mouseleave")f=c(a.relatedTarget).closest(i.selector)[0];if(!f||f!==o)d.push({elem:o,handleObj:i})}}n=0;for(r=d.length;n<r;n++){j=d[n];a.currentTarget=j.elem;a.data=j.handleObj.data;a.handleObj=j.handleObj;if(j.handleObj.origHandler.apply(j.elem,e)===false){b=false;break}}return b}}function pa(a,b){return"live."+(a&&a!=="*"?a+".":"")+b.replace(/\./g,"`").replace(/ /g, "&")}function qa(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function ra(a,b){var d=0;b.each(function(){if(this.nodeName===(a[d]&&a[d].nodeName)){var f=c.data(a[d++]),e=c.data(this,f);if(f=f&&f.events){delete e.handle;e.events={};for(var j in f)for(var i in f[j])c.event.add(this,j,f[j][i],f[j][i].data)}}})}function sa(a,b,d){var f,e,j;b=b&&b[0]?b[0].ownerDocument||b[0]:s;if(a.length===1&&typeof a[0]==="string"&&a[0].length<512&&b===s&&!ta.test(a[0])&&(c.support.checkClone||!ua.test(a[0]))){e= true;if(j=c.fragments[a[0]])if(j!==1)f=j}if(!f){f=b.createDocumentFragment();c.clean(a,b,f,d)}if(e)c.fragments[a[0]]=j?f:1;return{fragment:f,cacheable:e}}function K(a,b){var d={};c.each(va.concat.apply([],va.slice(0,b)),function(){d[this]=a});return d}function wa(a){return"scrollTo"in a&&a.document?a:a.nodeType===9?a.defaultView||a.parentWindow:false}var c=function(a,b){return new c.fn.init(a,b)},Ra=A.jQuery,Sa=A.$,s=A.document,T,Ta=/^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,Ua=/^.[^:#\[\.,]*$/,Va=/\S/, Wa=/^(\s|\u00A0)+|(\s|\u00A0)+$/g,Xa=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,P=navigator.userAgent,xa=false,Q=[],L,$=Object.prototype.toString,aa=Object.prototype.hasOwnProperty,ba=Array.prototype.push,R=Array.prototype.slice,ya=Array.prototype.indexOf;c.fn=c.prototype={init:function(a,b){var d,f;if(!a)return this;if(a.nodeType){this.context=this[0]=a;this.length=1;return this}if(a==="body"&&!b){this.context=s;this[0]=s.body;this.selector="body";this.length=1;return this}if(typeof a==="string")if((d=Ta.exec(a))&& (d[1]||!b))if(d[1]){f=b?b.ownerDocument||b:s;if(a=Xa.exec(a))if(c.isPlainObject(b)){a=[s.createElement(a[1])];c.fn.attr.call(a,b,true)}else a=[f.createElement(a[1])];else{a=sa([d[1]],[f]);a=(a.cacheable?a.fragment.cloneNode(true):a.fragment).childNodes}return c.merge(this,a)}else{if(b=s.getElementById(d[2])){if(b.id!==d[2])return T.find(a);this.length=1;this[0]=b}this.context=s;this.selector=a;return this}else if(!b&&/^\w+$/.test(a)){this.selector=a;this.context=s;a=s.getElementsByTagName(a);return c.merge(this, a)}else return!b||b.jquery?(b||T).find(a):c(b).find(a);else if(c.isFunction(a))return T.ready(a);if(a.selector!==w){this.selector=a.selector;this.context=a.context}return c.makeArray(a,this)},selector:"",jquery:"1.4.2",length:0,size:function(){return this.length},toArray:function(){return R.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this.slice(a)[0]:this[a]},pushStack:function(a,b,d){var f=c();c.isArray(a)?ba.apply(f,a):c.merge(f,a);f.prevObject=this;f.context=this.context;if(b=== "find")f.selector=this.selector+(this.selector?" ":"")+d;else if(b)f.selector=this.selector+"."+b+"("+d+")";return f},each:function(a,b){return c.each(this,a,b)},ready:function(a){c.bindReady();if(c.isReady)a.call(s,c);else Q&&Q.push(a);return this},eq:function(a){return a===-1?this.slice(a):this.slice(a,+a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(R.apply(this,arguments),"slice",R.call(arguments).join(","))},map:function(a){return this.pushStack(c.map(this, function(b,d){return a.call(b,d,b)}))},end:function(){return this.prevObject||c(null)},push:ba,sort:[].sort,splice:[].splice};c.fn.init.prototype=c.fn;c.extend=c.fn.extend=function(){var a=arguments[0]||{},b=1,d=arguments.length,f=false,e,j,i,o;if(typeof a==="boolean"){f=a;a=arguments[1]||{};b=2}if(typeof a!=="object"&&!c.isFunction(a))a={};if(d===b){a=this;--b}for(;b<d;b++)if((e=arguments[b])!=null)for(j in e){i=a[j];o=e[j];if(a!==o)if(f&&o&&(c.isPlainObject(o)||c.isArray(o))){i=i&&(c.isPlainObject(i)|| c.isArray(i))?i:c.isArray(o)?[]:{};a[j]=c.extend(f,i,o)}else if(o!==w)a[j]=o}return a};c.extend({noConflict:function(a){A.$=Sa;if(a)A.jQuery=Ra;return c},isReady:false,ready:function(){if(!c.isReady){if(!s.body)return setTimeout(c.ready,13);c.isReady=true;if(Q){for(var a,b=0;a=Q[b++];)a.call(s,c);Q=null}c.fn.triggerHandler&&c(s).triggerHandler("ready")}},bindReady:function(){if(!xa){xa=true;if(s.readyState==="complete")return c.ready();if(s.addEventListener){s.addEventListener("DOMContentLoaded", L,false);A.addEventListener("load",c.ready,false)}else if(s.attachEvent){s.attachEvent("onreadystatechange",L);A.attachEvent("onload",c.ready);var a=false;try{a=A.frameElement==null}catch(b){}s.documentElement.doScroll&&a&&ma()}}},isFunction:function(a){return $.call(a)==="[object Function]"},isArray:function(a){return $.call(a)==="[object Array]"},isPlainObject:function(a){if(!a||$.call(a)!=="[object Object]"||a.nodeType||a.setInterval)return false;if(a.constructor&&!aa.call(a,"constructor")&&!aa.call(a.constructor.prototype, "isPrototypeOf"))return false;var b;for(b in a);return b===w||aa.call(a,b)},isEmptyObject:function(a){for(var b in a)return false;return true},error:function(a){throw a;},parseJSON:function(a){if(typeof a!=="string"||!a)return null;a=c.trim(a);if(/^[\],:{}\s]*$/.test(a.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return A.JSON&&A.JSON.parse?A.JSON.parse(a):(new Function("return "+ a))();else c.error("Invalid JSON: "+a)},noop:function(){},globalEval:function(a){if(a&&Va.test(a)){var b=s.getElementsByTagName("head")[0]||s.documentElement,d=s.createElement("script");d.type="text/javascript";if(c.support.scriptEval)d.appendChild(s.createTextNode(a));else d.text=a;b.insertBefore(d,b.firstChild);b.removeChild(d)}},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,b,d){var f,e=0,j=a.length,i=j===w||c.isFunction(a);if(d)if(i)for(f in a){if(b.apply(a[f], d)===false)break}else for(;e<j;){if(b.apply(a[e++],d)===false)break}else if(i)for(f in a){if(b.call(a[f],f,a[f])===false)break}else for(d=a[0];e<j&&b.call(d,e,d)!==false;d=a[++e]);return a},trim:function(a){return(a||"").replace(Wa,"")},makeArray:function(a,b){b=b||[];if(a!=null)a.length==null||typeof a==="string"||c.isFunction(a)||typeof a!=="function"&&a.setInterval?ba.call(b,a):c.merge(b,a);return b},inArray:function(a,b){if(b.indexOf)return b.indexOf(a);for(var d=0,f=b.length;d<f;d++)if(b[d]=== a)return d;return-1},merge:function(a,b){var d=a.length,f=0;if(typeof b.length==="number")for(var e=b.length;f<e;f++)a[d++]=b[f];else for(;b[f]!==w;)a[d++]=b[f++];a.length=d;return a},grep:function(a,b,d){for(var f=[],e=0,j=a.length;e<j;e++)!d!==!b(a[e],e)&&f.push(a[e]);return f},map:function(a,b,d){for(var f=[],e,j=0,i=a.length;j<i;j++){e=b(a[j],j,d);if(e!=null)f[f.length]=e}return f.concat.apply([],f)},guid:1,proxy:function(a,b,d){if(arguments.length===2)if(typeof b==="string"){d=a;a=d[b];b=w}else if(b&& !c.isFunction(b)){d=b;b=w}if(!b&&a)b=function(){return a.apply(d||this,arguments)};if(a)b.guid=a.guid=a.guid||b.guid||c.guid++;return b},uaMatch:function(a){a=a.toLowerCase();a=/(webkit)[ \/]([\w.]+)/.exec(a)||/(opera)(?:.*version)?[ \/]([\w.]+)/.exec(a)||/(msie) ([\w.]+)/.exec(a)||!/compatible/.test(a)&&/(mozilla)(?:.*? rv:([\w.]+))?/.exec(a)||[];return{browser:a[1]||"",version:a[2]||"0"}},browser:{}});P=c.uaMatch(P);if(P.browser){c.browser[P.browser]=true;c.browser.version=P.version}if(c.browser.webkit)c.browser.safari= true;if(ya)c.inArray=function(a,b){return ya.call(b,a)};T=c(s);if(s.addEventListener)L=function(){s.removeEventListener("DOMContentLoaded",L,false);c.ready()};else if(s.attachEvent)L=function(){if(s.readyState==="complete"){s.detachEvent("onreadystatechange",L);c.ready()}};(function(){c.support={};var a=s.documentElement,b=s.createElement("script"),d=s.createElement("div"),f="script"+J();d.style.display="none";d.innerHTML=" <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>"; var e=d.getElementsByTagName("*"),j=d.getElementsByTagName("a")[0];if(!(!e||!e.length||!j)){c.support={leadingWhitespace:d.firstChild.nodeType===3,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/red/.test(j.getAttribute("style")),hrefNormalized:j.getAttribute("href")==="/a",opacity:/^0.55$/.test(j.style.opacity),cssFloat:!!j.style.cssFloat,checkOn:d.getElementsByTagName("input")[0].value==="on",optSelected:s.createElement("select").appendChild(s.createElement("option")).selected, parentNode:d.removeChild(d.appendChild(s.createElement("div"))).parentNode===null,deleteExpando:true,checkClone:false,scriptEval:false,noCloneEvent:true,boxModel:null};b.type="text/javascript";try{b.appendChild(s.createTextNode("window."+f+"=1;"))}catch(i){}a.insertBefore(b,a.firstChild);if(A[f]){c.support.scriptEval=true;delete A[f]}try{delete b.test}catch(o){c.support.deleteExpando=false}a.removeChild(b);if(d.attachEvent&&d.fireEvent){d.attachEvent("onclick",function k(){c.support.noCloneEvent= false;d.detachEvent("onclick",k)});d.cloneNode(true).fireEvent("onclick")}d=s.createElement("div");d.innerHTML="<input type='radio' name='radiotest' checked='checked'/>";a=s.createDocumentFragment();a.appendChild(d.firstChild);c.support.checkClone=a.cloneNode(true).cloneNode(true).lastChild.checked;c(function(){var k=s.createElement("div");k.style.width=k.style.paddingLeft="1px";s.body.appendChild(k);c.boxModel=c.support.boxModel=k.offsetWidth===2;s.body.removeChild(k).style.display="none"});a=function(k){var n= s.createElement("div");k="on"+k;var r=k in n;if(!r){n.setAttribute(k,"return;");r=typeof n[k]==="function"}return r};c.support.submitBubbles=a("submit");c.support.changeBubbles=a("change");a=b=d=e=j=null}})();c.props={"for":"htmlFor","class":"className",readonly:"readOnly",maxlength:"maxLength",cellspacing:"cellSpacing",rowspan:"rowSpan",colspan:"colSpan",tabindex:"tabIndex",usemap:"useMap",frameborder:"frameBorder"};var G="jQuery"+J(),Ya=0,za={};c.extend({cache:{},expando:G,noData:{embed:true,object:true, applet:true},data:function(a,b,d){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var f=a[G],e=c.cache;if(!f&&typeof b==="string"&&d===w)return null;f||(f=++Ya);if(typeof b==="object"){a[G]=f;e[f]=c.extend(true,{},b)}else if(!e[f]){a[G]=f;e[f]={}}a=e[f];if(d!==w)a[b]=d;return typeof b==="string"?a[b]:a}},removeData:function(a,b){if(!(a.nodeName&&c.noData[a.nodeName.toLowerCase()])){a=a==A?za:a;var d=a[G],f=c.cache,e=f[d];if(b){if(e){delete e[b];c.isEmptyObject(e)&&c.removeData(a)}}else{if(c.support.deleteExpando)delete a[c.expando]; else a.removeAttribute&&a.removeAttribute(c.expando);delete f[d]}}}});c.fn.extend({data:function(a,b){if(typeof a==="undefined"&&this.length)return c.data(this[0]);else if(typeof a==="object")return this.each(function(){c.data(this,a)});var d=a.split(".");d[1]=d[1]?"."+d[1]:"";if(b===w){var f=this.triggerHandler("getData"+d[1]+"!",[d[0]]);if(f===w&&this.length)f=c.data(this[0],a);return f===w&&d[1]?this.data(d[0]):f}else return this.trigger("setData"+d[1]+"!",[d[0],b]).each(function(){c.data(this, a,b)})},removeData:function(a){return this.each(function(){c.removeData(this,a)})}});c.extend({queue:function(a,b,d){if(a){b=(b||"fx")+"queue";var f=c.data(a,b);if(!d)return f||[];if(!f||c.isArray(d))f=c.data(a,b,c.makeArray(d));else f.push(d);return f}},dequeue:function(a,b){b=b||"fx";var d=c.queue(a,b),f=d.shift();if(f==="inprogress")f=d.shift();if(f){b==="fx"&&d.unshift("inprogress");f.call(a,function(){c.dequeue(a,b)})}}});c.fn.extend({queue:function(a,b){if(typeof a!=="string"){b=a;a="fx"}if(b=== w)return c.queue(this[0],a);return this.each(function(){var d=c.queue(this,a,b);a==="fx"&&d[0]!=="inprogress"&&c.dequeue(this,a)})},dequeue:function(a){return this.each(function(){c.dequeue(this,a)})},delay:function(a,b){a=c.fx?c.fx.speeds[a]||a:a;b=b||"fx";return this.queue(b,function(){var d=this;setTimeout(function(){c.dequeue(d,b)},a)})},clearQueue:function(a){return this.queue(a||"fx",[])}});var Aa=/[\n\t]/g,ca=/\s+/,Za=/\r/g,$a=/href|src|style/,ab=/(button|input)/i,bb=/(button|input|object|select|textarea)/i, cb=/^(a|area)$/i,Ba=/radio|checkbox/;c.fn.extend({attr:function(a,b){return X(this,a,b,true,c.attr)},removeAttr:function(a){return this.each(function(){c.attr(this,a,"");this.nodeType===1&&this.removeAttribute(a)})},addClass:function(a){if(c.isFunction(a))return this.each(function(n){var r=c(this);r.addClass(a.call(this,n,r.attr("class")))});if(a&&typeof a==="string")for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1)if(e.className){for(var j=" "+e.className+" ", i=e.className,o=0,k=b.length;o<k;o++)if(j.indexOf(" "+b[o]+" ")<0)i+=" "+b[o];e.className=c.trim(i)}else e.className=a}return this},removeClass:function(a){if(c.isFunction(a))return this.each(function(k){var n=c(this);n.removeClass(a.call(this,k,n.attr("class")))});if(a&&typeof a==="string"||a===w)for(var b=(a||"").split(ca),d=0,f=this.length;d<f;d++){var e=this[d];if(e.nodeType===1&&e.className)if(a){for(var j=(" "+e.className+" ").replace(Aa," "),i=0,o=b.length;i<o;i++)j=j.replace(" "+b[i]+" ", " ");e.className=c.trim(j)}else e.className=""}return this},toggleClass:function(a,b){var d=typeof a,f=typeof b==="boolean";if(c.isFunction(a))return this.each(function(e){var j=c(this);j.toggleClass(a.call(this,e,j.attr("class"),b),b)});return this.each(function(){if(d==="string")for(var e,j=0,i=c(this),o=b,k=a.split(ca);e=k[j++];){o=f?o:!i.hasClass(e);i[o?"addClass":"removeClass"](e)}else if(d==="undefined"||d==="boolean"){this.className&&c.data(this,"__className__",this.className);this.className= this.className||a===false?"":c.data(this,"__className__")||""}})},hasClass:function(a){a=" "+a+" ";for(var b=0,d=this.length;b<d;b++)if((" "+this[b].className+" ").replace(Aa," ").indexOf(a)>-1)return true;return false},val:function(a){if(a===w){var b=this[0];if(b){if(c.nodeName(b,"option"))return(b.attributes.value||{}).specified?b.value:b.text;if(c.nodeName(b,"select")){var d=b.selectedIndex,f=[],e=b.options;b=b.type==="select-one";if(d<0)return null;var j=b?d:0;for(d=b?d+1:e.length;j<d;j++){var i= e[j];if(i.selected){a=c(i).val();if(b)return a;f.push(a)}}return f}if(Ba.test(b.type)&&!c.support.checkOn)return b.getAttribute("value")===null?"on":b.value;return(b.value||"").replace(Za,"")}return w}var o=c.isFunction(a);return this.each(function(k){var n=c(this),r=a;if(this.nodeType===1){if(o)r=a.call(this,k,n.val());if(typeof r==="number")r+="";if(c.isArray(r)&&Ba.test(this.type))this.checked=c.inArray(n.val(),r)>=0;else if(c.nodeName(this,"select")){var u=c.makeArray(r);c("option",this).each(function(){this.selected= c.inArray(c(this).val(),u)>=0});if(!u.length)this.selectedIndex=-1}else this.value=r}})}});c.extend({attrFn:{val:true,css:true,html:true,text:true,data:true,width:true,height:true,offset:true},attr:function(a,b,d,f){if(!a||a.nodeType===3||a.nodeType===8)return w;if(f&&b in c.attrFn)return c(a)[b](d);f=a.nodeType!==1||!c.isXMLDoc(a);var e=d!==w;b=f&&c.props[b]||b;if(a.nodeType===1){var j=$a.test(b);if(b in a&&f&&!j){if(e){b==="type"&&ab.test(a.nodeName)&&a.parentNode&&c.error("type property can't be changed"); a[b]=d}if(c.nodeName(a,"form")&&a.getAttributeNode(b))return a.getAttributeNode(b).nodeValue;if(b==="tabIndex")return(b=a.getAttributeNode("tabIndex"))&&b.specified?b.value:bb.test(a.nodeName)||cb.test(a.nodeName)&&a.href?0:w;return a[b]}if(!c.support.style&&f&&b==="style"){if(e)a.style.cssText=""+d;return a.style.cssText}e&&a.setAttribute(b,""+d);a=!c.support.hrefNormalized&&f&&j?a.getAttribute(b,2):a.getAttribute(b);return a===null?w:a}return c.style(a,b,d)}});var O=/\.(.*)$/,db=function(a){return a.replace(/[^\w\s\.\|`]/g, function(b){return"\\"+b})};c.event={add:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){if(a.setInterval&&a!==A&&!a.frameElement)a=A;var e,j;if(d.handler){e=d;d=e.handler}if(!d.guid)d.guid=c.guid++;if(j=c.data(a)){var i=j.events=j.events||{},o=j.handle;if(!o)j.handle=o=function(){return typeof c!=="undefined"&&!c.event.triggered?c.event.handle.apply(o.elem,arguments):w};o.elem=a;b=b.split(" ");for(var k,n=0,r;k=b[n++];){j=e?c.extend({},e):{handler:d,data:f};if(k.indexOf(".")>-1){r=k.split("."); k=r.shift();j.namespace=r.slice(0).sort().join(".")}else{r=[];j.namespace=""}j.type=k;j.guid=d.guid;var u=i[k],z=c.event.special[k]||{};if(!u){u=i[k]=[];if(!z.setup||z.setup.call(a,f,r,o)===false)if(a.addEventListener)a.addEventListener(k,o,false);else a.attachEvent&&a.attachEvent("on"+k,o)}if(z.add){z.add.call(a,j);if(!j.handler.guid)j.handler.guid=d.guid}u.push(j);c.event.global[k]=true}a=null}}},global:{},remove:function(a,b,d,f){if(!(a.nodeType===3||a.nodeType===8)){var e,j=0,i,o,k,n,r,u,z=c.data(a), C=z&&z.events;if(z&&C){if(b&&b.type){d=b.handler;b=b.type}if(!b||typeof b==="string"&&b.charAt(0)==="."){b=b||"";for(e in C)c.event.remove(a,e+b)}else{for(b=b.split(" ");e=b[j++];){n=e;i=e.indexOf(".")<0;o=[];if(!i){o=e.split(".");e=o.shift();k=new RegExp("(^|\\.)"+c.map(o.slice(0).sort(),db).join("\\.(?:.*\\.)?")+"(\\.|$)")}if(r=C[e])if(d){n=c.event.special[e]||{};for(B=f||0;B<r.length;B++){u=r[B];if(d.guid===u.guid){if(i||k.test(u.namespace)){f==null&&r.splice(B--,1);n.remove&&n.remove.call(a,u)}if(f!= null)break}}if(r.length===0||f!=null&&r.length===1){if(!n.teardown||n.teardown.call(a,o)===false)Ca(a,e,z.handle);delete C[e]}}else for(var B=0;B<r.length;B++){u=r[B];if(i||k.test(u.namespace)){c.event.remove(a,n,u.handler,B);r.splice(B--,1)}}}if(c.isEmptyObject(C)){if(b=z.handle)b.elem=null;delete z.events;delete z.handle;c.isEmptyObject(z)&&c.removeData(a)}}}}},trigger:function(a,b,d,f){var e=a.type||a;if(!f){a=typeof a==="object"?a[G]?a:c.extend(c.Event(e),a):c.Event(e);if(e.indexOf("!")>=0){a.type= e=e.slice(0,-1);a.exclusive=true}if(!d){a.stopPropagation();c.event.global[e]&&c.each(c.cache,function(){this.events&&this.events[e]&&c.event.trigger(a,b,this.handle.elem)})}if(!d||d.nodeType===3||d.nodeType===8)return w;a.result=w;a.target=d;b=c.makeArray(b);b.unshift(a)}a.currentTarget=d;(f=c.data(d,"handle"))&&f.apply(d,b);f=d.parentNode||d.ownerDocument;try{if(!(d&&d.nodeName&&c.noData[d.nodeName.toLowerCase()]))if(d["on"+e]&&d["on"+e].apply(d,b)===false)a.result=false}catch(j){}if(!a.isPropagationStopped()&& f)c.event.trigger(a,b,f,true);else if(!a.isDefaultPrevented()){f=a.target;var i,o=c.nodeName(f,"a")&&e==="click",k=c.event.special[e]||{};if((!k._default||k._default.call(d,a)===false)&&!o&&!(f&&f.nodeName&&c.noData[f.nodeName.toLowerCase()])){try{if(f[e]){if(i=f["on"+e])f["on"+e]=null;c.event.triggered=true;f[e]()}}catch(n){}if(i)f["on"+e]=i;c.event.triggered=false}}},handle:function(a){var b,d,f,e;a=arguments[0]=c.event.fix(a||A.event);a.currentTarget=this;b=a.type.indexOf(".")<0&&!a.exclusive; if(!b){d=a.type.split(".");a.type=d.shift();f=new RegExp("(^|\\.)"+d.slice(0).sort().join("\\.(?:.*\\.)?")+"(\\.|$)")}e=c.data(this,"events");d=e[a.type];if(e&&d){d=d.slice(0);e=0;for(var j=d.length;e<j;e++){var i=d[e];if(b||f.test(i.namespace)){a.handler=i.handler;a.data=i.data;a.handleObj=i;i=i.handler.apply(this,arguments);if(i!==w){a.result=i;if(i===false){a.preventDefault();a.stopPropagation()}}if(a.isImmediatePropagationStopped())break}}}return a.result},props:"altKey attrChange attrName bubbles button cancelable charCode clientX clientY ctrlKey currentTarget data detail eventPhase fromElement handler keyCode layerX layerY metaKey newValue offsetX offsetY originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "), fix:function(a){if(a[G])return a;var b=a;a=c.Event(b);for(var d=this.props.length,f;d;){f=this.props[--d];a[f]=b[f]}if(!a.target)a.target=a.srcElement||s;if(a.target.nodeType===3)a.target=a.target.parentNode;if(!a.relatedTarget&&a.fromElement)a.relatedTarget=a.fromElement===a.target?a.toElement:a.fromElement;if(a.pageX==null&&a.clientX!=null){b=s.documentElement;d=s.body;a.pageX=a.clientX+(b&&b.scrollLeft||d&&d.scrollLeft||0)-(b&&b.clientLeft||d&&d.clientLeft||0);a.pageY=a.clientY+(b&&b.scrollTop|| d&&d.scrollTop||0)-(b&&b.clientTop||d&&d.clientTop||0)}if(!a.which&&(a.charCode||a.charCode===0?a.charCode:a.keyCode))a.which=a.charCode||a.keyCode;if(!a.metaKey&&a.ctrlKey)a.metaKey=a.ctrlKey;if(!a.which&&a.button!==w)a.which=a.button&1?1:a.button&2?3:a.button&4?2:0;return a},guid:1E8,proxy:c.proxy,special:{ready:{setup:c.bindReady,teardown:c.noop},live:{add:function(a){c.event.add(this,a.origType,c.extend({},a,{handler:oa}))},remove:function(a){var b=true,d=a.origType.replace(O,"");c.each(c.data(this, "events").live||[],function(){if(d===this.origType.replace(O,""))return b=false});b&&c.event.remove(this,a.origType,oa)}},beforeunload:{setup:function(a,b,d){if(this.setInterval)this.onbeforeunload=d;return false},teardown:function(a,b){if(this.onbeforeunload===b)this.onbeforeunload=null}}}};var Ca=s.removeEventListener?function(a,b,d){a.removeEventListener(b,d,false)}:function(a,b,d){a.detachEvent("on"+b,d)};c.Event=function(a){if(!this.preventDefault)return new c.Event(a);if(a&&a.type){this.originalEvent= a;this.type=a.type}else this.type=a;this.timeStamp=J();this[G]=true};c.Event.prototype={preventDefault:function(){this.isDefaultPrevented=Z;var a=this.originalEvent;if(a){a.preventDefault&&a.preventDefault();a.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=Z;var a=this.originalEvent;if(a){a.stopPropagation&&a.stopPropagation();a.cancelBubble=true}},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=Z;this.stopPropagation()},isDefaultPrevented:Y,isPropagationStopped:Y, isImmediatePropagationStopped:Y};var Da=function(a){var b=a.relatedTarget;try{for(;b&&b!==this;)b=b.parentNode;if(b!==this){a.type=a.data;c.event.handle.apply(this,arguments)}}catch(d){}},Ea=function(a){a.type=a.data;c.event.handle.apply(this,arguments)};c.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){c.event.special[a]={setup:function(d){c.event.add(this,b,d&&d.selector?Ea:Da,a)},teardown:function(d){c.event.remove(this,b,d&&d.selector?Ea:Da)}}});if(!c.support.submitBubbles)c.event.special.submit= {setup:function(){if(this.nodeName.toLowerCase()!=="form"){c.event.add(this,"click.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="submit"||d==="image")&&c(b).closest("form").length)return na("submit",this,arguments)});c.event.add(this,"keypress.specialSubmit",function(a){var b=a.target,d=b.type;if((d==="text"||d==="password")&&c(b).closest("form").length&&a.keyCode===13)return na("submit",this,arguments)})}else return false},teardown:function(){c.event.remove(this,".specialSubmit")}}; if(!c.support.changeBubbles){var da=/textarea|input|select/i,ea,Fa=function(a){var b=a.type,d=a.value;if(b==="radio"||b==="checkbox")d=a.checked;else if(b==="select-multiple")d=a.selectedIndex>-1?c.map(a.options,function(f){return f.selected}).join("-"):"";else if(a.nodeName.toLowerCase()==="select")d=a.selectedIndex;return d},fa=function(a,b){var d=a.target,f,e;if(!(!da.test(d.nodeName)||d.readOnly)){f=c.data(d,"_change_data");e=Fa(d);if(a.type!=="focusout"||d.type!=="radio")c.data(d,"_change_data", e);if(!(f===w||e===f))if(f!=null||e){a.type="change";return c.event.trigger(a,b,d)}}};c.event.special.change={filters:{focusout:fa,click:function(a){var b=a.target,d=b.type;if(d==="radio"||d==="checkbox"||b.nodeName.toLowerCase()==="select")return fa.call(this,a)},keydown:function(a){var b=a.target,d=b.type;if(a.keyCode===13&&b.nodeName.toLowerCase()!=="textarea"||a.keyCode===32&&(d==="checkbox"||d==="radio")||d==="select-multiple")return fa.call(this,a)},beforeactivate:function(a){a=a.target;c.data(a, "_change_data",Fa(a))}},setup:function(){if(this.type==="file")return false;for(var a in ea)c.event.add(this,a+".specialChange",ea[a]);return da.test(this.nodeName)},teardown:function(){c.event.remove(this,".specialChange");return da.test(this.nodeName)}};ea=c.event.special.change.filters}s.addEventListener&&c.each({focus:"focusin",blur:"focusout"},function(a,b){function d(f){f=c.event.fix(f);f.type=b;return c.event.handle.call(this,f)}c.event.special[b]={setup:function(){this.addEventListener(a, d,true)},teardown:function(){this.removeEventListener(a,d,true)}}});c.each(["bind","one"],function(a,b){c.fn[b]=function(d,f,e){if(typeof d==="object"){for(var j in d)this[b](j,f,d[j],e);return this}if(c.isFunction(f)){e=f;f=w}var i=b==="one"?c.proxy(e,function(k){c(this).unbind(k,i);return e.apply(this,arguments)}):e;if(d==="unload"&&b!=="one")this.one(d,f,e);else{j=0;for(var o=this.length;j<o;j++)c.event.add(this[j],d,i,f)}return this}});c.fn.extend({unbind:function(a,b){if(typeof a==="object"&& !a.preventDefault)for(var d in a)this.unbind(d,a[d]);else{d=0;for(var f=this.length;d<f;d++)c.event.remove(this[d],a,b)}return this},delegate:function(a,b,d,f){return this.live(b,d,f,a)},undelegate:function(a,b,d){return arguments.length===0?this.unbind("live"):this.die(b,null,d,a)},trigger:function(a,b){return this.each(function(){c.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0]){a=c.Event(a);a.preventDefault();a.stopPropagation();c.event.trigger(a,b,this[0]);return a.result}}, toggle:function(a){for(var b=arguments,d=1;d<b.length;)c.proxy(a,b[d++]);return this.click(c.proxy(a,function(f){var e=(c.data(this,"lastToggle"+a.guid)||0)%d;c.data(this,"lastToggle"+a.guid,e+1);f.preventDefault();return b[e].apply(this,arguments)||false}))},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}});var Ga={focus:"focusin",blur:"focusout",mouseenter:"mouseover",mouseleave:"mouseout"};c.each(["live","die"],function(a,b){c.fn[b]=function(d,f,e,j){var i,o=0,k,n,r=j||this.selector, u=j?this:c(this.context);if(c.isFunction(f)){e=f;f=w}for(d=(d||"").split(" ");(i=d[o++])!=null;){j=O.exec(i);k="";if(j){k=j[0];i=i.replace(O,"")}if(i==="hover")d.push("mouseenter"+k,"mouseleave"+k);else{n=i;if(i==="focus"||i==="blur"){d.push(Ga[i]+k);i+=k}else i=(Ga[i]||i)+k;b==="live"?u.each(function(){c.event.add(this,pa(i,r),{data:f,selector:r,handler:e,origType:i,origHandler:e,preType:n})}):u.unbind(pa(i,r),e)}}return this}});c.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error".split(" "), function(a,b){c.fn[b]=function(d){return d?this.bind(b,d):this.trigger(b)};if(c.attrFn)c.attrFn[b]=true});A.attachEvent&&!A.addEventListener&&A.attachEvent("onunload",function(){for(var a in c.cache)if(c.cache[a].handle)try{c.event.remove(c.cache[a].handle.elem)}catch(b){}});(function(){function a(g){for(var h="",l,m=0;g[m];m++){l=g[m];if(l.nodeType===3||l.nodeType===4)h+=l.nodeValue;else if(l.nodeType!==8)h+=a(l.childNodes)}return h}function b(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q]; if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1&&!p){t.sizcache=l;t.sizset=q}if(t.nodeName.toLowerCase()===h){y=t;break}t=t[g]}m[q]=y}}}function d(g,h,l,m,q,p){q=0;for(var v=m.length;q<v;q++){var t=m[q];if(t){t=t[g];for(var y=false;t;){if(t.sizcache===l){y=m[t.sizset];break}if(t.nodeType===1){if(!p){t.sizcache=l;t.sizset=q}if(typeof h!=="string"){if(t===h){y=true;break}}else if(k.filter(h,[t]).length>0){y=t;break}}t=t[g]}m[q]=y}}}var f=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g, e=0,j=Object.prototype.toString,i=false,o=true;[0,0].sort(function(){o=false;return 0});var k=function(g,h,l,m){l=l||[];var q=h=h||s;if(h.nodeType!==1&&h.nodeType!==9)return[];if(!g||typeof g!=="string")return l;for(var p=[],v,t,y,S,H=true,M=x(h),I=g;(f.exec(""),v=f.exec(I))!==null;){I=v[3];p.push(v[1]);if(v[2]){S=v[3];break}}if(p.length>1&&r.exec(g))if(p.length===2&&n.relative[p[0]])t=ga(p[0]+p[1],h);else for(t=n.relative[p[0]]?[h]:k(p.shift(),h);p.length;){g=p.shift();if(n.relative[g])g+=p.shift(); t=ga(g,t)}else{if(!m&&p.length>1&&h.nodeType===9&&!M&&n.match.ID.test(p[0])&&!n.match.ID.test(p[p.length-1])){v=k.find(p.shift(),h,M);h=v.expr?k.filter(v.expr,v.set)[0]:v.set[0]}if(h){v=m?{expr:p.pop(),set:z(m)}:k.find(p.pop(),p.length===1&&(p[0]==="~"||p[0]==="+")&&h.parentNode?h.parentNode:h,M);t=v.expr?k.filter(v.expr,v.set):v.set;if(p.length>0)y=z(t);else H=false;for(;p.length;){var D=p.pop();v=D;if(n.relative[D])v=p.pop();else D="";if(v==null)v=h;n.relative[D](y,v,M)}}else y=[]}y||(y=t);y||k.error(D|| g);if(j.call(y)==="[object Array]")if(H)if(h&&h.nodeType===1)for(g=0;y[g]!=null;g++){if(y[g]&&(y[g]===true||y[g].nodeType===1&&E(h,y[g])))l.push(t[g])}else for(g=0;y[g]!=null;g++)y[g]&&y[g].nodeType===1&&l.push(t[g]);else l.push.apply(l,y);else z(y,l);if(S){k(S,q,l,m);k.uniqueSort(l)}return l};k.uniqueSort=function(g){if(B){i=o;g.sort(B);if(i)for(var h=1;h<g.length;h++)g[h]===g[h-1]&&g.splice(h--,1)}return g};k.matches=function(g,h){return k(g,null,null,h)};k.find=function(g,h,l){var m,q;if(!g)return[]; for(var p=0,v=n.order.length;p<v;p++){var t=n.order[p];if(q=n.leftMatch[t].exec(g)){var y=q[1];q.splice(1,1);if(y.substr(y.length-1)!=="\\"){q[1]=(q[1]||"").replace(/\\/g,"");m=n.find[t](q,h,l);if(m!=null){g=g.replace(n.match[t],"");break}}}}m||(m=h.getElementsByTagName("*"));return{set:m,expr:g}};k.filter=function(g,h,l,m){for(var q=g,p=[],v=h,t,y,S=h&&h[0]&&x(h[0]);g&&h.length;){for(var H in n.filter)if((t=n.leftMatch[H].exec(g))!=null&&t[2]){var M=n.filter[H],I,D;D=t[1];y=false;t.splice(1,1);if(D.substr(D.length- 1)!=="\\"){if(v===p)p=[];if(n.preFilter[H])if(t=n.preFilter[H](t,v,l,p,m,S)){if(t===true)continue}else y=I=true;if(t)for(var U=0;(D=v[U])!=null;U++)if(D){I=M(D,t,U,v);var Ha=m^!!I;if(l&&I!=null)if(Ha)y=true;else v[U]=false;else if(Ha){p.push(D);y=true}}if(I!==w){l||(v=p);g=g.replace(n.match[H],"");if(!y)return[];break}}}if(g===q)if(y==null)k.error(g);else break;q=g}return v};k.error=function(g){throw"Syntax error, unrecognized expression: "+g;};var n=k.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF-]|\\.)+)/, CLASS:/\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(g){return g.getAttribute("href")}}, relative:{"+":function(g,h){var l=typeof h==="string",m=l&&!/\W/.test(h);l=l&&!m;if(m)h=h.toLowerCase();m=0;for(var q=g.length,p;m<q;m++)if(p=g[m]){for(;(p=p.previousSibling)&&p.nodeType!==1;);g[m]=l||p&&p.nodeName.toLowerCase()===h?p||false:p===h}l&&k.filter(h,g,true)},">":function(g,h){var l=typeof h==="string";if(l&&!/\W/.test(h)){h=h.toLowerCase();for(var m=0,q=g.length;m<q;m++){var p=g[m];if(p){l=p.parentNode;g[m]=l.nodeName.toLowerCase()===h?l:false}}}else{m=0;for(q=g.length;m<q;m++)if(p=g[m])g[m]= l?p.parentNode:p.parentNode===h;l&&k.filter(h,g,true)}},"":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("parentNode",h,m,g,p,l)},"~":function(g,h,l){var m=e++,q=d;if(typeof h==="string"&&!/\W/.test(h)){var p=h=h.toLowerCase();q=b}q("previousSibling",h,m,g,p,l)}},find:{ID:function(g,h,l){if(typeof h.getElementById!=="undefined"&&!l)return(g=h.getElementById(g[1]))?[g]:[]},NAME:function(g,h){if(typeof h.getElementsByName!=="undefined"){var l=[]; h=h.getElementsByName(g[1]);for(var m=0,q=h.length;m<q;m++)h[m].getAttribute("name")===g[1]&&l.push(h[m]);return l.length===0?null:l}},TAG:function(g,h){return h.getElementsByTagName(g[1])}},preFilter:{CLASS:function(g,h,l,m,q,p){g=" "+g[1].replace(/\\/g,"")+" ";if(p)return g;p=0;for(var v;(v=h[p])!=null;p++)if(v)if(q^(v.className&&(" "+v.className+" ").replace(/[\t\n]/g," ").indexOf(g)>=0))l||m.push(v);else if(l)h[p]=false;return false},ID:function(g){return g[1].replace(/\\/g,"")},TAG:function(g){return g[1].toLowerCase()}, CHILD:function(g){if(g[1]==="nth"){var h=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(g[2]==="even"&&"2n"||g[2]==="odd"&&"2n+1"||!/\D/.test(g[2])&&"0n+"+g[2]||g[2]);g[2]=h[1]+(h[2]||1)-0;g[3]=h[3]-0}g[0]=e++;return g},ATTR:function(g,h,l,m,q,p){h=g[1].replace(/\\/g,"");if(!p&&n.attrMap[h])g[1]=n.attrMap[h];if(g[2]==="~=")g[4]=" "+g[4]+" ";return g},PSEUDO:function(g,h,l,m,q){if(g[1]==="not")if((f.exec(g[3])||"").length>1||/^\w/.test(g[3]))g[3]=k(g[3],null,null,h);else{g=k.filter(g[3],h,l,true^q);l||m.push.apply(m, g);return false}else if(n.match.POS.test(g[0])||n.match.CHILD.test(g[0]))return true;return g},POS:function(g){g.unshift(true);return g}},filters:{enabled:function(g){return g.disabled===false&&g.type!=="hidden"},disabled:function(g){return g.disabled===true},checked:function(g){return g.checked===true},selected:function(g){return g.selected===true},parent:function(g){return!!g.firstChild},empty:function(g){return!g.firstChild},has:function(g,h,l){return!!k(l[3],g).length},header:function(g){return/h\d/i.test(g.nodeName)}, text:function(g){return"text"===g.type},radio:function(g){return"radio"===g.type},checkbox:function(g){return"checkbox"===g.type},file:function(g){return"file"===g.type},password:function(g){return"password"===g.type},submit:function(g){return"submit"===g.type},image:function(g){return"image"===g.type},reset:function(g){return"reset"===g.type},button:function(g){return"button"===g.type||g.nodeName.toLowerCase()==="button"},input:function(g){return/input|select|textarea|button/i.test(g.nodeName)}}, setFilters:{first:function(g,h){return h===0},last:function(g,h,l,m){return h===m.length-1},even:function(g,h){return h%2===0},odd:function(g,h){return h%2===1},lt:function(g,h,l){return h<l[3]-0},gt:function(g,h,l){return h>l[3]-0},nth:function(g,h,l){return l[3]-0===h},eq:function(g,h,l){return l[3]-0===h}},filter:{PSEUDO:function(g,h,l,m){var q=h[1],p=n.filters[q];if(p)return p(g,l,h,m);else if(q==="contains")return(g.textContent||g.innerText||a([g])||"").indexOf(h[3])>=0;else if(q==="not"){h= h[3];l=0;for(m=h.length;l<m;l++)if(h[l]===g)return false;return true}else k.error("Syntax error, unrecognized expression: "+q)},CHILD:function(g,h){var l=h[1],m=g;switch(l){case "only":case "first":for(;m=m.previousSibling;)if(m.nodeType===1)return false;if(l==="first")return true;m=g;case "last":for(;m=m.nextSibling;)if(m.nodeType===1)return false;return true;case "nth":l=h[2];var q=h[3];if(l===1&&q===0)return true;h=h[0];var p=g.parentNode;if(p&&(p.sizcache!==h||!g.nodeIndex)){var v=0;for(m=p.firstChild;m;m= m.nextSibling)if(m.nodeType===1)m.nodeIndex=++v;p.sizcache=h}g=g.nodeIndex-q;return l===0?g===0:g%l===0&&g/l>=0}},ID:function(g,h){return g.nodeType===1&&g.getAttribute("id")===h},TAG:function(g,h){return h==="*"&&g.nodeType===1||g.nodeName.toLowerCase()===h},CLASS:function(g,h){return(" "+(g.className||g.getAttribute("class"))+" ").indexOf(h)>-1},ATTR:function(g,h){var l=h[1];g=n.attrHandle[l]?n.attrHandle[l](g):g[l]!=null?g[l]:g.getAttribute(l);l=g+"";var m=h[2];h=h[4];return g==null?m==="!=":m=== "="?l===h:m==="*="?l.indexOf(h)>=0:m==="~="?(" "+l+" ").indexOf(h)>=0:!h?l&&g!==false:m==="!="?l!==h:m==="^="?l.indexOf(h)===0:m==="$="?l.substr(l.length-h.length)===h:m==="|="?l===h||l.substr(0,h.length+1)===h+"-":false},POS:function(g,h,l,m){var q=n.setFilters[h[2]];if(q)return q(g,l,h,m)}}},r=n.match.POS;for(var u in n.match){n.match[u]=new RegExp(n.match[u].source+/(?![^\[]*\])(?![^\(]*\))/.source);n.leftMatch[u]=new RegExp(/(^(?:.|\r|\n)*?)/.source+n.match[u].source.replace(/\\(\d+)/g,function(g, h){return"\\"+(h-0+1)}))}var z=function(g,h){g=Array.prototype.slice.call(g,0);if(h){h.push.apply(h,g);return h}return g};try{Array.prototype.slice.call(s.documentElement.childNodes,0)}catch(C){z=function(g,h){h=h||[];if(j.call(g)==="[object Array]")Array.prototype.push.apply(h,g);else if(typeof g.length==="number")for(var l=0,m=g.length;l<m;l++)h.push(g[l]);else for(l=0;g[l];l++)h.push(g[l]);return h}}var B;if(s.documentElement.compareDocumentPosition)B=function(g,h){if(!g.compareDocumentPosition|| !h.compareDocumentPosition){if(g==h)i=true;return g.compareDocumentPosition?-1:1}g=g.compareDocumentPosition(h)&4?-1:g===h?0:1;if(g===0)i=true;return g};else if("sourceIndex"in s.documentElement)B=function(g,h){if(!g.sourceIndex||!h.sourceIndex){if(g==h)i=true;return g.sourceIndex?-1:1}g=g.sourceIndex-h.sourceIndex;if(g===0)i=true;return g};else if(s.createRange)B=function(g,h){if(!g.ownerDocument||!h.ownerDocument){if(g==h)i=true;return g.ownerDocument?-1:1}var l=g.ownerDocument.createRange(),m= h.ownerDocument.createRange();l.setStart(g,0);l.setEnd(g,0);m.setStart(h,0);m.setEnd(h,0);g=l.compareBoundaryPoints(Range.START_TO_END,m);if(g===0)i=true;return g};(function(){var g=s.createElement("div"),h="script"+(new Date).getTime();g.innerHTML="<a name='"+h+"'/>";var l=s.documentElement;l.insertBefore(g,l.firstChild);if(s.getElementById(h)){n.find.ID=function(m,q,p){if(typeof q.getElementById!=="undefined"&&!p)return(q=q.getElementById(m[1]))?q.id===m[1]||typeof q.getAttributeNode!=="undefined"&& q.getAttributeNode("id").nodeValue===m[1]?[q]:w:[]};n.filter.ID=function(m,q){var p=typeof m.getAttributeNode!=="undefined"&&m.getAttributeNode("id");return m.nodeType===1&&p&&p.nodeValue===q}}l.removeChild(g);l=g=null})();(function(){var g=s.createElement("div");g.appendChild(s.createComment(""));if(g.getElementsByTagName("*").length>0)n.find.TAG=function(h,l){l=l.getElementsByTagName(h[1]);if(h[1]==="*"){h=[];for(var m=0;l[m];m++)l[m].nodeType===1&&h.push(l[m]);l=h}return l};g.innerHTML="<a href='#'></a>"; if(g.firstChild&&typeof g.firstChild.getAttribute!=="undefined"&&g.firstChild.getAttribute("href")!=="#")n.attrHandle.href=function(h){return h.getAttribute("href",2)};g=null})();s.querySelectorAll&&function(){var g=k,h=s.createElement("div");h.innerHTML="<p class='TEST'></p>";if(!(h.querySelectorAll&&h.querySelectorAll(".TEST").length===0)){k=function(m,q,p,v){q=q||s;if(!v&&q.nodeType===9&&!x(q))try{return z(q.querySelectorAll(m),p)}catch(t){}return g(m,q,p,v)};for(var l in g)k[l]=g[l];h=null}}(); (function(){var g=s.createElement("div");g.innerHTML="<div class='test e'></div><div class='test'></div>";if(!(!g.getElementsByClassName||g.getElementsByClassName("e").length===0)){g.lastChild.className="e";if(g.getElementsByClassName("e").length!==1){n.order.splice(1,0,"CLASS");n.find.CLASS=function(h,l,m){if(typeof l.getElementsByClassName!=="undefined"&&!m)return l.getElementsByClassName(h[1])};g=null}}})();var E=s.compareDocumentPosition?function(g,h){return!!(g.compareDocumentPosition(h)&16)}: function(g,h){return g!==h&&(g.contains?g.contains(h):true)},x=function(g){return(g=(g?g.ownerDocument||g:0).documentElement)?g.nodeName!=="HTML":false},ga=function(g,h){var l=[],m="",q;for(h=h.nodeType?[h]:h;q=n.match.PSEUDO.exec(g);){m+=q[0];g=g.replace(n.match.PSEUDO,"")}g=n.relative[g]?g+"*":g;q=0;for(var p=h.length;q<p;q++)k(g,h[q],l);return k.filter(m,l)};c.find=k;c.expr=k.selectors;c.expr[":"]=c.expr.filters;c.unique=k.uniqueSort;c.text=a;c.isXMLDoc=x;c.contains=E})();var eb=/Until$/,fb=/^(?:parents|prevUntil|prevAll)/, gb=/,/;R=Array.prototype.slice;var Ia=function(a,b,d){if(c.isFunction(b))return c.grep(a,function(e,j){return!!b.call(e,j,e)===d});else if(b.nodeType)return c.grep(a,function(e){return e===b===d});else if(typeof b==="string"){var f=c.grep(a,function(e){return e.nodeType===1});if(Ua.test(b))return c.filter(b,f,!d);else b=c.filter(b,f)}return c.grep(a,function(e){return c.inArray(e,b)>=0===d})};c.fn.extend({find:function(a){for(var b=this.pushStack("","find",a),d=0,f=0,e=this.length;f<e;f++){d=b.length; c.find(a,this[f],b);if(f>0)for(var j=d;j<b.length;j++)for(var i=0;i<d;i++)if(b[i]===b[j]){b.splice(j--,1);break}}return b},has:function(a){var b=c(a);return this.filter(function(){for(var d=0,f=b.length;d<f;d++)if(c.contains(this,b[d]))return true})},not:function(a){return this.pushStack(Ia(this,a,false),"not",a)},filter:function(a){return this.pushStack(Ia(this,a,true),"filter",a)},is:function(a){return!!a&&c.filter(a,this).length>0},closest:function(a,b){if(c.isArray(a)){var d=[],f=this[0],e,j= {},i;if(f&&a.length){e=0;for(var o=a.length;e<o;e++){i=a[e];j[i]||(j[i]=c.expr.match.POS.test(i)?c(i,b||this.context):i)}for(;f&&f.ownerDocument&&f!==b;){for(i in j){e=j[i];if(e.jquery?e.index(f)>-1:c(f).is(e)){d.push({selector:i,elem:f});delete j[i]}}f=f.parentNode}}return d}var k=c.expr.match.POS.test(a)?c(a,b||this.context):null;return this.map(function(n,r){for(;r&&r.ownerDocument&&r!==b;){if(k?k.index(r)>-1:c(r).is(a))return r;r=r.parentNode}return null})},index:function(a){if(!a||typeof a=== "string")return c.inArray(this[0],a?c(a):this.parent().children());return c.inArray(a.jquery?a[0]:a,this)},add:function(a,b){a=typeof a==="string"?c(a,b||this.context):c.makeArray(a);b=c.merge(this.get(),a);return this.pushStack(qa(a[0])||qa(b[0])?b:c.unique(b))},andSelf:function(){return this.add(this.prevObject)}});c.each({parent:function(a){return(a=a.parentNode)&&a.nodeType!==11?a:null},parents:function(a){return c.dir(a,"parentNode")},parentsUntil:function(a,b,d){return c.dir(a,"parentNode", d)},next:function(a){return c.nth(a,2,"nextSibling")},prev:function(a){return c.nth(a,2,"previousSibling")},nextAll:function(a){return c.dir(a,"nextSibling")},prevAll:function(a){return c.dir(a,"previousSibling")},nextUntil:function(a,b,d){return c.dir(a,"nextSibling",d)},prevUntil:function(a,b,d){return c.dir(a,"previousSibling",d)},siblings:function(a){return c.sibling(a.parentNode.firstChild,a)},children:function(a){return c.sibling(a.firstChild)},contents:function(a){return c.nodeName(a,"iframe")? a.contentDocument||a.contentWindow.document:c.makeArray(a.childNodes)}},function(a,b){c.fn[a]=function(d,f){var e=c.map(this,b,d);eb.test(a)||(f=d);if(f&&typeof f==="string")e=c.filter(f,e);e=this.length>1?c.unique(e):e;if((this.length>1||gb.test(f))&&fb.test(a))e=e.reverse();return this.pushStack(e,a,R.call(arguments).join(","))}});c.extend({filter:function(a,b,d){if(d)a=":not("+a+")";return c.find.matches(a,b)},dir:function(a,b,d){var f=[];for(a=a[b];a&&a.nodeType!==9&&(d===w||a.nodeType!==1||!c(a).is(d));){a.nodeType=== 1&&f.push(a);a=a[b]}return f},nth:function(a,b,d){b=b||1;for(var f=0;a;a=a[d])if(a.nodeType===1&&++f===b)break;return a},sibling:function(a,b){for(var d=[];a;a=a.nextSibling)a.nodeType===1&&a!==b&&d.push(a);return d}});var Ja=/ jQuery\d+="(?:\d+|null)"/g,V=/^\s+/,Ka=/(<([\w:]+)[^>]*?)\/>/g,hb=/^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,La=/<([\w:]+)/,ib=/<tbody/i,jb=/<|&#?\w+;/,ta=/<script|<object|<embed|<option|<style/i,ua=/checked\s*(?:[^=]|=\s*.checked.)/i,Ma=function(a,b,d){return hb.test(d)? a:b+"></"+d+">"},F={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]};F.optgroup=F.option;F.tbody=F.tfoot=F.colgroup=F.caption=F.thead;F.th=F.td;if(!c.support.htmlSerialize)F._default=[1,"div<div>","</div>"];c.fn.extend({text:function(a){if(c.isFunction(a))return this.each(function(b){var d= c(this);d.text(a.call(this,b,d.text()))});if(typeof a!=="object"&&a!==w)return this.empty().append((this[0]&&this[0].ownerDocument||s).createTextNode(a));return c.text(this)},wrapAll:function(a){if(c.isFunction(a))return this.each(function(d){c(this).wrapAll(a.call(this,d))});if(this[0]){var b=c(a,this[0].ownerDocument).eq(0).clone(true);this[0].parentNode&&b.insertBefore(this[0]);b.map(function(){for(var d=this;d.firstChild&&d.firstChild.nodeType===1;)d=d.firstChild;return d}).append(this)}return this}, wrapInner:function(a){if(c.isFunction(a))return this.each(function(b){c(this).wrapInner(a.call(this,b))});return this.each(function(){var b=c(this),d=b.contents();d.length?d.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){c(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){c.nodeName(this,"body")||c(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.appendChild(a)})}, prepend:function(){return this.domManip(arguments,true,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b,this)});else if(arguments.length){var a=c(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,false,function(b){this.parentNode.insertBefore(b, this.nextSibling)});else if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,c(arguments[0]).toArray());return a}},remove:function(a,b){for(var d=0,f;(f=this[d])!=null;d++)if(!a||c.filter(a,[f]).length){if(!b&&f.nodeType===1){c.cleanData(f.getElementsByTagName("*"));c.cleanData([f])}f.parentNode&&f.parentNode.removeChild(f)}return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++)for(b.nodeType===1&&c.cleanData(b.getElementsByTagName("*"));b.firstChild;)b.removeChild(b.firstChild); return this},clone:function(a){var b=this.map(function(){if(!c.support.noCloneEvent&&!c.isXMLDoc(this)){var d=this.outerHTML,f=this.ownerDocument;if(!d){d=f.createElement("div");d.appendChild(this.cloneNode(true));d=d.innerHTML}return c.clean([d.replace(Ja,"").replace(/=([^="'>\s]+\/)>/g,'="$1">').replace(V,"")],f)[0]}else return this.cloneNode(true)});if(a===true){ra(this,b);ra(this.find("*"),b.find("*"))}return b},html:function(a){if(a===w)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Ja, ""):null;else if(typeof a==="string"&&!ta.test(a)&&(c.support.leadingWhitespace||!V.test(a))&&!F[(La.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Ka,Ma);try{for(var b=0,d=this.length;b<d;b++)if(this[b].nodeType===1){c.cleanData(this[b].getElementsByTagName("*"));this[b].innerHTML=a}}catch(f){this.empty().append(a)}}else c.isFunction(a)?this.each(function(e){var j=c(this),i=j.html();j.empty().append(function(){return a.call(this,e,i)})}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&& this[0].parentNode){if(c.isFunction(a))return this.each(function(b){var d=c(this),f=d.html();d.replaceWith(a.call(this,b,f))});if(typeof a!=="string")a=c(a).detach();return this.each(function(){var b=this.nextSibling,d=this.parentNode;c(this).remove();b?c(b).before(a):c(d).append(a)})}else return this.pushStack(c(c.isFunction(a)?a():a),"replaceWith",a)},detach:function(a){return this.remove(a,true)},domManip:function(a,b,d){function f(u){return c.nodeName(u,"table")?u.getElementsByTagName("tbody")[0]|| u.appendChild(u.ownerDocument.createElement("tbody")):u}var e,j,i=a[0],o=[],k;if(!c.support.checkClone&&arguments.length===3&&typeof i==="string"&&ua.test(i))return this.each(function(){c(this).domManip(a,b,d,true)});if(c.isFunction(i))return this.each(function(u){var z=c(this);a[0]=i.call(this,u,b?z.html():w);z.domManip(a,b,d)});if(this[0]){e=i&&i.parentNode;e=c.support.parentNode&&e&&e.nodeType===11&&e.childNodes.length===this.length?{fragment:e}:sa(a,this,o);k=e.fragment;if(j=k.childNodes.length=== 1?(k=k.firstChild):k.firstChild){b=b&&c.nodeName(j,"tr");for(var n=0,r=this.length;n<r;n++)d.call(b?f(this[n],j):this[n],n>0||e.cacheable||this.length>1?k.cloneNode(true):k)}o.length&&c.each(o,Qa)}return this}});c.fragments={};c.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){c.fn[a]=function(d){var f=[];d=c(d);var e=this.length===1&&this[0].parentNode;if(e&&e.nodeType===11&&e.childNodes.length===1&&d.length===1){d[b](this[0]); return this}else{e=0;for(var j=d.length;e<j;e++){var i=(e>0?this.clone(true):this).get();c.fn[b].apply(c(d[e]),i);f=f.concat(i)}return this.pushStack(f,a,d.selector)}}});c.extend({clean:function(a,b,d,f){b=b||s;if(typeof b.createElement==="undefined")b=b.ownerDocument||b[0]&&b[0].ownerDocument||s;for(var e=[],j=0,i;(i=a[j])!=null;j++){if(typeof i==="number")i+="";if(i){if(typeof i==="string"&&!jb.test(i))i=b.createTextNode(i);else if(typeof i==="string"){i=i.replace(Ka,Ma);var o=(La.exec(i)||["", ""])[1].toLowerCase(),k=F[o]||F._default,n=k[0],r=b.createElement("div");for(r.innerHTML=k[1]+i+k[2];n--;)r=r.lastChild;if(!c.support.tbody){n=ib.test(i);o=o==="table"&&!n?r.firstChild&&r.firstChild.childNodes:k[1]==="<table>"&&!n?r.childNodes:[];for(k=o.length-1;k>=0;--k)c.nodeName(o[k],"tbody")&&!o[k].childNodes.length&&o[k].parentNode.removeChild(o[k])}!c.support.leadingWhitespace&&V.test(i)&&r.insertBefore(b.createTextNode(V.exec(i)[0]),r.firstChild);i=r.childNodes}if(i.nodeType)e.push(i);else e= c.merge(e,i)}}if(d)for(j=0;e[j];j++)if(f&&c.nodeName(e[j],"script")&&(!e[j].type||e[j].type.toLowerCase()==="text/javascript"))f.push(e[j].parentNode?e[j].parentNode.removeChild(e[j]):e[j]);else{e[j].nodeType===1&&e.splice.apply(e,[j+1,0].concat(c.makeArray(e[j].getElementsByTagName("script"))));d.appendChild(e[j])}return e},cleanData:function(a){for(var b,d,f=c.cache,e=c.event.special,j=c.support.deleteExpando,i=0,o;(o=a[i])!=null;i++)if(d=o[c.expando]){b=f[d];if(b.events)for(var k in b.events)e[k]? c.event.remove(o,k):Ca(o,k,b.handle);if(j)delete o[c.expando];else o.removeAttribute&&o.removeAttribute(c.expando);delete f[d]}}});var kb=/z-?index|font-?weight|opacity|zoom|line-?height/i,Na=/alpha\([^)]*\)/,Oa=/opacity=([^)]*)/,ha=/float/i,ia=/-([a-z])/ig,lb=/([A-Z])/g,mb=/^-?\d+(?:px)?$/i,nb=/^-?\d/,ob={position:"absolute",visibility:"hidden",display:"block"},pb=["Left","Right"],qb=["Top","Bottom"],rb=s.defaultView&&s.defaultView.getComputedStyle,Pa=c.support.cssFloat?"cssFloat":"styleFloat",ja= function(a,b){return b.toUpperCase()};c.fn.css=function(a,b){return X(this,a,b,true,function(d,f,e){if(e===w)return c.curCSS(d,f);if(typeof e==="number"&&!kb.test(f))e+="px";c.style(d,f,e)})};c.extend({style:function(a,b,d){if(!a||a.nodeType===3||a.nodeType===8)return w;if((b==="width"||b==="height")&&parseFloat(d)<0)d=w;var f=a.style||a,e=d!==w;if(!c.support.opacity&&b==="opacity"){if(e){f.zoom=1;b=parseInt(d,10)+""==="NaN"?"":"alpha(opacity="+d*100+")";a=f.filter||c.curCSS(a,"filter")||"";f.filter= Na.test(a)?a.replace(Na,b):b}return f.filter&&f.filter.indexOf("opacity=")>=0?parseFloat(Oa.exec(f.filter)[1])/100+"":""}if(ha.test(b))b=Pa;b=b.replace(ia,ja);if(e)f[b]=d;return f[b]},css:function(a,b,d,f){if(b==="width"||b==="height"){var e,j=b==="width"?pb:qb;function i(){e=b==="width"?a.offsetWidth:a.offsetHeight;f!=="border"&&c.each(j,function(){f||(e-=parseFloat(c.curCSS(a,"padding"+this,true))||0);if(f==="margin")e+=parseFloat(c.curCSS(a,"margin"+this,true))||0;else e-=parseFloat(c.curCSS(a, "border"+this+"Width",true))||0})}a.offsetWidth!==0?i():c.swap(a,ob,i);return Math.max(0,Math.round(e))}return c.curCSS(a,b,d)},curCSS:function(a,b,d){var f,e=a.style;if(!c.support.opacity&&b==="opacity"&&a.currentStyle){f=Oa.test(a.currentStyle.filter||"")?parseFloat(RegExp.$1)/100+"":"";return f===""?"1":f}if(ha.test(b))b=Pa;if(!d&&e&&e[b])f=e[b];else if(rb){if(ha.test(b))b="float";b=b.replace(lb,"-$1").toLowerCase();e=a.ownerDocument.defaultView;if(!e)return null;if(a=e.getComputedStyle(a,null))f= a.getPropertyValue(b);if(b==="opacity"&&f==="")f="1"}else if(a.currentStyle){d=b.replace(ia,ja);f=a.currentStyle[b]||a.currentStyle[d];if(!mb.test(f)&&nb.test(f)){b=e.left;var j=a.runtimeStyle.left;a.runtimeStyle.left=a.currentStyle.left;e.left=d==="fontSize"?"1em":f||0;f=e.pixelLeft+"px";e.left=b;a.runtimeStyle.left=j}}return f},swap:function(a,b,d){var f={};for(var e in b){f[e]=a.style[e];a.style[e]=b[e]}d.call(a);for(e in b)a.style[e]=f[e]}});if(c.expr&&c.expr.filters){c.expr.filters.hidden=function(a){var b= a.offsetWidth,d=a.offsetHeight,f=a.nodeName.toLowerCase()==="tr";return b===0&&d===0&&!f?true:b>0&&d>0&&!f?false:c.curCSS(a,"display")==="none"};c.expr.filters.visible=function(a){return!c.expr.filters.hidden(a)}}var sb=J(),tb=/<script(.|\s)*?\/script>/gi,ub=/select|textarea/i,vb=/color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,N=/=\?(&|$)/,ka=/\?/,wb=/(\?|&)_=.*?(&|$)/,xb=/^(\w+:)?\/\/([^\/?#]+)/,yb=/%20/g,zb=c.fn.load;c.fn.extend({load:function(a,b,d){if(typeof a!== "string")return zb.call(this,a);else if(!this.length)return this;var f=a.indexOf(" ");if(f>=0){var e=a.slice(f,a.length);a=a.slice(0,f)}f="GET";if(b)if(c.isFunction(b)){d=b;b=null}else if(typeof b==="object"){b=c.param(b,c.ajaxSettings.traditional);f="POST"}var j=this;c.ajax({url:a,type:f,dataType:"html",data:b,complete:function(i,o){if(o==="success"||o==="notmodified")j.html(e?c("<div />").append(i.responseText.replace(tb,"")).find(e):i.responseText);d&&j.each(d,[i.responseText,o,i])}});return this}, serialize:function(){return c.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?c.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||ub.test(this.nodeName)||vb.test(this.type))}).map(function(a,b){a=c(this).val();return a==null?null:c.isArray(a)?c.map(a,function(d){return{name:b.name,value:d}}):{name:b.name,value:a}}).get()}});c.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function(a,b){c.fn[b]=function(d){return this.bind(b,d)}});c.extend({get:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b=null}return c.ajax({type:"GET",url:a,data:b,success:d,dataType:f})},getScript:function(a,b){return c.get(a,null,b,"script")},getJSON:function(a,b,d){return c.get(a,b,d,"json")},post:function(a,b,d,f){if(c.isFunction(b)){f=f||d;d=b;b={}}return c.ajax({type:"POST",url:a,data:b,success:d,dataType:f})},ajaxSetup:function(a){c.extend(c.ajaxSettings,a)},ajaxSettings:{url:location.href, global:true,type:"GET",contentType:"application/x-www-form-urlencoded",processData:true,async:true,xhr:A.XMLHttpRequest&&(A.location.protocol!=="file:"||!A.ActiveXObject)?function(){return new A.XMLHttpRequest}:function(){try{return new A.ActiveXObject("Microsoft.XMLHTTP")}catch(a){}},accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},etag:{},ajax:function(a){function b(){e.success&& e.success.call(k,o,i,x);e.global&&f("ajaxSuccess",[x,e])}function d(){e.complete&&e.complete.call(k,x,i);e.global&&f("ajaxComplete",[x,e]);e.global&&!--c.active&&c.event.trigger("ajaxStop")}function f(q,p){(e.context?c(e.context):c.event).trigger(q,p)}var e=c.extend(true,{},c.ajaxSettings,a),j,i,o,k=a&&a.context||e,n=e.type.toUpperCase();if(e.data&&e.processData&&typeof e.data!=="string")e.data=c.param(e.data,e.traditional);if(e.dataType==="jsonp"){if(n==="GET")N.test(e.url)||(e.url+=(ka.test(e.url)? "&":"?")+(e.jsonp||"callback")+"=?");else if(!e.data||!N.test(e.data))e.data=(e.data?e.data+"&":"")+(e.jsonp||"callback")+"=?";e.dataType="json"}if(e.dataType==="json"&&(e.data&&N.test(e.data)||N.test(e.url))){j=e.jsonpCallback||"jsonp"+sb++;if(e.data)e.data=(e.data+"").replace(N,"="+j+"$1");e.url=e.url.replace(N,"="+j+"$1");e.dataType="script";A[j]=A[j]||function(q){o=q;b();d();A[j]=w;try{delete A[j]}catch(p){}z&&z.removeChild(C)}}if(e.dataType==="script"&&e.cache===null)e.cache=false;if(e.cache=== false&&n==="GET"){var r=J(),u=e.url.replace(wb,"$1_="+r+"$2");e.url=u+(u===e.url?(ka.test(e.url)?"&":"?")+"_="+r:"")}if(e.data&&n==="GET")e.url+=(ka.test(e.url)?"&":"?")+e.data;e.global&&!c.active++&&c.event.trigger("ajaxStart");r=(r=xb.exec(e.url))&&(r[1]&&r[1]!==location.protocol||r[2]!==location.host);if(e.dataType==="script"&&n==="GET"&&r){var z=s.getElementsByTagName("head")[0]||s.documentElement,C=s.createElement("script");C.src=e.url;if(e.scriptCharset)C.charset=e.scriptCharset;if(!j){var B= false;C.onload=C.onreadystatechange=function(){if(!B&&(!this.readyState||this.readyState==="loaded"||this.readyState==="complete")){B=true;b();d();C.onload=C.onreadystatechange=null;z&&C.parentNode&&z.removeChild(C)}}}z.insertBefore(C,z.firstChild);return w}var E=false,x=e.xhr();if(x){e.username?x.open(n,e.url,e.async,e.username,e.password):x.open(n,e.url,e.async);try{if(e.data||a&&a.contentType)x.setRequestHeader("Content-Type",e.contentType);if(e.ifModified){c.lastModified[e.url]&&x.setRequestHeader("If-Modified-Since", c.lastModified[e.url]);c.etag[e.url]&&x.setRequestHeader("If-None-Match",c.etag[e.url])}r||x.setRequestHeader("X-Requested-With","XMLHttpRequest");x.setRequestHeader("Accept",e.dataType&&e.accepts[e.dataType]?e.accepts[e.dataType]+", */*":e.accepts._default)}catch(ga){}if(e.beforeSend&&e.beforeSend.call(k,x,e)===false){e.global&&!--c.active&&c.event.trigger("ajaxStop");x.abort();return false}e.global&&f("ajaxSend",[x,e]);var g=x.onreadystatechange=function(q){if(!x||x.readyState===0||q==="abort"){E|| d();E=true;if(x)x.onreadystatechange=c.noop}else if(!E&&x&&(x.readyState===4||q==="timeout")){E=true;x.onreadystatechange=c.noop;i=q==="timeout"?"timeout":!c.httpSuccess(x)?"error":e.ifModified&&c.httpNotModified(x,e.url)?"notmodified":"success";var p;if(i==="success")try{o=c.httpData(x,e.dataType,e)}catch(v){i="parsererror";p=v}if(i==="success"||i==="notmodified")j||b();else c.handleError(e,x,i,p);d();q==="timeout"&&x.abort();if(e.async)x=null}};try{var h=x.abort;x.abort=function(){x&&h.call(x); g("abort")}}catch(l){}e.async&&e.timeout>0&&setTimeout(function(){x&&!E&&g("timeout")},e.timeout);try{x.send(n==="POST"||n==="PUT"||n==="DELETE"?e.data:null)}catch(m){c.handleError(e,x,null,m);d()}e.async||g();return x}},handleError:function(a,b,d,f){if(a.error)a.error.call(a.context||a,b,d,f);if(a.global)(a.context?c(a.context):c.event).trigger("ajaxError",[b,a,f])},active:0,httpSuccess:function(a){try{return!a.status&&location.protocol==="file:"||a.status>=200&&a.status<300||a.status===304||a.status=== 1223||a.status===0}catch(b){}return false},httpNotModified:function(a,b){var d=a.getResponseHeader("Last-Modified"),f=a.getResponseHeader("Etag");if(d)c.lastModified[b]=d;if(f)c.etag[b]=f;return a.status===304||a.status===0},httpData:function(a,b,d){var f=a.getResponseHeader("content-type")||"",e=b==="xml"||!b&&f.indexOf("xml")>=0;a=e?a.responseXML:a.responseText;e&&a.documentElement.nodeName==="parsererror"&&c.error("parsererror");if(d&&d.dataFilter)a=d.dataFilter(a,b);if(typeof a==="string")if(b=== "json"||!b&&f.indexOf("json")>=0)a=c.parseJSON(a);else if(b==="script"||!b&&f.indexOf("javascript")>=0)c.globalEval(a);return a},param:function(a,b){function d(i,o){if(c.isArray(o))c.each(o,function(k,n){b||/\[\]$/.test(i)?f(i,n):d(i+"["+(typeof n==="object"||c.isArray(n)?k:"")+"]",n)});else!b&&o!=null&&typeof o==="object"?c.each(o,function(k,n){d(i+"["+k+"]",n)}):f(i,o)}function f(i,o){o=c.isFunction(o)?o():o;e[e.length]=encodeURIComponent(i)+"="+encodeURIComponent(o)}var e=[];if(b===w)b=c.ajaxSettings.traditional; if(c.isArray(a)||a.jquery)c.each(a,function(){f(this.name,this.value)});else for(var j in a)d(j,a[j]);return e.join("&").replace(yb,"+")}});var la={},Ab=/toggle|show|hide/,Bb=/^([+-]=)?([\d+-.]+)(.*)$/,W,va=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]];c.fn.extend({show:function(a,b){if(a||a===0)return this.animate(K("show",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay"); this[a].style.display=d||"";if(c.css(this[a],"display")==="none"){d=this[a].nodeName;var f;if(la[d])f=la[d];else{var e=c("<"+d+" />").appendTo("body");f=e.css("display");if(f==="none")f="block";e.remove();la[d]=f}c.data(this[a],"olddisplay",f)}}a=0;for(b=this.length;a<b;a++)this[a].style.display=c.data(this[a],"olddisplay")||"";return this}},hide:function(a,b){if(a||a===0)return this.animate(K("hide",3),a,b);else{a=0;for(b=this.length;a<b;a++){var d=c.data(this[a],"olddisplay");!d&&d!=="none"&&c.data(this[a], "olddisplay",c.css(this[a],"display"))}a=0;for(b=this.length;a<b;a++)this[a].style.display="none";return this}},_toggle:c.fn.toggle,toggle:function(a,b){var d=typeof a==="boolean";if(c.isFunction(a)&&c.isFunction(b))this._toggle.apply(this,arguments);else a==null||d?this.each(function(){var f=d?a:c(this).is(":hidden");c(this)[f?"show":"hide"]()}):this.animate(K("toggle",3),a,b);return this},fadeTo:function(a,b,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,d)}, animate:function(a,b,d,f){var e=c.speed(b,d,f);if(c.isEmptyObject(a))return this.each(e.complete);return this[e.queue===false?"each":"queue"](function(){var j=c.extend({},e),i,o=this.nodeType===1&&c(this).is(":hidden"),k=this;for(i in a){var n=i.replace(ia,ja);if(i!==n){a[n]=a[i];delete a[i];i=n}if(a[i]==="hide"&&o||a[i]==="show"&&!o)return j.complete.call(this);if((i==="height"||i==="width")&&this.style){j.display=c.css(this,"display");j.overflow=this.style.overflow}if(c.isArray(a[i])){(j.specialEasing= j.specialEasing||{})[i]=a[i][1];a[i]=a[i][0]}}if(j.overflow!=null)this.style.overflow="hidden";j.curAnim=c.extend({},a);c.each(a,function(r,u){var z=new c.fx(k,j,r);if(Ab.test(u))z[u==="toggle"?o?"show":"hide":u](a);else{var C=Bb.exec(u),B=z.cur(true)||0;if(C){u=parseFloat(C[2]);var E=C[3]||"px";if(E!=="px"){k.style[r]=(u||1)+E;B=(u||1)/z.cur(true)*B;k.style[r]=B+E}if(C[1])u=(C[1]==="-="?-1:1)*u+B;z.custom(B,u,E)}else z.custom(B,u,"")}});return true})},stop:function(a,b){var d=c.timers;a&&this.queue([]); this.each(function(){for(var f=d.length-1;f>=0;f--)if(d[f].elem===this){b&&d[f](true);d.splice(f,1)}});b||this.dequeue();return this}});c.each({slideDown:K("show",1),slideUp:K("hide",1),slideToggle:K("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"}},function(a,b){c.fn[a]=function(d,f){return this.animate(b,d,f)}});c.extend({speed:function(a,b,d){var f=a&&typeof a==="object"?a:{complete:d||!d&&b||c.isFunction(a)&&a,duration:a,easing:d&&b||b&&!c.isFunction(b)&&b};f.duration=c.fx.off?0:typeof f.duration=== "number"?f.duration:c.fx.speeds[f.duration]||c.fx.speeds._default;f.old=f.complete;f.complete=function(){f.queue!==false&&c(this).dequeue();c.isFunction(f.old)&&f.old.call(this)};return f},easing:{linear:function(a,b,d,f){return d+f*a},swing:function(a,b,d,f){return(-Math.cos(a*Math.PI)/2+0.5)*f+d}},timers:[],fx:function(a,b,d){this.options=b;this.elem=a;this.prop=d;if(!b.orig)b.orig={}}});c.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this);(c.fx.step[this.prop]|| c.fx.step._default)(this);if((this.prop==="height"||this.prop==="width")&&this.elem.style)this.elem.style.display="block"},cur:function(a){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];return(a=parseFloat(c.css(this.elem,this.prop,a)))&&a>-10000?a:parseFloat(c.curCSS(this.elem,this.prop))||0},custom:function(a,b,d){function f(j){return e.step(j)}this.startTime=J();this.start=a;this.end=b;this.unit=d||this.unit||"px";this.now=this.start; this.pos=this.state=0;var e=this;f.elem=this.elem;if(f()&&c.timers.push(f)&&!W)W=setInterval(c.fx.tick,13)},show:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.show=true;this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur());c(this.elem).show()},hide:function(){this.options.orig[this.prop]=c.style(this.elem,this.prop);this.options.hide=true;this.custom(this.cur(),0)},step:function(a){var b=J(),d=true;if(a||b>=this.options.duration+this.startTime){this.now= this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;for(var f in this.options.curAnim)if(this.options.curAnim[f]!==true)d=false;if(d){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;a=c.data(this.elem,"olddisplay");this.elem.style.display=a?a:this.options.display;if(c.css(this.elem,"display")==="none")this.elem.style.display="block"}this.options.hide&&c(this.elem).hide();if(this.options.hide||this.options.show)for(var e in this.options.curAnim)c.style(this.elem, e,this.options.orig[e]);this.options.complete.call(this.elem)}return false}else{e=b-this.startTime;this.state=e/this.options.duration;a=this.options.easing||(c.easing.swing?"swing":"linear");this.pos=c.easing[this.options.specialEasing&&this.options.specialEasing[this.prop]||a](this.state,e,0,1,this.options.duration);this.now=this.start+(this.end-this.start)*this.pos;this.update()}return true}};c.extend(c.fx,{tick:function(){for(var a=c.timers,b=0;b<a.length;b++)a[b]()||a.splice(b--,1);a.length|| c.fx.stop()},stop:function(){clearInterval(W);W=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){c.style(a.elem,"opacity",a.now)},_default:function(a){if(a.elem.style&&a.elem.style[a.prop]!=null)a.elem.style[a.prop]=(a.prop==="width"||a.prop==="height"?Math.max(0,a.now):a.now)+a.unit;else a.elem[a.prop]=a.now}}});if(c.expr&&c.expr.filters)c.expr.filters.animated=function(a){return c.grep(c.timers,function(b){return a===b.elem}).length};c.fn.offset="getBoundingClientRect"in s.documentElement? function(a){var b=this[0];if(a)return this.each(function(e){c.offset.setOffset(this,a,e)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);var d=b.getBoundingClientRect(),f=b.ownerDocument;b=f.body;f=f.documentElement;return{top:d.top+(self.pageYOffset||c.support.boxModel&&f.scrollTop||b.scrollTop)-(f.clientTop||b.clientTop||0),left:d.left+(self.pageXOffset||c.support.boxModel&&f.scrollLeft||b.scrollLeft)-(f.clientLeft||b.clientLeft||0)}}:function(a){var b= this[0];if(a)return this.each(function(r){c.offset.setOffset(this,a,r)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return c.offset.bodyOffset(b);c.offset.initialize();var d=b.offsetParent,f=b,e=b.ownerDocument,j,i=e.documentElement,o=e.body;f=(e=e.defaultView)?e.getComputedStyle(b,null):b.currentStyle;for(var k=b.offsetTop,n=b.offsetLeft;(b=b.parentNode)&&b!==o&&b!==i;){if(c.offset.supportsFixedPosition&&f.position==="fixed")break;j=e?e.getComputedStyle(b,null):b.currentStyle; k-=b.scrollTop;n-=b.scrollLeft;if(b===d){k+=b.offsetTop;n+=b.offsetLeft;if(c.offset.doesNotAddBorder&&!(c.offset.doesAddBorderForTableAndCells&&/^t(able|d|h)$/i.test(b.nodeName))){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=d;d=b.offsetParent}if(c.offset.subtractsBorderForOverflowNotVisible&&j.overflow!=="visible"){k+=parseFloat(j.borderTopWidth)||0;n+=parseFloat(j.borderLeftWidth)||0}f=j}if(f.position==="relative"||f.position==="static"){k+=o.offsetTop;n+=o.offsetLeft}if(c.offset.supportsFixedPosition&& f.position==="fixed"){k+=Math.max(i.scrollTop,o.scrollTop);n+=Math.max(i.scrollLeft,o.scrollLeft)}return{top:k,left:n}};c.offset={initialize:function(){var a=s.body,b=s.createElement("div"),d,f,e,j=parseFloat(c.curCSS(a,"marginTop",true))||0;c.extend(b.style,{position:"absolute",top:0,left:0,margin:0,border:0,width:"1px",height:"1px",visibility:"hidden"});b.innerHTML="<div style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;'><div></div></div><table style='position:absolute;top:0;left:0;margin:0;border:5px solid #000;padding:0;width:1px;height:1px;' cellpadding='0' cellspacing='0'><tr><td></td></tr></table>"; a.insertBefore(b,a.firstChild);d=b.firstChild;f=d.firstChild;e=d.nextSibling.firstChild.firstChild;this.doesNotAddBorder=f.offsetTop!==5;this.doesAddBorderForTableAndCells=e.offsetTop===5;f.style.position="fixed";f.style.top="20px";this.supportsFixedPosition=f.offsetTop===20||f.offsetTop===15;f.style.position=f.style.top="";d.style.overflow="hidden";d.style.position="relative";this.subtractsBorderForOverflowNotVisible=f.offsetTop===-5;this.doesNotIncludeMarginInBodyOffset=a.offsetTop!==j;a.removeChild(b); c.offset.initialize=c.noop},bodyOffset:function(a){var b=a.offsetTop,d=a.offsetLeft;c.offset.initialize();if(c.offset.doesNotIncludeMarginInBodyOffset){b+=parseFloat(c.curCSS(a,"marginTop",true))||0;d+=parseFloat(c.curCSS(a,"marginLeft",true))||0}return{top:b,left:d}},setOffset:function(a,b,d){if(/static/.test(c.curCSS(a,"position")))a.style.position="relative";var f=c(a),e=f.offset(),j=parseInt(c.curCSS(a,"top",true),10)||0,i=parseInt(c.curCSS(a,"left",true),10)||0;if(c.isFunction(b))b=b.call(a, d,e);d={top:b.top-e.top+j,left:b.left-e.left+i};"using"in b?b.using.call(a,d):f.css(d)}};c.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),d=this.offset(),f=/^body|html$/i.test(b[0].nodeName)?{top:0,left:0}:b.offset();d.top-=parseFloat(c.curCSS(a,"marginTop",true))||0;d.left-=parseFloat(c.curCSS(a,"marginLeft",true))||0;f.top+=parseFloat(c.curCSS(b[0],"borderTopWidth",true))||0;f.left+=parseFloat(c.curCSS(b[0],"borderLeftWidth",true))||0;return{top:d.top- f.top,left:d.left-f.left}},offsetParent:function(){return this.map(function(){for(var a=this.offsetParent||s.body;a&&!/^body|html$/i.test(a.nodeName)&&c.css(a,"position")==="static";)a=a.offsetParent;return a})}});c.each(["Left","Top"],function(a,b){var d="scroll"+b;c.fn[d]=function(f){var e=this[0],j;if(!e)return null;if(f!==w)return this.each(function(){if(j=wa(this))j.scrollTo(!a?f:c(j).scrollLeft(),a?f:c(j).scrollTop());else this[d]=f});else return(j=wa(e))?"pageXOffset"in j?j[a?"pageYOffset": "pageXOffset"]:c.support.boxModel&&j.document.documentElement[d]||j.document.body[d]:e[d]}});c.each(["Height","Width"],function(a,b){var d=b.toLowerCase();c.fn["inner"+b]=function(){return this[0]?c.css(this[0],d,false,"padding"):null};c.fn["outer"+b]=function(f){return this[0]?c.css(this[0],d,false,f?"margin":"border"):null};c.fn[d]=function(f){var e=this[0];if(!e)return f==null?null:this;if(c.isFunction(f))return this.each(function(j){var i=c(this);i[d](f.call(this,j,i[d]()))});return"scrollTo"in e&&e.document?e.document.compatMode==="CSS1Compat"&&e.document.documentElement["client"+b]||e.document.body["client"+b]:e.nodeType===9?Math.max(e.documentElement["client"+b],e.body["scroll"+b],e.documentElement["scroll"+b],e.body["offset"+b],e.documentElement["offset"+b]):f===w?c.css(e,d):this.css(d,typeof f==="string"?f:f+"px")}});A.jQuery=A.$=c})(window);
Package.describe({ summary: "Run a function when the user scrolls past an element", version: "1.0.9", deprecated: true, documentation: 'README.md' }); Package.onUse(function (api) { api.use('jquery'); api.use('coffeescript'); api.addFiles('waypoints.coffee', 'client'); });
module.exports = { parser: '@typescript-eslint/parser', env: { node: true }, plugins: [ '@typescript-eslint', ], extends: [ 'airbnb-typescript/base', 'plugin:@typescript-eslint/eslint-recommended', 'plugin:@typescript-eslint/recommended', 'plugin:@typescript-eslint/recommended-requiring-type-checking', 'prettier/@typescript-eslint', 'plugin:prettier/recommended', ], parserOptions: { ecmaVersion: 2018, sourceType: 'module', project: './tsconfig.json' }, rules: { 'import/order': ['error', { 'newlines-between': 'always', 'groups': [ 'external', 'internal', ], 'alphabetize': { 'order': 'asc', 'caseInsensitive': false } }], 'no-void': ["error", { "allowAsStatement": true }], 'no-console': 'off', 'no-restricted-syntax': ['error', 'FunctionDeclaration[generator=true]'], 'max-classes-per-file': 'off', '@typescript-eslint/no-explicit-any': 'off', '@typescript-eslint/no-misused-promises': ['error', { 'checksVoidReturn': false }], '@typescript-eslint/explicit-function-return-type': 'off', '@typescript-eslint/no-unused-vars': 'off', }, };
/** * Created by liuchang on 16/1/21. * * this test karma configuration and should assertion lib * it should work with typescript and es6 */ 'use strict'; var co = require('co'); require("should"); describe('karma test', function () { describe('should test', function () { it('should return -1 when the value is not present', function () { [1, 2, 3].indexOf(5).should.equal(-1); [1, 2, 3].indexOf(0).should.equal(-1); }); it('should support universal font', function () { '中文测试'.should.be.a.String(); '日本語テスト'.should.be.a.String(); }); it('should run in async task', (done) => { let val = 1; setTimeout(function () { val = 10; val.should.equal(10); done(); }, 500); }); }); describe('co test', function () { it('should be a function', function () { co.should.be.a.Function(); }); it('co should work', function () { let ret = co(function* () { yield Promise.resolve(1); }); ret.should.be.Promise(); }); }); });
'use strict'; angular.module('copayApp.controllers').controller('preferencesThemeController', function($scope, configService, profileService, go) { var config = configService.getSync(); this.themeOpts = [ { name: 'DigiByte Gaming Default', url: 'url("./img/digibytedefault.jpg")', }, { name: 'DigiByte Banner Other', url: 'url("./img/digibyteother.jpg")', }, { name: 'League Of Legends - Blitzcrank', url: 'url("./img/lolblitzcrank.jpg")', }, { name: 'League Of Legends - Ezreal', url: 'url("./img/lolezreal.jpg")', }, { name: 'League Of Legends - Jayce', url: 'url("./img/loljayce.jpg")', }, { name: 'League Of Legends - Lissandra', url: 'url("./img/lollissandra.jpg")', }, { name: 'League Of Legends - Volibear', url: 'url("./img/lolvolibear.jpg")', }, { name: 'Hearthstone: Heroes of Warcraft', url: 'url("./img/hearthstone.jpg")', }, { name: 'Dota 2 ', url: 'url("./img/dota2.jpg")', }, { name: 'Counter-Strike: Global Offensive', url: 'url("./img/csgo.jpg")', } ]; var fc = profileService.focusedClient; var walletId = fc.credentials.walletId; var config = configService.getSync(); config.themeFor = config.themeFor || {}; this.theme = config.themeFor[walletId] || 'url("./img/digibyteother.jpg")'; this.save = function(theme) { var self = this; var opts = { themeFor: { themeName: theme.name, themeUrl: theme.url, } }; this.themeName = theme.name; opts.themeFor[walletId] = theme; configService.set(opts, function(err) { if (err) { $scope.$emit('Local/DeviceError', err); return; } self.theme = theme; $scope.$emit('Local/ThemeUpdated'); }); }; });
/** * @class Denkmal_Component_HeaderBar * @extends Denkmal_Component_Abstract */ var Denkmal_Component_HeaderBar = Denkmal_Component_Abstract.extend({ /** @type String */ _class: 'Denkmal_Component_HeaderBar', events: { 'click .menu.dates a': function() { if (!this.getWeekdayMenuVisible()) { this.setWeekdayMenuVisible(true); return false; } } }, appEvents: { 'navigate:start': function() { this.setWeekdayMenuVisible(false); } }, /** * @param {Boolean} state */ setWeekdayMenuVisible: function(state) { var callback = function(state) { $(this).attr('data-weekday-menu', state ? '' : null); }; if (state) { this.$el.toggleModal('open', callback); } else { this.$el.toggleModal('close', callback); } }, /** * @returns {boolean} */ getWeekdayMenuVisible: function() { return this.el.hasAttribute('data-weekday-menu'); }, /** * @param {Boolean} state */ setNavigationIndicationVisible: function(state) { this.$el.attr('data-navigation-indication', state ? '' : null); } });
(function () { 'use strict'; var module = angular.module('fim.base'); module.config(function($routeProvider) { $routeProvider.when('/search/:engine/:category/:query?', { templateUrl: 'partials/search.html', controller: 'SearchController' }) }); module.controller('SearchController', function ($scope, nxt, $routeParams, $rootScope, SearchProvider, $location) { $rootScope.paramEngine = $routeParams.engine; $scope.paramEngine = $routeParams.engine; $scope.paramCategory = $routeParams.category; $scope.paramQuery = $routeParams.query || ''; if ($scope.paramEngine == 'fim') { var api = nxt.fim(); } else if ($scope.paramEngine == 'nxt') { var api = nxt.nxt(); } else { $location.path('home/fim/activity/latest'); return; } if (['accounts', 'assets', 'currencies', 'market', 'aliases'].indexOf($scope.paramCategory) == -1) { $location.path('/home/fim/activity/latest'); return; } var reload_promise = null; function reload() { $scope.provider = new SearchProvider(api, $scope, 10, $scope.paramCategory, $scope.paramQuery); reload_promise = $scope.provider.reload(); reload_promise.then(function () { reload_promise = null; }); } reload(); $scope.doSearch = function () { $location.path('/search/'+$scope.paramEngine+'/'+$scope.paramCategory+'/'+$scope.paramQuery); } $scope.$watch('paramQuery', function () { if (reload_promise) { reload_promise.then(function () { reload(); }) } else { reload(); } window.locaction }); }); })();
/** @method Seemple.unbindNode @module seemple/unbindnode @importance 3 @since 1.1 @summary Разрывает связь между свойством и HTML элементом @desc Этот статичный метод работает так же, как и {@link Seemple#unbindNode} и все его вариации, но принимает в качестве первого аргумента любой JavaScript объект. @returns {object} Первый аргумент @see {@link Seemple#unbindNode} @example const object = {}; Seemple.unbindNode(object, 'x', '.my-node'); */
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _reactIconBase = require('react-icon-base'); var _reactIconBase2 = _interopRequireDefault(_reactIconBase); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var MdUsb = function MdUsb(props) { return _react2.default.createElement( _reactIconBase2.default, _extends({ viewBox: '0 0 40 40' }, props), _react2.default.createElement( 'g', null, _react2.default.createElement('path', { d: 'm25 11.6h6.6v6.8h-1.6v3.2c0 1.9-1.5 3.4-3.4 3.4h-5v5.1c1.2 0.6 2.1 1.9 2.1 3.3 0 2-1.7 3.6-3.7 3.6s-3.7-1.6-3.7-3.6c0-1.4 0.9-2.7 2.1-3.3v-5.1h-5c-1.9 0-3.4-1.5-3.4-3.4v-3.4c-1.2-0.6-2-1.8-2-3.2 0-2 1.6-3.7 3.6-3.7s3.7 1.7 3.7 3.7c0 1.4-0.8 2.6-1.9 3.2v3.4h5v-13.2h-3.4l5-6.8 5 6.8h-3.4v13.2h5v-3.2h-1.6v-6.8z' }) ) ); }; exports.default = MdUsb; module.exports = exports['default'];
export default /* glsl */` uniform float skyboxIntensity; vec3 processEnvironment(vec3 color) { return color * skyboxIntensity; } `;
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M19 5H5c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-1 12H6c-.55 0-1-.45-1-1V8c0-.55.45-1 1-1h12c.55 0 1 .45 1 1v8c0 .55-.45 1-1 1z" /></g></React.Fragment> , 'Crop54Rounded');
if(!dojo._hasResource["dijit._Templated"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code. dojo._hasResource["dijit._Templated"] = true; dojo.provide("dijit._Templated"); dojo.require("dijit._Widget"); dojo.require("dojo.string"); dojo.require("dojo.parser"); dojo.declare("dijit._Templated", null, { // summary: // Mixin for widgets that are instantiated from a template // // templateNode: DomNode // a node that represents the widget template. Pre-empts both templateString and templatePath. templateNode: null, // templateString: String // a string that represents the widget template. Pre-empts the // templatePath. In builds that have their strings "interned", the // templatePath is converted to an inline templateString, thereby // preventing a synchronous network call. templateString: null, // templatePath: String // Path to template (HTML file) for this widget relative to dojo.baseUrl templatePath: null, // widgetsInTemplate: Boolean // should we parse the template to find widgets that might be // declared in markup inside it? false by default. widgetsInTemplate: false, // containerNode: DomNode // holds child elements. "containerNode" is generally set via a // dojoAttachPoint assignment and it designates where children of // the src dom node will be placed containerNode: null, // skipNodeCache: Boolean // if using a cached widget template node poses issues for a // particular widget class, it can set this property to ensure // that its template is always re-built from a string _skipNodeCache: false, _stringRepl: function(tmpl){ var className = this.declaredClass, _this = this; // Cache contains a string because we need to do property replacement // do the property replacement return dojo.string.substitute(tmpl, this, function(value, key){ if(key.charAt(0) == '!'){ value = _this[key.substr(1)]; } if(typeof value == "undefined"){ throw new Error(className+" template:"+key); } // a debugging aide if(!value){ return ""; } // Substitution keys beginning with ! will skip the transform step, // in case a user wishes to insert unescaped markup, e.g. ${!foo} return key.charAt(0) == "!" ? value : // Safer substitution, see heading "Attribute values" in // http://www.w3.org/TR/REC-html40/appendix/notes.html#h-B.3.2 value.toString().replace(/"/g,"&quot;"); //TODO: add &amp? use encodeXML method? }, this); }, // method over-ride buildRendering: function(){ // summary: // Construct the UI for this widget from a template, setting this.domNode. // Lookup cached version of template, and download to cache if it // isn't there already. Returns either a DomNode or a string, depending on // whether or not the template contains ${foo} replacement parameters. var cached = dijit._Templated.getCachedTemplate(this.templatePath, this.templateString, this._skipNodeCache); var node; if(dojo.isString(cached)){ node = dijit._Templated._createNodesFromText(this._stringRepl(cached))[0]; }else{ // if it's a node, all we have to do is clone it node = cached.cloneNode(true); } // recurse through the node, looking for, and attaching to, our // attachment points which should be defined on the template node. this._attachTemplateNodes(node); var source = this.srcNodeRef; if(source && source.parentNode){ source.parentNode.replaceChild(node, source); } this.domNode = node; if(this.widgetsInTemplate){ var cw = this._supportingWidgets = dojo.parser.parse(node); this._attachTemplateNodes(cw, function(n,p){ return n[p]; }); } this._fillContent(source); }, _fillContent: function(/*DomNode*/ source){ // summary: // relocate source contents to templated container node // this.containerNode must be able to receive children, or exceptions will be thrown var dest = this.containerNode; if(source && dest){ while(source.hasChildNodes()){ dest.appendChild(source.firstChild); } } }, _attachTemplateNodes: function(rootNode, getAttrFunc){ // summary: Iterate through the template and attach functions and nodes accordingly. // description: // Map widget properties and functions to the handlers specified in // the dom node and it's descendants. This function iterates over all // nodes and looks for these properties: // * dojoAttachPoint // * dojoAttachEvent // * waiRole // * waiState // rootNode: DomNode|Array[Widgets] // the node to search for properties. All children will be searched. // getAttrFunc: function? // a function which will be used to obtain property for a given // DomNode/Widget getAttrFunc = getAttrFunc || function(n,p){ return n.getAttribute(p); }; var nodes = dojo.isArray(rootNode) ? rootNode : (rootNode.all || rootNode.getElementsByTagName("*")); var x=dojo.isArray(rootNode)?0:-1; for(; x<nodes.length; x++){ var baseNode = (x == -1) ? rootNode : nodes[x]; if(this.widgetsInTemplate && getAttrFunc(baseNode,'dojoType')){ continue; } // Process dojoAttachPoint var attachPoint = getAttrFunc(baseNode, "dojoAttachPoint"); if(attachPoint){ var point, points = attachPoint.split(/\s*,\s*/); while((point = points.shift())){ if(dojo.isArray(this[point])){ this[point].push(baseNode); }else{ this[point]=baseNode; } } } // Process dojoAttachEvent var attachEvent = getAttrFunc(baseNode, "dojoAttachEvent"); if(attachEvent){ // NOTE: we want to support attributes that have the form // "domEvent: nativeEvent; ..." var event, events = attachEvent.split(/\s*,\s*/); var trim = dojo.trim; while((event = events.shift())){ if(event){ var thisFunc = null; if(event.indexOf(":") != -1){ // oh, if only JS had tuple assignment var funcNameArr = event.split(":"); event = trim(funcNameArr[0]); thisFunc = trim(funcNameArr[1]); }else{ event = trim(event); } if(!thisFunc){ thisFunc = event; } this.connect(baseNode, event, thisFunc); } } } // waiRole, waiState var role = getAttrFunc(baseNode, "waiRole"); if(role){ dijit.setWaiRole(baseNode, role); } var values = getAttrFunc(baseNode, "waiState"); if(values){ dojo.forEach(values.split(/\s*,\s*/), function(stateValue){ if(stateValue.indexOf('-') != -1){ var pair = stateValue.split('-'); dijit.setWaiState(baseNode, pair[0], pair[1]); } }); } } } } ); // key is either templatePath or templateString; object is either string or DOM tree dijit._Templated._templateCache = {}; dijit._Templated.getCachedTemplate = function(templatePath, templateString, alwaysUseString){ // summary: // Static method to get a template based on the templatePath or // templateString key // templatePath: String // The URL to get the template from. dojo.uri.Uri is often passed as well. // templateString: String? // a string to use in lieu of fetching the template from a URL. Takes precedence // over templatePath // Returns: Mixed // Either string (if there are ${} variables that need to be replaced) or just // a DOM tree (if the node can be cloned directly) // is it already cached? var tmplts = dijit._Templated._templateCache; var key = templateString || templatePath; var cached = tmplts[key]; if(cached){ return cached; } // If necessary, load template string from template path if(!templateString){ templateString = dijit._Templated._sanitizeTemplateString(dojo._getText(templatePath)); } templateString = dojo.string.trim(templateString); if(alwaysUseString || templateString.match(/\$\{([^\}]+)\}/g)){ // there are variables in the template so all we can do is cache the string return (tmplts[key] = templateString); //String }else{ // there are no variables in the template so we can cache the DOM tree return (tmplts[key] = dijit._Templated._createNodesFromText(templateString)[0]); //Node } }; dijit._Templated._sanitizeTemplateString = function(/*String*/tString){ // summary: // Strips <?xml ...?> declarations so that external SVG and XML // documents can be added to a document without worry. Also, if the string // is an HTML document, only the part inside the body tag is returned. if(tString){ tString = tString.replace(/^\s*<\?xml(\s)+version=[\'\"](\d)*.(\d)*[\'\"](\s)*\?>/im, ""); var matches = tString.match(/<body[^>]*>\s*([\s\S]+)\s*<\/body>/im); if(matches){ tString = matches[1]; } }else{ tString = ""; } return tString; //String }; if(dojo.isIE){ dojo.addOnUnload(function(){ var cache = dijit._Templated._templateCache; for(var key in cache){ var value = cache[key]; if(!isNaN(value.nodeType)){ // isNode equivalent dojo._destroyElement(value); } delete cache[key]; } }); } (function(){ var tagMap = { cell: {re: /^<t[dh][\s\r\n>]/i, pre: "<table><tbody><tr>", post: "</tr></tbody></table>"}, row: {re: /^<tr[\s\r\n>]/i, pre: "<table><tbody>", post: "</tbody></table>"}, section: {re: /^<(thead|tbody|tfoot)[\s\r\n>]/i, pre: "<table>", post: "</table>"} }; // dummy container node used temporarily to hold nodes being created var tn; dijit._Templated._createNodesFromText = function(/*String*/text){ // summary: // Attempts to create a set of nodes based on the structure of the passed text. if(!tn){ tn = dojo.doc.createElement("div"); tn.style.display="none"; dojo.body().appendChild(tn); } var tableType = "none"; var rtext = text.replace(/^\s+/, ""); for(var type in tagMap){ var map = tagMap[type]; if(map.re.test(rtext)){ tableType = type; text = map.pre + text + map.post; break; } } tn.innerHTML = text; if(tn.normalize){ tn.normalize(); } var tag = { cell: "tr", row: "tbody", section: "table" }[tableType]; var _parent = (typeof tag != "undefined") ? tn.getElementsByTagName(tag)[0] : tn; var nodes = []; while(_parent.firstChild){ nodes.push(_parent.removeChild(_parent.firstChild)); } tn.innerHTML=""; return nodes; // Array } })(); // These arguments can be specified for widgets which are used in templates. // Since any widget can be specified as sub widgets in template, mix it // into the base widget class. (This is a hack, but it's effective.) dojo.extend(dijit._Widget,{ dojoAttachEvent: "", dojoAttachPoint: "", waiRole: "", waiState:"" }) }
/////////////////////////////////////////////////////////////////////////// // Copyright © Esri. All Rights Reserved. // // Licensed under the Apache License Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /////////////////////////////////////////////////////////////////////////// define([ 'dojo/on', 'dojo/query', 'dojo/_base/lang', 'dojo/_base/html', 'dojo/_base/declare', 'dojo/Evented', 'dojo/Deferred', './BaseDijitSetting', 'dijit/_WidgetsInTemplateMixin', 'dojo/text!./ChartDijitSetting.html', 'jimu/dijit/TabContainer3', 'jimu/utils', './_dijits/ChartSort', './_dijits/TogglePocket', './_dijits/VisibleSliderBar', './_dijits/SeriesStyle/SeriesStyle', './_dijits/Mark/Marks', './_dijits/ChartColorSetting', './_dijits/DataFields', './_dijits/Toggle', '../utils', 'dijit/form/ValidationTextBox', 'dijit/form/Select', 'dijit/form/RadioButton', 'dijit/form/NumberSpinner', 'dijit/form/TextBox' ], function(on, query, lang, html, declare, Evented, Deferred, BaseDijitSetting, _WidgetsInTemplateMixin, templateString, TabContainer3, jimuUtils, ChartSort, TogglePocket, VisibleSliderBar, SeriesStyle, Marks, ChartColorSetting, DataFields, Toggle, utils) { var clazz = declare([BaseDijitSetting, _WidgetsInTemplateMixin, Evented], { templateString: templateString, type: 'chart', baseClass: 'infographic-chart-dijit-setting', colors: ['#68D2E0', '#087E92', '#47BCF5', '#FBE66A', '#F29157', '#C8501D', '#2DB7C6', '#C4EEF6'], //dataSourceType: '', //CLIENT_FEATURES, FRAMEWORK_FEATURES, FRAMEWORK_STATISTICS //this... config: null, _defColor: null, //{textColor, bgColor} _modes: null, _clusterFields: null, _valueFields: null, // options: // nls // definition // layerObject // popupInfo // dataSource // config // features // keyProperties {type, stack, area, innerRadius} // public methods: // setLayerDefinition, setLayerObject, setFeatures // setConfig // setDataSource // reset // clearMarks // isValid (check config) // getConfig // onChange // updateDijit (try to render chart dijit) //config: // data: // mode:feature|category|count|field // type:column|bar|line|pie // clusterField: fieldInfo.name (The field used as the horizontal axis) // valueFields:[fieldInfo.name] (The field used as the vertical axis) // dateConfig: // minPeriod: year|month|day|hour|minute|second|automatic(Automatically select the appropriate time unit according to the time interval) // isNeedFilled:boolean(Whether to display time nodes without data) // operation:sum|average|min|max // nullValue:boolean (Whether null is counted as zero when calculating the average value) // sortOrder: // isLabelAxis: boolean (Whether to sort by the value of the horizontal axis) // isAsx: boolean (It's ascending order) // field:fieldInfo.name (Sort by the value of which field, only valid when isLabelAxis is false) // maxLabels:number (How many columns(pieces) are displayed) // display // backgroundColor: string for color(#fffff...) // seriesStyle: object, (Style of each series, refer to _dijits/SeriesStyle) // xAxis/yAxis:(Set the style of the horizontal and vertical axes) // show:boolean // format:{type:int | float, digitSeparator: boolean} // textStyle{color, fontSize} // nameTextStyle{color, fontSize} // legend: // show:boolean (Whether to display the legend) // testStyle:{color, fontSize} // dataLabel:(only valid for pie) // show:boolean // testStyle:{color, fontSize} // innerRadius:(Inside radius, only valid for pie) // stack:boolean (Whether to stack two series of columns together, only valid for column,bar) // area:boolean (Whether to draw the area below the line, only valid for line) // marks:object(Add some markers(line, area) to the chart with the axis, only valid for column,bar,line refer to _dijits/Mark) postMixInProperties: function() { lang.mixin(this.nls, window.jimuNls.statisticsChart); }, /* Init default option */ constructor: function(option) { this.inherited(arguments); if (option.nls) { this.nls = option.nls; } this.config = option.config; this._initChartKeyProperty(this.config); var theme = option.appConfig && option.appConfig.theme; this._defColor = utils.getDefaultColorOfTheme(theme); //{textColor, bgColor} }, postCreate: function() { this.inherited(arguments); this._initDijitInTemplate(); this._ignoreEvent(); this._createInitNodeByType(this.config); }, setLayerDefinition: function(definition) { definition = utils.preProcessDefinition(definition); this.definition = definition; if (this.seriesStyleDijit) { this.seriesStyleDijit.setLayerDefinition(definition); } }, setLayerObject: function(layerObject, popupInfo) { this.layerObject = layerObject; this.popupInfo = popupInfo; }, setConfig: function(config) { this.config = utils.upgradeChartAxisFormatConfig(config, this.definition, this.popupInfo); this._initChartKeyProperty(config); }, //features for calculate custom color setFeatures: function(features) { if (this.seriesStyleDijit) { this.features = true; this.seriesStyleDijit.setFeatures(features); } }, setDataSource: function(dataSource) { this.dataSource = dataSource; }, render: function(){ var deferred = new Deferred(); if (!this.definition || !this.config || !this.dataSource || !this.features) { deferred.reject('No definition or config or dataSource or features, render error.'); return deferred; } var dataSource = this.dataSource; this._ignoreEvent(); this._setDataSourceToDijits(dataSource); this._initNodesByDataSource(dataSource); var mode = this.config.data && this.config.data.mode; if (!mode) { mode = this._modes && this._modes[0]; } if (!mode) { deferred.reject('Can not get a valid mode.'); return deferred; } this._onModeChanged(mode, !this.isTemplateConfig(this.config)); this._updateNodeBeforeSetConfig(this.config); this._setConfig(this.config); this._careEvent().then(function(){ this.tryAutoRuning(); deferred.resolve(); }.bind(this)); return deferred; }, _initDijitInTemplate: function() { this.valueFields = new DataFields(); this.valueFields.placeAt(this.valueFieldsDiv); this.own(on(this.valueFields, 'change', this._onValueFieldsChanged.bind(this))); this.bgColor = new ChartColorSetting(); this.bgColor.placeAt(this.bgColorDiv, 'last'); this.own(on(this.bgColor, 'change', this.onChange.bind(this))); this.legendTextColor = new ChartColorSetting(); this.legendTextColor.placeAt(this.legendTextColorDiv, 'last'); this.own(on(this.legendTextColor, 'change', this.onChange.bind(this))); this.horTitleColor = new ChartColorSetting(); this.horTitleColor.placeAt(this.horTitleColorDiv, 'last'); this.own(on(this.horTitleColor, 'change', this.onChange.bind(this))); this.horTextColor = new ChartColorSetting(); this.horTextColor.placeAt(this.horTextColorDiv, 'last'); this.own(on(this.horTextColor, 'change', this.onChange.bind(this))); this.hAxisKeepIntScale = new Toggle(); this.hAxisKeepIntScale.placeAt(this.hAxisKeepIntScaleRow, 'last'); this.own(on(this.hAxisKeepIntScale, 'change', this.onChange.bind(this))); //separator this.hAxisSeparator = new Toggle(); this.hAxisSeparator.placeAt(this.hAxisSeparatorRow, 'last'); this.own(on(this.hAxisSeparator, 'change', this.onChange.bind(this))); this.vAxisSeparator = new Toggle(); this.vAxisSeparator.placeAt(this.vAxisSeparatorRow, 'last'); this.own(on(this.vAxisSeparator, 'change', this.onChange.bind(this))); this.verTitleColor = new ChartColorSetting(); this.verTitleColor.placeAt(this.verTitleColorDiv, 'last'); this.own(on(this.verTitleColor, 'change', this.onChange.bind(this))); this.verTextColor = new ChartColorSetting(); this.verTextColor.placeAt(this.verTextColorDiv, 'last'); this.own(on(this.verTextColor, 'change', this.onChange.bind(this))); this.vAxisKeepIntScale = new Toggle(); this.vAxisKeepIntScale.placeAt(this.vAxisKeepIntScaleRow, 'last'); this.own(on(this.vAxisKeepIntScale, 'change', this.onChange.bind(this))); this.dataLabelTextColor = new ChartColorSetting(); this.dataLabelTextColor.placeAt(this.dataLabelTextColorDiv, 'last'); this.own(on(this.dataLabelTextColor, 'change', this.onChange.bind(this))); }, _initChartKeyProperty: function(config) { if (!config) { return; } var data = config.data; var display = config.display; if (!data) { this.keyProperties = {}; console.error('Invalid configuration file or template'); return; } this.keyProperties = { type: data.type }; if (!display) { return; } this.keyProperties.stack = display.stack; this.keyProperties.area = display.area; this.keyProperties.innerRadius = display.innerRadius; }, isTemplateConfig:function(config){ return !!(config && config.data && !config.data.mode); }, tryAutoRuning: function(){ if(this.canAutoRunning()){ this.onChange(); } }, canAutoRunning: function(){ var config = this.config; var defaultMode = this._modes && this._modes[0]; return this.isTemplateConfig(config) && defaultMode === 'count'; }, _updateNodeBeforeSetConfig: function(config) { if (!config) { return; } var clusterField = config.data.clusterField; clusterField = clusterField || this.clusterFieldSelect.get('value'); this._updateNumberOptionDisplay(clusterField); }, _setDataSourceToDijits: function(dataSource) { if (this.seriesStyleDijit) { this.seriesStyleDijit.setDataSource(dataSource); } }, _onChartModeChanged: function(mode) { if (this.ignoreChangeEvents) { return; } this._onModeChanged(mode); this.onChange(); }, _onModeChanged: function(mode, hasConfig) { this.reset(); var clusterField = hasConfig ? this.config.data.clusterField : this.clusterFieldSelect.get('value'); this._updateElementDisplayByChartMode(mode); //mode select this._chartModeTriggerForModeSelect(mode); //date option container this._chartModeTriggerForDateOption(clusterField); //sort this._chartModeTriggerForSort(mode); //legend this._chartModeTriggerForLegend(mode); //value fields this._chartModeTriggerForValueFields(mode); //series style this._chartModeTriggerForSeriesStyle(mode, hasConfig); this._emitSettingChange(mode, clusterField); }, _emitSettingChange: function(mode, clusterField) { clusterField = clusterField || this.clusterFieldSelect.get('value'); mode = mode || this.chartModeSelect.get('value'); var isDataType = this._isClusterDateType(clusterField); this.emit('chartSettingChanged', { mode: mode, isDataType: isDataType }); }, //triggers _chartModeTriggerForModeSelect: function(mode) { utils.updateOptions(this.chartModeSelect, null, mode); this._updateSelectTitleByValue(this.chartModeSelect, mode); }, _chartModeTriggerForSort: function(mode) { this.chartSortDijit.setMode(mode); var fields = this._getSortFields(mode, true); this.chartSortDijit.setFields(fields); }, _chartModeTriggerForLegend: function(mode) { var seriesStyle = this.config.display && this.config.display.seriesStyle; var seriesStyleType = seriesStyle && seriesStyle.type; this._updateLegendDisplay(mode, seriesStyleType); }, _chartModeTriggerForValueFields: function(mode) { var isSingleMode = this._shouldValueFieldAsSingleMode(mode); if (isSingleMode) { this.valueFields.setSingleMode(); } else { this.valueFields.setMultipleMode(); } }, _chartModeTriggerForSeriesStyle: function(mode, hasConfig) { var data = this.config && this.config.data; var clusterField = hasConfig ? (data && data.clusterField) : this.clusterFieldSelect.get('value'); var valueFields = hasConfig ? data && data.valueFields : this.valueFields.getSelectedFieldNames(); this.seriesStyleDijit.render(mode, clusterField, valueFields); }, _chartModeTriggerForDateOption: function(clusterField) { clusterField = clusterField || this.clusterFieldSelect.get('value'); this._updateDateOptionContainerDisplay(clusterField); }, reset: function() { //reset label(category) field select var clusterField = this._clusterFields && this._clusterFields[0] && this._clusterFields[0].name; utils.updateOptions(this.clusterFieldSelect, null, clusterField); this._updateDateOptionContainerDisplay(); this._updateNumberOptionDisplay(clusterField); //clear value fields selected field this.valueFields.uncheckAllFields(); //reset chart sort this.chartSortDijit.reset(); //clear max categories this.maxLabels.set('value', ''); if (this.keyProperties.type === 'pie') { this.maxLabels.set('value', 100); } //tooltip mode this.tooltipModeSelect.set('value', 'axis'); this._updateTooltipmodeDisplay(); //reset marks this.clearMarks(); }, _setConfig: function(config) { if (!config) { return; } var data = config.data; var display = config.display; //data properties var clusterField, valueFields, operation, dateConfig, sortOrder, maxLabels, nullValue; if (data) { clusterField = data.clusterField; valueFields = data.valueFields; operation = data.operation; dateConfig = data.dateConfig; sortOrder = data.sortOrder; maxLabels = data.maxLabels; nullValue = data.nullValue; } this.clusterFieldSelect.set('value', clusterField); this.valueFields.selectFields(valueFields); this.operationSelect.set('value', operation); if (dateConfig) { //Minimum period this.periodSelect.set('value', dateConfig.minPeriod); //Periods without records this.showRadioBtn.setChecked(dateConfig.isNeedFilled); this.hideRadioBtn.setChecked(!dateConfig.isNeedFilled); } if (sortOrder) { this.chartSortDijit.setConfig(sortOrder); } if (typeof maxLabels !== 'undefined') { this.maxLabels.set('value', maxLabels); } else { this.maxLabels.set('value', ''); } if (typeof nullValue !== 'undefined') { this.zeroRadioBtn.setChecked(nullValue); this.ignoreRadioBtn.setChecked(!nullValue); } //display properties var backgroundColor, tooltip, seriesStyle, innerRadius, legend, xAxis, yAxis, dataLabel, marks; if (display) { backgroundColor = display.backgroundColor; tooltip = display.tooltip; seriesStyle = display.seriesStyle; innerRadius = display.innerRadius; legend = display.legend; xAxis = display.xAxis; yAxis = display.yAxis; dataLabel = display.dataLabel; marks = display.marks; } if (seriesStyle) { this.seriesStyleDijit.setConfig(seriesStyle); } if (typeof innerRadius !== 'undefined') { this.hollowSizeControl.setValue(innerRadius); } if (backgroundColor) { this.bgColor.setSingleColor(backgroundColor); } if (tooltip && this.keyProperties.type !== 'pie') { this._updateTooltipmodeDisplay(); this.tooltipModeSelect.set('value', tooltip.trigger); } //legend, xAxis, yAxis, dataLabel var show, title, nameTextStyle, titleColor, textStyle, labelColor, labelSize, format, formatType, digitSeparator; show = legend && legend.show; textStyle = legend && legend.textStyle; labelColor = textStyle && textStyle.color; labelSize = textStyle && textStyle.fontSize; this.legendTogglePocket.setState(!!show); if (labelColor) { this.legendTextColor.setSingleColor(labelColor); } if (labelSize) { this.legendTextSizeControl.setValue(labelSize); } show = yAxis && yAxis.show; show = typeof show === 'undefined' ? true : show; this.verTogglePocket.setState(!!show); title = yAxis && yAxis.name; textStyle = yAxis && yAxis.textStyle; nameTextStyle = yAxis && yAxis.nameTextStyle; format = yAxis && yAxis.format; titleColor = nameTextStyle && nameTextStyle.color; labelColor = textStyle && textStyle.color; labelSize = textStyle && textStyle.fontSize; formatType = format && format.type; digitSeparator = format && format.digitSeparator; if (title) { this.verTitle.set('value', title); } if (titleColor) { this.verTitleColor.setSingleColor(titleColor); } if (labelColor) { this.verTextColor.setSingleColor(labelColor); } if (labelSize) { this.verticalAxisTextSizeControl.setValue(labelSize); } if (typeof formatType !== 'undefined') { this.vAxisKeepIntScale.setState(formatType === 'int'); } if(typeof digitSeparator !== 'undefined'){ this.vAxisSeparator.setState(digitSeparator); } show = xAxis && xAxis.show; show = typeof show === 'undefined' ? true : show; this.horTogglePocket.setState(!!show); title = xAxis && xAxis.name; textStyle = xAxis && xAxis.textStyle; nameTextStyle = xAxis && xAxis.nameTextStyle; format = xAxis && xAxis.format; titleColor = nameTextStyle && nameTextStyle.color; labelColor = textStyle && textStyle.color; labelSize = textStyle && textStyle.fontSize; formatType = format && format.type; digitSeparator = format && format.digitSeparator; if (title) { this.horTitle.set('value', title); } if (titleColor) { this.horTitleColor.setSingleColor(titleColor); } if (labelColor) { this.horTextColor.setSingleColor(labelColor); } if (labelSize) { this.horizontalAxisTextSizeControl.setValue(labelSize); } if (typeof formatType !== 'undefined') { this.hAxisKeepIntScale.setState(formatType === 'int'); } if(typeof digitSeparator !== 'undefined'){ this.hAxisSeparator.setState(digitSeparator); } show = dataLabel && dataLabel.show; textStyle = dataLabel && dataLabel.textStyle; labelColor = textStyle && textStyle.color; labelSize = textStyle && textStyle.fontSize; this.dataLabelTogglePocket.setState(!!show); if (labelColor) { this.dataLabelTextColor.setSingleColor(labelColor); } if (labelSize) { this.dataLabelSizeControl.setValue(labelSize); } if (marks) { this.marks.setConfig(marks); } }, clearMarks: function() { if (this.marks) { this.marks.setConfig({}); } }, isValid: function() { if (!this.definition) { return false; } return this.maxLabels.isValid() && this.hollowSizeControl.isValid() && this.legendTextSizeControl.isValid() && this.verticalAxisTextSizeControl.isValid() && this.horizontalAxisTextSizeControl.isValid() && this.dataLabelSizeControl.isValid(); }, getConfig: function(check) { if (!this.isValid(check)) { return false; } var type = this.keyProperties.type; var enumValues = { type: type, stack: this.keyProperties.stack, area: this.keyProperties.area, innerRadius: this.keyProperties.innerRadius }; // data tab var mode = this.chartModeSelect.get('value'); enumValues.mode = mode; var clusterField; if (mode === 'feature' || mode === 'category' || mode === 'count') { clusterField = this.clusterFieldSelect.get('value'); enumValues.clusterField = clusterField; } //Date config if (this._isClusterDateType(clusterField)) { var dateConfig = {}; dateConfig.minPeriod = this.periodSelect.get('value'); dateConfig.isNeedFilled = this.showRadioBtn.checked; enumValues.dateConfig = dateConfig; } enumValues.nullValue = this.zeroRadioBtn.checked; enumValues.operation = this.operationSelect.get('value'); enumValues.valueFields = this.valueFields.getSelectedFieldNames(); enumValues.sortOrder = this.chartSortDijit.getConfig(); enumValues.maxLabels = this.maxLabels.get('value') || undefined; //display tab enumValues.backgroundColor = this.bgColor.getSingleColor(); //tooltip if(type !== 'pie'){ var trigger = this.tooltipModeSelect.get('value'); var tooltip = { confine: true, trigger: trigger }; enumValues.tooltip = tooltip; }else{ enumValues.tooltip = { confine: true, trigger: 'item' }; } //legend var legend = { textStyle: {} }; var legendVisible = this.legendTogglePocket.visible(); legend.show = legendVisible ? this.legendTogglePocket.getState() : false; legend.textStyle.color = this.legendTextColor.getSingleColor(); legend.textStyle.fontSize = this.legendTextSizeControl.getValue(); enumValues.legend = legend; //xAxis var xAxis = { textStyle: {} }; xAxis.show = this.horTogglePocket.getState(); var xName = this.horTitle.get('value'); if (xName) { xAxis.name = xName; xAxis.nameTextStyle = {}; xAxis.nameTextStyle.color = this.horTitleColor.getSingleColor(); } xAxis.textStyle.color = this.horTextColor.getSingleColor(); xAxis.textStyle.fontSize = this.horizontalAxisTextSizeControl.getValue(); //format type var xFormat = {}; var xValueAxis = utils.isValueAxis(false, type); if(xValueAxis){ var isXIntType = this.hAxisKeepIntScale.getState(); xFormat = { type: isXIntType ? 'int' : 'float' }; } var _isXNumberOptionValid = this._isNumberOptionValid(false, clusterField, type); if(_isXNumberOptionValid){ var isXHasSeparator = this.hAxisSeparator.getState(); xFormat.digitSeparator = isXHasSeparator; } xAxis.format = xFormat; enumValues.xAxis = xAxis; //yAxis var yAxis = { textStyle: {} }; yAxis.show = this.verTogglePocket.getState(); var yName = this.verTitle.get('value'); if (yName) { yAxis.name = yName; yAxis.nameTextStyle = {}; yAxis.nameTextStyle.color = this.verTitleColor.getSingleColor(); } yAxis.textStyle.color = this.verTextColor.getSingleColor(); yAxis.textStyle.fontSize = this.verticalAxisTextSizeControl.getValue(); //format type var yFormat = {}; var yValueAxis = utils.isValueAxis(true, type); if(yValueAxis){ var isYIntType = this.vAxisKeepIntScale.getState(); yFormat.type = isYIntType ? 'int' : 'float'; } var _isYNumberOptionValid = this._isNumberOptionValid(true, clusterField, type); if(_isYNumberOptionValid){ var isYHasSeparator = this.vAxisSeparator.getState(); yFormat.digitSeparator = isYHasSeparator; } yAxis.format = yFormat; enumValues.yAxis = yAxis; //data labels var dataLabel = { textStyle: {} }; dataLabel.show = this.dataLabelTogglePocket.getState(); dataLabel.textStyle.color = this.dataLabelTextColor.getSingleColor(); dataLabel.textStyle.fontSize = this.dataLabelSizeControl.getValue(); enumValues.dataLabel = dataLabel; //inner radius enumValues.innerRadius = this.hollowSizeControl.getValue(); if (this.marks) { var marks = this.marks.getConfig(); if (marks === false) { return false; } enumValues.marks = marks; } //series style if (this.seriesStyleDijit) { var seriesStyle = this.seriesStyleDijit.getConfig(); enumValues.seriesStyle = seriesStyle; } var chartConfig = utils.getChartConfig(enumValues); if (!chartConfig) { this.dijit.clearChart(); return; } this.config = chartConfig; return chartConfig; }, onChange: function() { if (this.ignoreChangeEvents) { return; } this.getConfig(); this.updateDijit(); }, updateDijit: function() { var isEqual = jimuUtils.isEqual(this.cacheConfig, this.config); if (!isEqual) { this.dijit.setConfig(this.config); this.dijit.startRendering(); } this.cacheConfig = null; this.cacheConfig = lang.clone(this.config); }, _createInitNodeByType: function(config) { var data = config.data; if (!data) { return; } var type = data.type; var tabs = [{ title: this.nls.data, content: this.dataSection }, { title: this.nls.display, content: this.displaySection }]; if (type !== 'pie') { tabs.push({ title: this.nls.marks, content: this.marksSection }); } this.tabContainer = new TabContainer3({ average: true, tabs: tabs }); if (type !== 'pie') { this.marks = new Marks({ chartType: type, nls: this.nls, folderUrl: this.folderUrl, defaultColor: this._defColor.textColor }); this.marks.placeAt(this.marksSection); this.own(on(this.marks, 'change', lang.hitch(this, this.onChange))); this.valueFields.setMultipleMode(); } else { this.valueFields.setSingleMode(); } this._updateKeepIntScaleRowDisplay(); //background color this.bgColor.setSingleColor(this._defColor.bgColor); //series style this.seriesStyleDijit = new SeriesStyle({ nls: this.nls, map: this.map, chartInfo: { type: this.keyProperties.type, area: this.keyProperties.area } }); this.seriesStyleDijit.placeAt(this.chartColorContainer); this.seriesStyleDijit.startup(); this.own(on(this.seriesStyleDijit, 'change', lang.hitch(this, function(seriesStyleConfig){ var seriesStyleType = seriesStyleConfig && seriesStyleConfig.type; var mode = this.chartModeSelect.get('value'); this._updateLegendDisplay(mode, seriesStyleType); this.onChange(); }))); //hollow size, inner radius this.hollowSizeControl = new VisibleSliderBar({ min: 0, max: 60, step: 1, value: this.keyProperties.innerRadius || 0 }); this.own(on(this.hollowSizeControl, 'change', lang.hitch(this, this.onChange))); this.hollowSizeControl.placeAt(this.hollowSize); //legend this.legendTogglePocket = new TogglePocket({ titleLabel: this.nls.legend, content: this.legendTogglePocketContent, className: 'section-item column-type bar-type line-type pie-type' }); this.legendTogglePocket.setState(false); this.own(on(this.legendTogglePocket, 'change', lang.hitch(this, this.onChange))); this.legendTogglePocket.placeAt(this.displaySection); this.legendTextColor.setSingleColor(this._defColor.textColor); this.legendTextSizeControl = new VisibleSliderBar({ min: 6, max: 40, step: 1, value: 12 }); this.own(on(this.legendTextSizeControl, 'change', lang.hitch(this, this.onChange))); this.legendTextSizeControl.placeAt(this.legendTextSize); //vertical axis for column, bar and line this.verTogglePocket = new TogglePocket({ titleLabel: this.nls.verticalAxis, content: this.verTogglePocketContent, className: 'section-item column-type bar-type line-type' }); this.verTogglePocket.setState(false); this.own(on(this.verTogglePocket, 'change', lang.hitch(this, this.onChange))); this.verTogglePocket.placeAt(this.displaySection); this.verTextColor.setSingleColor(this._defColor.textColor); this.verTitleColor.setSingleColor(this._defColor.textColor); this.verticalAxisTextSizeControl = new VisibleSliderBar({ min: 6, max: 40, step: 1, value: 12 }); this.own(on(this.verticalAxisTextSizeControl, 'change', lang.hitch(this, this.onChange))); this.verticalAxisTextSizeControl.placeAt(this.verTextSize); //axis scale type this.vAxisKeepIntScale.setState(false); //xAxis this.horTogglePocket = new TogglePocket({ titleLabel: this.nls.horizontalAxis, content: this.horTogglePocketContent, className: 'section-item column-type bar-type line-type' }); this.horTogglePocket.setState(false); this.own(on(this.horTogglePocket, 'change', lang.hitch(this, this.onChange))); this.horTogglePocket.placeAt(this.displaySection); this.horTextColor.setSingleColor(this._defColor.textColor); this.horTitleColor.setSingleColor(this._defColor.textColor); this.horizontalAxisTextSizeControl = new VisibleSliderBar({ min: 6, max: 40, step: 1, value: 12 }); this.own(on(this.horizontalAxisTextSizeControl, 'change', lang.hitch(this, this.onChange))); this.horizontalAxisTextSizeControl.placeAt(this.horTextSize); this.hAxisKeepIntScale.setState(false); //data Label this.dataLabelTogglePocket = new TogglePocket({ titleLabel: this.nls.dataLabels, content: this.dataLabelTogglePocketContent, className: 'section-item pie-type' }); this.dataLabelTogglePocket.setState(false); this.own(on(this.dataLabelTogglePocket, 'change', lang.hitch(this, this.onChange))); this.dataLabelTogglePocket.placeAt(this.displaySection); this.dataLabelTextColor.setSingleColor(this._defColor.textColor); this.dataLabelSizeControl = new VisibleSliderBar({ min: 6, max: 40, step: 1, value: 12 }); this.own(on(this.dataLabelSizeControl, 'change', lang.hitch(this, this.onChange))); this.dataLabelSizeControl.placeAt(this.dataLabelTextSize); // init chart sort this.chartSortDijit = new ChartSort({ nls: this.nls }); this.own(on(this.chartSortDijit, 'change', lang.hitch(this, this.onChange))); this.chartSortDijit.placeAt(this.chartSort); this.tabContainer.placeAt(this.domNode); //max categories if (type === 'pie') { this.maxLabels.constraints = { min: 1, max: 100 }; this.maxLabels.set('value', 100); this.maxLabels.required = true; } else { this.maxLabels.constraints = { min: 1, max: 3000 }; this.maxLabels.required = false; } this._updateElementDisplayByChartType(type); }, _ignoreEvent: function() { this.ignoreChangeEvents = true; }, _careEvent: function() { var deferred = new Deferred(); setTimeout(function() { this.ignoreChangeEvents = false; deferred.resolve(); }.bind(this), 200); return deferred; }, _updateSelectTitleByValue: function(select, value) { var option = select.getOptions(value); if (option && typeof option.label !== 'undefined') { select.set('title', option.label); } }, _updateLegendDisplay: function(mode, seriesStyleType) { mode = mode || this.chartModeSelect.get('value'); var show = this._shouldLegendDisplay(mode, seriesStyleType); var type = this.keyProperties.type; if (show) { this._showLegend(type); } else { this._hideLegend(); } }, // tool methods for dom and definition _getValueFields: function() { return this.valueFields.getSelectedFieldNames(); }, _getSortFields: function(mode, fromConfig) { var definition = this.definition; if (!definition || !mode) { return; } var valueFields; if (fromConfig) { valueFields = this.config.data && this.config.data.valueFields; } else { valueFields = this._getValueFields(); } if (mode !== 'feature' && (!valueFields || !valueFields[0])) { return; } var fields = []; if (mode === 'feature') { fields = lang.clone(definition.fields); fields = utils.getNotGeometryFields(fields); } else if (valueFields) { fields = utils.getFieldInfosByFieldName(valueFields, definition); } var fieldOption = fields.map(function(field) { return { value: field.name, label: field.alias || field.name }; }); return fieldOption; }, _initNodesByDataSource: function(dataSource) { this._initInfoByDataSource(dataSource); //init nodes by data source this._fillModeSelect(this._modes); this._fillClusterFieldSelect(this._clusterFields); this._fillValueFieldLists(this._valueFields); }, _initInfoByDataSource: function(dataSource) { if (!dataSource) { return; } this._modes = this._getSupportedModes(dataSource, this.definition); var fields = this._getSupportFields(this.definition); this._clusterFields = fields[0]; this._valueFields = fields[1]; }, _getSupportedModes: function(dataSource, definition) { if (!definition || !dataSource) { return; } var isFSDS = false; var modes = ["feature", "category", "count", "field"]; var frameWorkDsId = dataSource.frameWorkDsId; if (frameWorkDsId) { var dataSources = this.appConfig.dataSource && this.appConfig.dataSource.dataSources; var dsMeta = dataSources[frameWorkDsId]; if (dsMeta.type === 'FeatureStatistics') { isFSDS = true; var dataSchema = lang.clone(dsMeta.dataSchema); var groupByFields = dataSchema.groupByFields || []; if (groupByFields.length > 0) { //available modes: category, count if (utils.hasNumberFields(definition)) { modes = ["category", "count"]; } else { modes = ["count"]; } } else { modes = ["field"]; } } } if (!isFSDS && !utils.hasNumberFields(definition)) { modes = ['count']; } return modes; }, _fillModeSelect: function(modes) { if (!modes) { return; } //remove all mode this.chartModeSelect.removeOption(this.chartModeSelect.getOptions()); modes.forEach(function(mode) { if (mode === 'feature') { this.chartModeSelect.addOption({ value: 'feature', label: this.nls.featureOption }); } else if (mode === 'category') { this.chartModeSelect.addOption({ value: 'category', label: this.nls.categoryOption }); } else if (mode === 'count') { this.chartModeSelect.addOption({ value: 'count', label: this.nls.countOption }); } else if (mode === 'field') { this.chartModeSelect.addOption({ value: 'field', label: this.nls.fieldOption }); } }.bind(this)); }, _getSupportFields: function(definition) { if (!definition) { return; } var fields = lang.clone(definition.fields); if (!fields || !fields.length) { return; } //update have been checked to uncheck //fix a bug of all field auto checked when select ds from featureStatistics fields.forEach(function(item) { if (item.checked) { item.checked = false; } }); var gbFields = definition.groupByFields; //clusterFields var clusterFields = utils.getClusterFields(fields, gbFields); //valueFields var valueFields = utils.getValueFields(fields, gbFields, clusterFields); return [clusterFields, valueFields]; }, _fillClusterFieldSelect: function(clusterFields) { var fieldOptions = clusterFields.map(function(field) { return { label: field.alias || field.name, value: field.name }; }); utils.updateOptions(this.clusterFieldSelect, fieldOptions); }, _fillValueFieldLists: function(valueFields) { this.valueFields.setFields(valueFields); }, //value fields trigger _valueFieldsTriggerForTooltipMode: function(){ this._updateTooltipmodeDisplay(); }, _valueFieldsTriggerForSeriesStyle: function(){ var mode = this.chartModeSelect.get('value'); var clusterField = this.clusterFieldSelect.get('value'); var valueFields = this.valueFields.getSelectedFieldNames(); this.seriesStyleDijit.render(mode, clusterField, valueFields); }, _valueFieldsTriggerForChartSort: function(){ var mode = this.chartModeSelect.get('value'); var fields = this._getSortFields(mode); this.chartSortDijit.setFields(fields); }, // -------------- change event ------------ _onClusterFieldChanged: function(clusterField) { if (this.ignoreChangeEvents) { return; } var mode = this.chartModeSelect.get('value'); this._clusterFieldChangeTriggerForDateOption(clusterField); this._clusterFieldChangeTriggerForSeriesStyle(mode, clusterField); this._clusterFieldChangeTriggerForNumberOption(clusterField); this.onChange(); this._emitSettingChange(mode, clusterField); }, _clusterFieldChangeTriggerForDateOption: function(clusterField) { this._updateDateOptionContainerDisplay(clusterField); }, _clusterFieldChangeTriggerForSeriesStyle: function(mode, clusterField) { var valueFields = this.valueFields.getSelectedFieldNames(); this.seriesStyleDijit.render(mode, clusterField, valueFields); }, _updateKeepIntScaleRowDisplay: function() { var vertivcalValid = utils.isValueAxis(true, this.keyProperties.type); this._updateAxisIntScaleRowDisplay(true, vertivcalValid); this._updateAxisIntScaleRowDisplay(false, !vertivcalValid); }, _updateNumberOptionDisplay: function(clusterField) { var vertivcalValid = this._isNumberOptionValid(true, clusterField, this.keyProperties.type); var horizontalValid = this._isNumberOptionValid(false, clusterField, this.keyProperties.type); if (vertivcalValid) { this._updateAxisNumberOptionDisplay(true, true); } else { this._updateAxisNumberOptionDisplay(true, false); } if (horizontalValid) { this._updateAxisNumberOptionDisplay(false, true); } else { this._updateAxisNumberOptionDisplay(false, false); } }, _clusterFieldChangeTriggerForNumberOption: function(clusterField) { this._updateNumberOptionDisplay(clusterField); }, _onValueFieldsChanged: function() { if (this.ignoreChangeEvents) { return; } this._valueFieldsTriggerForSeriesStyle(); this._valueFieldsTriggerForChartSort(); this._valueFieldsTriggerForTooltipMode(); this.onChange(); }, _shouldShowDateOption: function(clusterField) { var mode = this.chartModeSelect.get('value'); clusterField = clusterField || this.clusterFieldSelect.get('value'); var definition = this.definition; var isDateField = utils.isDateField(clusterField, definition); return (mode === 'category' || mode === 'count') && isDateField; }, _shouldShowTooltipMode: function() { var type = this.keyProperties.type; if(type === 'pie'){ return false; } var mode = this.chartModeSelect.get('value'); if(mode === 'count' || mode === 'field'){ return false; } var valueFields = this.valueFields.getSelectedFieldNames(); return valueFields.length > 1; }, //---------- Tool methods for dom ----------- _showDateOptionContainer: function(type) { if (type !== 'pie') { this._showPeriodsRecordsDiv(); } this._showPeridoDiv(); }, _hideDateOptionContainer: function() { this._hidePeridoDiv(); this._hidePeriodsRecordsDiv(); }, _showPeridoDiv: function() { html.setStyle(this.periodDiv, 'display', ''); }, _hidePeridoDiv: function() { html.setStyle(this.periodDiv, 'display', 'none'); }, _showPeriodsRecordsDiv: function() { html.setStyle(this.periodsRecordsDiv, 'display', ''); }, _hidePeriodsRecordsDiv: function() { html.setStyle(this.periodsRecordsDiv, 'display', 'none'); }, _showTooltipMode: function(){ html.setStyle(this.tooltipDiv, 'display', ''); }, _hideTooltipMode: function(){ html.setStyle(this.tooltipDiv, 'display', 'none'); }, _hideLegend: function() { if (this.legendTogglePocket) { this.legendTogglePocket.hide(); } }, _showLegend: function() { if (this.legendTogglePocket) { this.legendTogglePocket.show(); } }, _updateAxisNumberOptionDisplay: function(isVertical, show) { if (show) { this._showAxisSeparatorRow(isVertical); } else { this._hideAxisSeparatorRow(isVertical); } }, _updateAxisIntScaleRowDisplay: function(isVertical, show) { if (show) { this._showAxisKeepIntScaleRow(isVertical); } else { this._hideAxisKeepIntScaleRow(isVertical); } }, _showAxisKeepIntScaleRow: function(isVertical) { if (isVertical) { html.removeClass(this.vAxisKeepIntScaleRow, 'hide'); } else { html.removeClass(this.hAxisKeepIntScaleRow, 'hide'); } }, _hideAxisKeepIntScaleRow: function(isVertical) { if (isVertical) { html.addClass(this.vAxisKeepIntScaleRow, 'hide'); } else { html.addClass(this.hAxisKeepIntScaleRow, 'hide'); } }, _showAxisSeparatorRow: function(isVertical) { if (isVertical) { html.removeClass(this.vAxisSeparatorRow, 'hide'); } else { html.removeClass(this.hAxisSeparatorRow, 'hide'); } }, _hideAxisSeparatorRow: function(isVertical) { if (isVertical) { html.addClass(this.vAxisSeparatorRow, 'hide'); } else { html.addClass(this.hAxisSeparatorRow, 'hide'); } }, _showSectionItem: function(itemDom) { html.removeClass(itemDom, 'hide'); }, _hideSectionItem: function(itemDom) { html.addClass(itemDom, 'hide'); }, //---------- pure Tool methods ----------- _shouldValueFieldAsSingleMode: function(mode) { var type = this.keyProperties.type; return (mode === 'feature' || mode === 'category') && type === 'pie'; }, _isNumberOptionValid: function(isVertical, clusterField, type) { if (!utils.isAxisType(type)) { return; } var valueType = utils.isValueAxis(isVertical, type); if (valueType) { return true; } var mode = this.chartModeSelect.get('value'); if (mode === 'field') { return false; } clusterField = clusterField || this.clusterFieldSelect.get('value'); return this.isClusterNumberType(clusterField); }, isClusterNumberType: function(clusterField) { var definition = this.definition; return utils.isNumberType(clusterField, definition, true); }, _shouldLegendDisplay: function(mode, seriesStyleType) { var type = this.keyProperties.type; var legendDisplay; if (type === 'pie') { legendDisplay = true; } else { legendDisplay = true; if (mode === 'count' || mode === 'field') { legendDisplay = false; } else { legendDisplay = seriesStyleType !== 'layerSymbol'; } } return legendDisplay; }, _tryGetLayerIdFromDataSource: function(dataSource) { if (!dataSource) { return; } var layerId = dataSource.layerId; var frameWorkDsId = dataSource.frameWorkDsId; if (!layerId && frameWorkDsId) { var dsTypeInfo = utils.parseDataSourceId(frameWorkDsId); if (dsTypeInfo && dsTypeInfo.layerId !== 'undefined') { layerId = dsTypeInfo.layerId; } } return layerId; }, _updateDateOptionContainerDisplay: function(clusterField) { var show = this._shouldShowDateOption(clusterField); var type = this.keyProperties.type; if (show) { this._showDateOptionContainer(type); } else { this._hideDateOptionContainer(); } }, _updateTooltipmodeDisplay: function() { var show = this._shouldShowTooltipMode(); if (show) { this._showTooltipMode(); } else { this._hideTooltipMode(); } }, _isClusterDateType: function(clusterField) { return this._shouldShowDateOption(clusterField); }, _updateElementDisplayByChartMode: function(mode) { var className = mode + '-mode'; var dataSectionItems = query('.section-item', this.dataSection); dataSectionItems.forEach(lang.hitch(this, function(sectionItem) { if (html.hasClass(sectionItem, className)) { this._showSectionItem(sectionItem); } else { this._hideSectionItem(sectionItem); } })); }, _updateElementDisplayByChartType: function(type) { //update visibility var chartTypeClassName = type + "-type"; var displayItems = query('.section-item', this.displaySection); displayItems.forEach(lang.hitch(this, function(sectionItem) { if (html.hasClass(sectionItem, chartTypeClassName)) { this._showSectionItem(sectionItem); } else { this._hideSectionItem(sectionItem); } })); }, _showChartNoData: function(tempConfig) { setTimeout(function() { if (tempConfig) { this.dijit.setConfig(tempConfig); } this.dijit.clearChart(); }.bind(this), 200); }, _getDefaultFieldName: function() { var fieldName; if (this._clusterFieldOptions && this._clusterFieldOptions[0]) { fieldName = this._clusterFieldOptions[0].value; } return fieldName; } }); return clazz; });
export * from './Tw2Animation'; export * from './Tw2AnimationController'; export * from './Tw2Bone'; export * from './Tw2Model'; export * from './Tw2Track'; export * from './Tw2TrackGroup';
module.exports = { description: 'excludes constructors that are known to be pure', options: { moduleName: 'myBundle' } };
/** * @depends jquery, core.console, jquery.extra, jquery.balclass * @name jquery.balclass.bespin.sparkle * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} */ /** * jQuery Aliaser */ (function($){ /** * Prepare Body */ $(document.body).addClass('js'); /** * jQuery Sparkle - jQuery's DRY Effect Library * @version 1.5.0 * @date August 28, 2010 * @since 1.0.0, June 30, 2010 * @package jquery-sparkle {@link http://balupton.com/projects/jquery-sparkle} * @author Benjamin "balupton" Lupton {@link http://balupton.com} * @copyright (c) 2009-2010 Benjamin Arthur Lupton {@link http://balupton.com} * @license MIT License {@link http://creativecommons.org/licenses/MIT/} */ if ( !($.Sparkle||false) ) { /** * $.SparkleClass */ $.SparkleClass = $.BalClass.clone({ /** * Alias for Sparkle.addExtension */ addExtensions: function() { // Prepare var Sparkle = this; // Handle var result = Sparkle.addExtension.apply(Sparkle,arguments); // Fire the Configured Promise Sparkle.onConfigured(true); // Return result return result; }, /** * Add an Extension */ addExtension: function() { // Prepare var Sparkle = this, Extension = {}; // Determine switch ( true ) { case Boolean(arguments[2]||false): // name, config, extension // name, extension, config if ( typeof arguments[0] === 'string' && typeof arguments[2] === 'function' && typeof arguments[1] === 'object' ) { Extension.extension = arguments[2]; Extension.config = arguments[1]; Extension.name = arguments[0]; } if ( typeof arguments[0] === 'string' && typeof arguments[1] === 'function' && typeof arguments[2] === 'object' ) { Extension.extension = arguments[1]; Extension.config = arguments[2]; Extension.name = arguments[0]; } else { window.console.error('Sparkle.addExtension: Invalid Input'); } break; case Boolean(arguments[1]||false): // name, Extension // name, extension if ( typeof arguments[0] === 'string' && typeof arguments[1] === 'function' ) { Extension.extension = arguments[1]; Extension.name = arguments[0]; } else if ( typeof arguments[0] === 'string' && Sparkle.isExtension(arguments[1]) ){ Extension = arguments[1]; Extension.name = arguments[0]; } else { window.console.error('Sparkle.addExtension: Invalid Input'); } break; case Boolean(arguments[0]||false): // Extension // Series if ( Sparkle.isExtension(arguments[0]) ) { Extension = arguments[0]; } else if ( typeof arguments[0] === 'object' || typeof arguments[0] === 'array' ) { // Series $.each(arguments[0],function(key,value){ Sparkle.addExtension(key,value); }); // Chain return this; } else { window.console.error('Sparkle.addExtension: Invalid Input'); } break; } // Ensure Extension.config = Extension.config||{}; Extension.extension = Extension.extension||{}; // Add Extension Sparkle.addConfig(Extension.name, Extension); // Bind Ready Handler Sparkle.onReady(function(){ // Fire Extension Sparkle.triggerExtension($('body'),Extension); }); // Chain return this; }, /** * Do we have that Extension */ hasExtension: function (extension) { // Prepare var Sparkle = this, Extension = Sparkle.getExtension(extension); // Return return Extension !== 'undefined'; }, /** * Is the passed Extension an Extension */ isExtension: function (extension) { // Return return Boolean(extension && (extension.extension||false)); }, /** * Get the Extensions */ getExtensions: function ( ) { // Prepare var Sparkle = this, Config = Sparkle.getConfig(), Extensions = {}; // Handle $.each(Config,function(key,value){ if ( Sparkle.isExtension(value) ) { Extensions[key] = value; } }); // Return Extensions return Extensions; }, /** * Get an Extension */ getExtension: function(extension) { // Prepare var Sparkle = this, Extension = undefined; // HAndle if ( Sparkle.isExtension(extension) ) { Extension = extension; } else { var fetched = Sparkle.getConfigWithDefault(extension); if ( Sparkle.isExtension(fetched) ) { Extension = fetched; } } // Return Extension return Extension; }, /** * Get Config from an Extension */ getExtensionConfig: function(extension) { // Prepare var Sparkle = this Extension = Sparkle.getExtension(extension); // Return return Extension.config||{}; }, /** * Apply Config to an Extension */ applyExtensionConfig: function(extension, config) { // Prepare var Sparkle = this; // Handle Sparkle.applyConfig(extension, {'config':config}); // Chain return this; }, /** * Trigger all the Extensions */ triggerExtensions: function(element){ // Prepare var Sparkle = this, Extensions = Sparkle.getExtensions(); // Handle $.each(Extensions,function(extension,Extension){ Sparkle.triggerExtension(element,Extension); }); // Chain return this; }, /** * Trigger Extension */ triggerExtension: function(element,extension){ // Prepare var Sparkle = this, Extension = Sparkle.getExtension(extension), element = element instanceof jQuery ? element : $('body'); // Handle if ( Extension ) { return Extension.extension.apply(element, [Sparkle, Extension.config, Extension]); } else { window.console.error('Sparkle.triggerExtension: Could not find the extension.', [this,arguments], [extension,Extension]); } // Chain return this; }, /** * Sparkle jQuery Function */ fn: function(Sparkle,extension){ // Prepare var $el = $(this); // HAndle if ( extension ) { // Individual Sparkle.triggerExtension.apply(Sparkle, [$el,extension]); } else { // Series Sparkle.triggerExtensions.apply(Sparkle, [$el]); } // Chain return this; }, /** * Sparkle Constructor */ built: function(){ // Prepare var Sparkle = this; // -------------------------- // Attach $.fn.sparkle = function(extension) { // Alias return Sparkle.fn.apply(this,[Sparkle,extension]); }; // -------------------------- // Setup Promises // Bind DomReady Handler $(function(){ // Fire DocumentReady Promise Sparkle.onDocumentReady(true); }); // Bind Configured Handler Sparkle.onConfigured(function(){ // Bind DocumentReady Handler Sparkle.onDocumentReady(function(){ // Fire Ready Promise Sparkle.onReady(true); }); }); // -------------------------- // Return true return true; }, /** * Handle the Configured Promise * We use promise as the function will fire if the event was already fired as it is still true * @param {mixed} arguments */ onConfigured: function(){ var Sparkle = this; // Handle Promise return $.promise({ 'object': Sparkle, 'handlers': 'onConfiguredHandlers', 'flag': 'isConfigured', 'arguments': arguments }); }, /** * Handle the DocumentReady Promise * We use promise as the function will fire if the event was already fired as it is still true * @param {mixed} arguments */ onDocumentReady: function(handler){ // Prepare var Sparkle = this; // Handle Promise return $.promise({ 'object': Sparkle, 'handlers': 'onDocumentReadyHandlers', 'flag': 'isDocumentReady', 'arguments': arguments }); }, /** * Handle the Ready Promise * We use promise as the function will fire if the event was already fired as it is still true * @param {mixed} arguments */ onReady: function(handler){ // Prepare var Sparkle = this; // Handle Promise return $.promise({ 'object': Sparkle, 'handlers': 'onReadyHandlers', 'flag': 'isReady', 'arguments': arguments }); } }); /** * $.Sparkle */ $.Sparkle = $.SparkleClass.create().addExtensions({ 'date': { config: { selector: '.sparkle-date', datepickerOptions: { }, demoText: 'Date format must use the international standard: [year-month-day]. This due to other formats being ambigious eg. day/month/year or month/day/year.', demo: '<input type="text" class="sparkle-date" value="2010-08-05" />' }, extension: function(Sparkle, config){ var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Check if ( typeof $elements.Datepicker === 'undefined' ) { window.console.warn('Datepicker not loaded. Did you forget to include it?'); return false; } // Apply $elements.Datepicker(config.datepickerOptions); // Done return true; } }, 'time': { config: { selector: '.sparkle-time', timepickerOptions: { }, demoText: 'Time format must be either [hour:minute:second] or [hour:minute], with hours being between 0-23.', demo: '<input type="text" class="sparkle-time" value="23:11" />' }, extension: function(Sparkle, config){ var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Check if ( typeof $elements.Timepicker === 'undefined' ) { window.console.warn('Timepicker not loaded. Did you forget to include it?'); return false; } // Apply $elements.Timepicker(config.timepickerOptions); // Done return true; } }, 'datetime': { config: { selector: '.sparkle-datetime', datepickerOptions: { }, timepickerOptions: { }, demoText: 'Date format must use the international standard: [year-month-day]. This due to other formats being ambigious eg. day/month/year or month/day/year.<br/>\ Time format must be either [hour:minute:second] or [hour:minute], with hours being between 0-23.', demo: '<input type="text" class="sparkle-datetime" value="2010-08-05 23:10:09" />' }, extension: function(Sparkle, config){ var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Check if ( typeof $elements.Datetimepicker === 'undefined' ) { window.console.warn('Datetimepicker not loaded. Did you forget to include it?'); return false; } // Apply $elements.Datetimepicker({ datepickerOptions: Sparkle.getExtensionConfig('date').datepickerOptions, timepickerOptions: Sparkle.getExtensionConfig('time').timepickerOptions }); // Done return true; } }, 'hide-if-empty': { config: { selector: '.sparkle-hide-if-empty:empty', demo: '<div class="sparkle-hide-if-empty" style="border:1px solid black"></div>'+"\n"+ '<div class="sparkle-hide-if-empty" style="border:1px solid black">Hello World</div>' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply $elements.hide(); // Done return true; } }, 'hide': { config: { selector: '.sparkle-hide', demo: '<div class="sparkle-hide">Something to Hide when Sparkle has Loaded</div>' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply $elements.removeClass(config.selector.replace('.','')).hide(); // Done return true; } }, 'show': { config: { selector: '.sparkle-show', demo: '<div class="sparkle-show" style="display:none;">Something to Show when Sparkle has Loaded</div>' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply $elements.removeClass(config.selector.replace('.','')).show(); // Done return true; } }, 'subtle': { config: { selector: '.sparkle-subtle', css: { }, inSpeed: 200, inCss: { 'opacity': 1 }, outSpeed: 400, outCss: { 'opacity': 0.5 }, demo: '<div class="sparkle-subtle">This is some subtle text. (mouseover)</div>' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply var css = {}; $.extend(css, config.outCss, config.css); $elements.css(css).opacityFix().hover(function() { // Over $(this).stop(true, false).animate(config.inCss, config.inSpeed); }, function() { // Out $(this).stop(true, false).animate(config.outCss, config.outSpeed); }); // Done return true; } }, 'panelshower': { config: { selectorSwitch: '.sparkle-panelshower-switch', selectorPanel: '.sparkle-panelshower-panel', inSpeed: 200, outSpeed: 200, demo: '' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $switches = $this.findAndSelf(config.selectorSwitch); var $panels = $this.findAndSelf(config.selectorPanel); if ( !$switches.length && !$panels.length ) { return true; } // Events var events = { clickEvent: function(event) { var $switch = $(this); var $panel = $switch.siblings(config.selectorPanel).filter(':first'); var value = $switch.val(); var show = $switch.is(':checked,:selected') && !(!value || value === 0 || value === '0' || value === 'false' || value === false || value === 'no' || value === 'off'); if (show) { $panel.fadeIn(config.inSpeed); } else { $panel.fadeOut(config.outSpeed); } } }; // Apply $switches.once('click',events.clickEvent); $panels.hide(); // Done return true; } }, 'autogrow': { config: { selector: 'textarea.autogrow,textarea.autosize', demo: '<textarea class="autogrow">This textarea will autogrow with your input. - Only if jQuery Autogrow has been loaded.</textarea>' }, extension: function(Sparkle, config){ var $this = $(this); // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Check if (typeof $.fn.autogrow === 'undefined') { window.console.warn('autogrow not loaded. Did you forget to include it?'); return false; } // Apply $elements.autogrow(); // Done return true; } }, 'gsfnwidget': { config: { selector: '.gsfnwidget', demo: '<a class="gsfnwidget" href="#">This link will show a GetSatisfaction Widget onclick. - Only if GetSatisfaction has been loaded.</a>' }, extension: function(Sparkle, config) { var $this = $(this); // Events var events = { clickEvent: function(event) { if ( typeof GSFN_feedback_widget === 'undefined' ) { window.console.warn('GSFN not loaded. Did you forget to include it?'); return true; // continue with click event } GSFN_feedback_widget.show(); //event.stopPropagation(); event.preventDefault(); return false; } }; // Fetch var $elements = $this.findAndSelf(config.selector); if ( !$elements.length ) { return true; } // Apply $elements.once('click',events.clickEvent); // Done return true; } }, 'hint': { config: { selector: '.form-input-tip,.sparkle-hint,.sparkle-hint-has,:text[placeholder]', hasClass: 'sparkle-hint-has', hintedClass: 'sparkle-hint-hinted', demoText: 'Simulates HTML5\'s <code>placeholder</code> attribute for non HTML5 browsers. Placeholder can be the <code>title</code> or <code>placeholder</code> attribute. Placeholder will not be sent with the form (unlike most other solutions). The <code>sparkle-hint</code> class is optional if you are using the <code>placeholder</code> attribute.', demo: '<input type="text" class="sparkle-hint" placeholder="This is some hint text." title="This is a title." /><br/>'+"\n"+ '<input type="text" class="sparkle-hint" title="This is some hint text." />' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $inputs = $this.findAndSelf(config.selector).addClass(config.hasClass); if ( !$inputs.length ) { return true; } // Events var events = { focusEvent: function(){ var $input = $(this); var tip = $input.attr('placeholder')||$input.attr('title'); var val = $input.val(); // Handle if (tip === val) { $input.val('').removeClass(config.hintedClass); } // Done return true; }, blurEvent: function(){ var $input = $(this); var tip = $input.attr('placeholder')||$input.attr('title'); var val = $input.val(); // Handle if (tip === val || !val) { $input.val('').addClass(config.hintedClass).val(tip); } // Done return true; }, submitEvent: function(){ $inputs.trigger('focus'); } }; // Apply if ( typeof Modernizr !== 'undefined' && Modernizr.input.placeholder ) { // We Support HTML5 Hinting $inputs.each(function(){ var $input = $(this); // Set the placeholder as the title if the placeholder does not exist // We could use a filter selector, however we believe this should be faster - not benchmarked though var title = $input.attr('title'); if ( title && !$input.attr('placeholder') ) { $input.attr('placeholder',title); } }); } else { // We Support Javascript Hinting $inputs.each(function(){ var $input = $(this); $input.once('focus',events.focusEvent).once('blur',events.blurEvent).trigger('blur'); }); $this.find('form').once('submit',events.submitEvent); } // Done return $this; } }, 'debug': { config: { selector: '.sparkle-debug', hasClass: 'sparkle-debug-has', hintedClass: 'sparkle-debug-hinted', showVar: 'sparkle-debug-show', demo: '' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $debug = $this.findAndSelf(config.selector); if ( !$debug.length ) { return true; } // Apply $debug.addClass(config.hasClass).find('.value:has(.var)').hide().siblings('.name,.type').addClass('link').once('singleclick',events.clickEvent).once('dblclick',events.dblclickEvent); // Events var events = { clickEvent: function(event){ var $this = $(this); var $parent = $this.parent(); var show = !$parent.data(config.showVar); $parent.data(config.showVar, show); $this.siblings('.value').toggle(show); }, dblclickEvent: function(event){ var $this = $(this); var $parent = $this.parent(); var show = $parent.data(config.showVar); // first click will set this off $parent.data(config.showVar, show); $parent.find('.value').toggle(show); } }; // Done return $this; } }, 'submit': { config: { selector: '.sparkle-submit', demoText: 'Adding the <code>sparkle-submit</code> class to an element within a <code>form</code> will submit the form when that element is clicked.' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $submit = $this.findAndSelf(config.selector); if ( !$submit.length ) { return true; } // Events var events = { clickEvent: function(event){ var $this = $(this).submitForm(); return true; } }; // Apply $submit.once('singleclick',events.clickEvent); // Done return $this; } }, 'submitswap': { config: { selector: '.sparkle-submitswap', demoText: 'Adding the <code>sparkle-submitswap</code> class to a submit button, will swap it\'s value with it\'s title when it has been clicked. Making it possible for a submit value which isn\'t the submit button\'s text.' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $submit = $this.findAndSelf(config.selector); if ( !$submit.length ) { return true; } // Events var events = { clickEvent: function(event){ // Fetch var $submit = $(this); // Put correct value back $submit.val($submit.data('sparkle-submitswap-value')); // Continue with Form Submission return true; } }; // Apply $submit.once('singleclick',events.clickEvent); $submit.each(function(){ var $submit = $(this); $submit.data('sparkle-submitswap-value', $submit.val()); $submit.val($submit.attr('title')); $submit.removeAttr('title'); }); // Done return $this; } }, 'highlight-values': { config: { selector: '.sparkle-highlight-values', innerSelector: 'td,.column', empty: ['',false,null,'false','null',0,'-'], emptyClass: 'sparkle-highlight-values-empty', notemptyClass: 'sparkle-highlight-values-notempty', demoText: 'Adding the <code>sparkle-highlight-values</code> class to a table will highlight all <code>td</code> elements with non empty values. By adding <code>sparkle-highlight-values-notempty</code> or <code>sparkle-highlight-values-empty</code> to the corresponding <code>td</code> element - which can by styled by yourself. Benefit over css\'s <code>:empty</code> as 0, false, null and - are counted as empty values (not just "").' }, extension: function(Sparkle, config) { var $this = $(this); // Fetch var $container = $this.findAndSelf(config.selector); if ( !$container.length ) { return true; } // Apply var $inner = $container.findAndSelf(config.innerSelector); $inner.each(function(){ var $this = $(this); var value = $this.text().trim(); var empty = config.empty.has(value); if ( empty ) { $this.addClass(config.emptyClass); } else { $this.addClass(config.notemptyClass); } }); // Done return $this; } }, 'demo': { config: { selector: '.sparkle-demo', hasClass: 'sparkle-debug-has', demoText: 'Adding the <code>sparkle-demo</code> will display all these demo examples used on this page.' }, extension: function(Sparkle, config){ var $this = $(this); var $container = $this.findAndSelf(config.selector); // Prepare if ( $container.hasClass(config.hasClass) || !$container.length ) { // Only run once return true; } $container.addClass(config.hasClass); // Fetch var Extensions = Sparkle.getExtensions(); // Cycle $.each(Extensions,function(extension,Extension){ var demo = Extension.config.demo||''; var demoText = Extension.config.demoText||''; if ( !demo && !demoText ) { return true; // continue } var $demo = $( '<div class="sparkle-demo-section" id="sparkle-demo-'+extension+'">\ <h3>'+extension+'</h3>\ </div>' ); if ( demoText ) { $demo.append('<div class="sparkle-demo-text">'+demoText+'</div>'); } if ( demo ) { var demoCode = demo.replace(/</g,'&lt;').replace(/>/g,'&gt;'); $demo.append( '<h4>Example Code:</h4>\ <pre class="code language-html sparkle-demo-code">'+demoCode+'</pre>\ <h4>Example Result:</h4>\ <div class="sparkle-demo-result">'+demo+'</div>' ); } $demo.appendTo($container); }); // Sparkle $container.sparkle(); // Done return $this; } } }); } else { window.console.warn('$.Sparkle has already been defined...'); } })(jQuery);
/** # watermark(表單欄位浮水印)[view] ## 更新訊息 原始來源: https://code.google.com/p/jquery-watermark 最後編輯者: Hank Kuo 最後修改日期: 2013/11/07 更新資訊: 時間 | 版本 | 說明 | 編輯人 ---------- | ---- | --------------------- | ---- 2013.11.07 | 1.0 | 建立元件 | Hank Kuo ## 相依套件與檔案 #### 相依第三方套件 vendor/jquery/plugins/jquery.watermark.min.js #### 相依元件 #### 相依外部檔案與目錄 ## 相依後端I/O #### controller: #### template: ``` {{#view "watermark" watermark="this is watermark"}} {{input type="text" value=viewText}} {{/view}} ``` @class watermark @since 1.0 */ /** ###### 浮水印內容 @property watermark @type String @default '' @optional **/ var watermark = Ember.View.extend({ didInsertElement: function() { var that = this; var self = '#' + that.get('elementId'); var watermark = this.get('watermark') || ''; var child = '#'; var inputNumber = $(self + ' input').length; var textareaNumber = $(self + ' textarea').length; var childNumber = inputNumber + textareaNumber; if (childNumber == 0) { throw new Error('view(watermark): 必須要有input或textarea'); } else if (childNumber > 1) { throw new Error('view(watermark): 只能有一個input或textarea'); } if (inputNumber) { child = $(self + ' input'); } else { child = $(self + ' textarea'); } $(child).watermark(watermark); } }); export default watermark;
/** * @fileoverview * Shuffl card plug-in for simple card containing an image and associated notes * * @author Graham Klyne * @version $Id: shuffl-card-imagegallery.js 828 2010-06-14 15:26:11Z gk-google@ninebynine.org $ * * Coypyright (C) 2009, University of Oxford * * Licensed under the MIT License. You may obtain a copy of the License at: * * http://www.opensource.org/licenses/mit-license.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // ---------------------------------------------------------------- // Globals and data // ---------------------------------------------------------------- /** * create shuffl namespace */ if (typeof shuffl == "undefined") { alert("shuffl-card-imagegallery.js: shuffl-base.js must be loaded first"); } if (typeof shuffl.card == "undefined") { alert("shuffl-card-imagegallery.js: shuffl-cardhandlers.js must be loaded before this"); } /** * Create namespace for this card type */ shuffl.card.imagegallery = {}; /** * Template for initializing a card model, and * creating new card object for serialization. */ shuffl.card.imagegallery.datamap = { 'shuffl:title': { def: '@id' } , 'shuffl:tags': { def: '@tags', type: 'array' } //// @@more }; /** * jQuery base element for building new cards (used by shuffl.makeCard) */ shuffl.card.imagegallery.blank = jQuery( "<div class='shuffl-card-setsize' style='z-index:10;'>\n"+ " <chead>\n"+ " <chandle><c></c></chandle>" + " <ctitle>card title</ctitle>\n"+ " </chead>\n"+ " <crow>\n"+ " <cbody>...</cbody>\n"+ " </crow>\n"+ " <cfoot>\n"+ " <ctagslabel>Tags: </ctagslabel><ctags>card_ZZZ tags</ctags>\n"+ " </cfoot>"+ "</div>"); /** * Creates and return a new card instance. * * @param cardtype type identifier for the new card element * @param cardcss CSS class name(s) for the new card element * @param cardid local card identifier - a local name for the card, * which may be combined with a base URI to form a URI * for the card. * @param carddata an object or string containing additional data used in * constructing the body of the card. This is either a * string or an object structure with fields * 'shuffl:title', 'shuffl:tags' and 'shuffl:text'. * @return a jQuery object representing the new card. */ shuffl.card.imagegallery.newCard = function (cardtype, cardcss, cardid, carddata) { //log.debug("shuffl.card.imagegallery.newCard: "+ // cardtype+", "+cardcss+", "+cardid+", "+carddata); // Initialize the card object var card = shuffl.card.imagegallery.blank.clone(); card.data('shuffl:type' , cardtype); card.data('shuffl:id', cardid); card.data("shuffl:tojson", shuffl.card.imagegallery.serialize); card.attr('id', cardid); card.addClass(cardcss); card.find("cident").text(cardid); // Set card id text card.find("cclass").text(cardtype); // Set card class/type text card.data("resizeAlso", "cbody"); card.resizable(); // Set up model listener and user input handlers ////shuffl.bindLineEditable(card, "shuffl:title", "ctitle"); ////shuffl.bindLineEditable(card, "shuffl:tags", "ctags"); ////var cbody = card.find("cbody"); // Initialize the model shuffl.initModel(card, carddata, shuffl.card.imagegallery.datamap, {id: cardid, tags: [cardtype]} ); return card; }; /** * Serializes a free-text card to JSON for storage * * @param card a jQuery object corresponding to the card * @return an object containing the card data */ shuffl.card.imagegallery.serialize = function (card) { return shuffl.serializeModel(card, shuffl.card.imagegallery.datamap); }; /** * Add new card type factories */ shuffl.addCardFactory("shuffl-imagegallery-yellow", "stock-yellow", shuffl.card.imagegallery.newCard); shuffl.addCardFactory("shuffl-imagegallery-blue", "stock-blue", shuffl.card.imagegallery.newCard); shuffl.addCardFactory("shuffl-imagegallery-green", "stock-green", shuffl.card.imagegallery.newCard); shuffl.addCardFactory("shuffl-imagegallery-orange", "stock-orange", shuffl.card.imagegallery.newCard); shuffl.addCardFactory("shuffl-imagegallery-pink", "stock-pink", shuffl.card.imagegallery.newCard); shuffl.addCardFactory("shuffl-imagegallery-purple", "stock-purple", shuffl.card.imagegallery.newCard); // End.
export default function toArray ( arrayLike ) { var array = [], i = arrayLike.length; while ( i-- ) { array[i] = arrayLike[i]; } return array; }
import * as tslib_1 from "tslib"; /** * @license Angular v4.3.2 * (c) 2010-2017 Google, Inc. https://angular.io/ * License: MIT */ import { AUTO_STYLE, NoopAnimationPlayer } from '@angular/animations'; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var _contains = function (elm1, elm2) { return false; }; var _matches = function (element, selector) { return false; }; var _query = function (element, selector, multi) { return []; }; if (typeof Element != 'undefined') { // this is well supported in all browsers _contains = function (elm1, elm2) { return elm1.contains(elm2); }; if (Element.prototype.matches) { _matches = function (element, selector) { return element.matches(selector); }; } else { var proto = Element.prototype; var fn_1 = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector; if (fn_1) { _matches = function (element, selector) { return fn_1.apply(element, [selector]); }; } } _query = function (element, selector, multi) { var results = []; if (multi) { results.push.apply(results, element.querySelectorAll(selector)); } else { var elm = element.querySelector(selector); if (elm) { results.push(elm); } } return results; }; } var matchesElement = _matches; var containsElement = _contains; var invokeQuery = _query; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function allowPreviousPlayerStylesMerge(duration, delay) { return duration === 0 || delay === 0; } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @experimental Animation support is experimental. */ var MockAnimationDriver = (function () { function MockAnimationDriver() { } MockAnimationDriver.prototype.matchesElement = function (element, selector) { return matchesElement(element, selector); }; MockAnimationDriver.prototype.containsElement = function (elm1, elm2) { return containsElement(elm1, elm2); }; MockAnimationDriver.prototype.query = function (element, selector, multi) { return invokeQuery(element, selector, multi); }; MockAnimationDriver.prototype.computeStyle = function (element, prop, defaultValue) { return defaultValue || ''; }; MockAnimationDriver.prototype.animate = function (element, keyframes, duration, delay, easing, previousPlayers) { if (previousPlayers === void 0) { previousPlayers = []; } var player = new MockAnimationPlayer(element, keyframes, duration, delay, easing, previousPlayers); MockAnimationDriver.log.push(player); return player; }; return MockAnimationDriver; }()); MockAnimationDriver.log = []; /** * @experimental Animation support is experimental. */ var MockAnimationPlayer = (function (_super) { tslib_1.__extends(MockAnimationPlayer, _super); function MockAnimationPlayer(element, keyframes, duration, delay, easing, previousPlayers) { var _this = _super.call(this) || this; _this.element = element; _this.keyframes = keyframes; _this.duration = duration; _this.delay = delay; _this.easing = easing; _this.previousPlayers = previousPlayers; _this.__finished = false; _this.__started = false; _this.previousStyles = {}; _this._onInitFns = []; _this.currentSnapshot = {}; if (allowPreviousPlayerStylesMerge(duration, delay)) { previousPlayers.forEach(function (player) { if (player instanceof MockAnimationPlayer) { var styles_1 = player.currentSnapshot; Object.keys(styles_1).forEach(function (prop) { return _this.previousStyles[prop] = styles_1[prop]; }); } }); } _this.totalTime = delay + duration; return _this; } /* @internal */ MockAnimationPlayer.prototype.onInit = function (fn) { this._onInitFns.push(fn); }; /* @internal */ MockAnimationPlayer.prototype.init = function () { _super.prototype.init.call(this); this._onInitFns.forEach(function (fn) { return fn(); }); this._onInitFns = []; }; MockAnimationPlayer.prototype.finish = function () { _super.prototype.finish.call(this); this.__finished = true; }; MockAnimationPlayer.prototype.destroy = function () { _super.prototype.destroy.call(this); this.__finished = true; }; /* @internal */ MockAnimationPlayer.prototype.triggerMicrotask = function () { }; MockAnimationPlayer.prototype.play = function () { _super.prototype.play.call(this); this.__started = true; }; MockAnimationPlayer.prototype.hasStarted = function () { return this.__started; }; MockAnimationPlayer.prototype.beforeDestroy = function () { var _this = this; var captures = {}; Object.keys(this.previousStyles).forEach(function (prop) { captures[prop] = _this.previousStyles[prop]; }); if (this.hasStarted()) { // when assembling the captured styles, it's important that // we build the keyframe styles in the following order: // {other styles within keyframes, ... previousStyles } this.keyframes.forEach(function (kf) { Object.keys(kf).forEach(function (prop) { if (prop != 'offset') { captures[prop] = _this.__finished ? kf[prop] : AUTO_STYLE; } }); }); } this.currentSnapshot = captures; }; return MockAnimationPlayer; }(NoopAnimationPlayer)); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @module * @description * Entry point for all public APIs of the platform-browser/animations/testing package. */ export { MockAnimationDriver, MockAnimationPlayer }; //# sourceMappingURL=testing.es5.js.map
/** * @fileoverview Disallow parenthesesisng higher precedence subexpressions. * @author Michael Ficarra * @copyright 2014 Michael Ficarra. All rights reserved. */ "use strict"; //------------------------------------------------------------------------------ // Rule Definition //------------------------------------------------------------------------------ module.exports = function(context) { function isParenthesised(node) { var previousToken = context.getTokenBefore(node), nextToken = context.getTokenAfter(node); return previousToken && nextToken && previousToken.value === "(" && previousToken.range[1] <= node.range[0] && nextToken.value === ")" && nextToken.range[0] >= node.range[1]; } function isParenthesisedTwice(node) { var previousToken = context.getTokenBefore(node, 1), nextToken = context.getTokenAfter(node, 1); return isParenthesised(node) && previousToken && nextToken && previousToken.value === "(" && previousToken.range[1] <= node.range[0] && nextToken.value === ")" && nextToken.range[0] >= node.range[1]; } function precedence(node) { switch (node.type) { case "SequenceExpression": return 0; case "AssignmentExpression": return 1; case "ConditionalExpression": return 3; case "LogicalExpression": switch (node.operator) { case "||": return 4; case "&&": return 5; // no default } /* falls through */ case "BinaryExpression": switch (node.operator) { case "|": return 6; case "^": return 7; case "&": return 8; case "==": case "!=": case "===": case "!==": return 9; case "<": case "<=": case ">": case ">=": case "in": case "instanceof": return 10; case "<<": case ">>": case ">>>": return 11; case "+": case "-": return 12; case "*": case "/": case "%": return 13; // no default } /* falls through */ case "UnaryExpression": return 14; case "UpdateExpression": return 15; case "CallExpression": // IIFE is allowed to have parens in any position (#655) if (node.callee.type === "FunctionExpression") { return -1; } return 16; case "NewExpression": return 17; // no default } return 18; } function report(node) { var previousToken = context.getTokenBefore(node); context.report(node, previousToken.loc.start, "Gratuitous parentheses around expression."); } function dryUnaryUpdate(node) { if (isParenthesised(node.argument) && precedence(node.argument) >= precedence(node)) { report(node.argument); } } function dryCallNew(node) { if (isParenthesised(node.callee) && precedence(node.callee) >= precedence(node) && !(node.type === "CallExpression" && node.callee.type === "FunctionExpression")) { report(node.callee); } if (node.arguments.length === 1) { if (isParenthesisedTwice(node.arguments[0]) && precedence(node.arguments[0]) >= precedence({type: "AssignmentExpression"})) { report(node.arguments[0]); } } else { [].forEach.call(node.arguments, function(arg) { if (isParenthesised(arg) && precedence(arg) >= precedence({type: "AssignmentExpression"})) { report(arg); } }); } } function dryBinaryLogical(node) { var prec = precedence(node); if (isParenthesised(node.left) && precedence(node.left) >= prec) { report(node.left); } if (isParenthesised(node.right) && precedence(node.right) > prec) { report(node.right); } } return { "ArrayExpression": function(node) { [].forEach.call(node.elements, function(e) { if (e && isParenthesised(e) && precedence(e) >= precedence({type: "AssignmentExpression"})) { report(e); } }); }, "AssignmentExpression": function(node) { if (isParenthesised(node.right) && precedence(node.right) >= precedence(node)) { report(node.right); } }, "BinaryExpression": dryBinaryLogical, "CallExpression": dryCallNew, "ConditionalExpression": function(node) { if (isParenthesised(node.test) && precedence(node.test) >= precedence({type: "LogicalExpression", operator: "||"})) { report(node.test); } if (isParenthesised(node.consequent) && precedence(node.consequent) >= precedence({type: "AssignmentExpression"})) { report(node.consequent); } if (isParenthesised(node.alternate) && precedence(node.alternate) >= precedence({type: "AssignmentExpression"})) { report(node.alternate); } }, "DoWhileStatement": function(node) { if (isParenthesisedTwice(node.test)) { report(node.test); } }, "ExpressionStatement": function(node) { var firstToken; if (isParenthesised(node.expression)) { firstToken = context.getFirstToken(node.expression); if (firstToken.value !== "function" && firstToken.value !== "{") { report(node.expression); } } }, "ForInStatement": function(node) { if (isParenthesised(node.right)) { report(node.right); } }, "ForOfStatement": function(node) { if (isParenthesised(node.right)) { report(node.right); } }, "ForStatement": function(node) { if (node.init && isParenthesised(node.init)) { report(node.init); } if (node.test && isParenthesised(node.test)) { report(node.test); } if (node.update && isParenthesised(node.update)) { report(node.update); } }, "IfStatement": function(node) { if (isParenthesisedTwice(node.test)) { report(node.test); } }, "LogicalExpression": dryBinaryLogical, "MemberExpression": function(node) { if ( isParenthesised(node.object) && precedence(node.object) >= precedence(node) && ( node.computed || !( (node.object.type === "Literal" && typeof node.object.value === "number" && /^[0-9]+$/.test(context.getFirstToken(node.object).value)) || // RegExp literal is allowed to have parens (#1589) (node.object.type === "Literal" && node.object.regex) ) ) ) { report(node.object); } }, "NewExpression": dryCallNew, "ObjectExpression": function(node) { [].forEach.call(node.properties, function(e) { var v = e.value; if (v && isParenthesised(v) && precedence(v) >= precedence({type: "AssignmentExpression"})) { report(v); } }); }, "ReturnStatement": function(node) { if (node.argument && isParenthesised(node.argument) && // RegExp literal is allowed to have parens (#1589) !(node.argument.type === "Literal" && node.argument.regex)) { report(node.argument); } }, "SequenceExpression": function(node) { [].forEach.call(node.expressions, function(e) { if (isParenthesised(e) && precedence(e) >= precedence(node)) { report(e); } }); }, "SwitchCase": function(node) { if (node.test && isParenthesised(node.test)) { report(node.test); } }, "SwitchStatement": function(node) { if (isParenthesisedTwice(node.discriminant)) { report(node.discriminant); } }, "ThrowStatement": function(node) { if (isParenthesised(node.argument)) { report(node.argument); } }, "UnaryExpression": dryUnaryUpdate, "UpdateExpression": dryUnaryUpdate, "VariableDeclarator": function(node) { if (node.init && isParenthesised(node.init) && precedence(node.init) >= precedence({type: "AssignmentExpression"}) && // RegExp literal is allowed to have parens (#1589) !(node.init.type === "Literal" && node.init.regex)) { report(node.init); } }, "WhileStatement": function(node) { if (isParenthesisedTwice(node.test)) { report(node.test); } }, "WithStatement": function(node) { if (isParenthesisedTwice(node.object)) { report(node.object); } } }; };
/*! * Bootstrap-select v1.12.4 (https://silviomoreto.github.io/bootstrap-select) * * Copyright 2013-2018 bootstrap-select * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) */ !function(e,t){"function"==typeof define&&define.amd?define(["jquery"],function(e){return t(e)}):"object"==typeof module&&module.exports?module.exports=t(require("jquery")):t(e.jQuery)}(this,function(e){e.fn.selectpicker.defaults={noneSelectedText:"Inget valt",noneResultsText:"Inget sökresultat matchar {0}",countSelectedText:function(e,t){return 1===e?"{0} alternativ valt":"{0} alternativ valda"},maxOptionsText:function(e,t){return["Gräns uppnåd (max {n} alternativ)","Gräns uppnåd (max {n} gruppalternativ)"]},selectAllText:"Markera alla",deselectAllText:"Avmarkera alla",multipleSeparator:", "}});
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M22 6h-3v9H6v3h12l4 4V6zm-5 7V2H2v15l4-4h11z" }), 'ForumSharp');
(function(){ var opts={"version":1,"apiEndpoint":"https://api.trello.com","authEndpoint":"https://trello.com","key":"ceae40df964ba24f0facf988498e2bd2"}; var deferred,isFunction,isReady,ready,waitUntil,wrapper,__slice=[].slice; wrapper=function(c,g,b){var f,d,l,w,y,m,r,n,z,x,e,s,t,u,h,v,p;m=b.key;e=b.token;d=b.apiEndpoint;l=b.authEndpoint;s=b.version;y=""+d+"/"+s+"/";n=c.location;f={version:function(){return s},key:function(){return m},setKey:function(a){m=a},token:function(){return e},setToken:function(a){e=a},rest:function(){var a,c,d,k;c=arguments[0];a=2<=arguments.length?__slice.call(arguments,1):[];k=z(a);d=k[0];a=k[1];b={url:""+y+d,type:c,data:{},dataType:"json",success:k[2],error:k[3]};g.support.cors||(b.dataType= "jsonp","GET"!==c&&(b.type="GET",g.extend(b.data,{_method:c})));m&&(b.data.key=m);e&&(b.data.token=e);null!=a&&g.extend(b.data,a);return g.ajax(b)},authorized:function(){return null!=e},deauthorize:function(){e=null;t("token",e)},authorize:function(a){var q,d,k,f,h;b=g.extend(!0,{type:"redirect",persist:!0,interactive:!0,scope:{read:!0,write:!1,account:!1},expiration:"30days"},a);a=/[&#]?token=([0-9a-f]{64})/;d=function(){if(b.persist&&null!=e)return t("token",e)};b.persist&&null==e&&(e=x("token")); null==e&&(e=null!=(h=a.exec(n.hash))?h[1]:void 0);if(this.authorized())return d(),n.hash=n.hash.replace(a,""),"function"===typeof b.success?b.success():void 0;if(!b.interactive)return"function"===typeof b.error?b.error():void 0;k=function(){var a,c;a=b.scope;c=[];for(q in a)(f=a[q])&&c.push(q);return c}().join(",");switch(b.type){case "popup":(function(){var a,q,e,f;waitUntil("authorized",function(a){return function(a){return a?(d(),"function"===typeof b.success?b.success():void 0):"function"===typeof b.error? b.error():void 0}}(this));a=c.screenX+(c.innerWidth-420)/2;e=c.screenY+(c.innerHeight-470)/2;q=null!=(f=/^[a-z]+:\/\/[^\/]*/.exec(n))?f[0]:void 0;return c.open(w({return_url:q,callback_method:"postMessage",scope:k,expiration:b.expiration,name:b.name}),"trello","width=420,height=470,left="+a+",top="+e)})();break;default:c.location=w({redirect_uri:n.href,callback_method:"fragment",scope:k,expiration:b.expiration,name:b.name})}}};p=["GET","PUT","POST","DELETE"];u=function(a){return f[a.toLowerCase()]= function(){return this.rest.apply(this,[a].concat(__slice.call(arguments)))}};h=0;for(v=p.length;h<v;h++)d=p[h],u(d);f.del=f["delete"];p="actions cards checklists boards lists members organizations lists".split(" ");u=function(a){return f[a]={get:function(b,c,d,e){return f.get(""+a+"/"+b,c,d,e)}}};h=0;for(v=p.length;h<v;h++)d=p[h],u(d);c.Trello=f;w=function(a){return l+"/"+s+"/authorize?"+g.param(g.extend({response_type:"token",key:m},a))};z=function(a){var b,c,d;c=a[0];b=a[1];d=a[2];a=a[3];isFunction(b)&& (a=d,d=b,b={});c=c.replace(/^\/*/,"");return[c,b,d,a]};d=function(a){var b;a.origin===l&&(null!=(b=a.source)&&b.close(),e=null!=a.data&&4<a.data.length?a.data:null,isReady("authorized",f.authorized()))};r=c.localStorage;null!=r?(x=function(a){return r["trello_"+a]},t=function(a,b){return null===b?delete r["trello_"+a]:r["trello_"+a]=b}):x=t=function(){};"function"===typeof c.addEventListener&&c.addEventListener("message",d,!1)};deferred={};ready={}; waitUntil=function(c,g){return null!=ready[c]?g(ready[c]):(null!=deferred[c]?deferred[c]:deferred[c]=[]).push(g)};isReady=function(c,g){var b,f,d,l;ready[c]=g;if(deferred[c]){f=deferred[c];delete deferred[c];d=0;for(l=f.length;d<l;d++)b=f[d],b(g)}};isFunction=function(c){return"function"===typeof c};wrapper(window,jQuery,opts); })()
/** * Extension: Event */ export default class EventEmitter { constructor() { this._events = {}; } /** * Attach a handler to an custom event. * * @param {string} type * @param {Function} callback * @returns {Event} this */ on(type, callback) { if (type && callback) { this._events[type] = this._events[type] || []; this._events[type].push({ type, callback }); } return this; } /** * Remove a previously-attached custom event handler. * * @param {string} type * @param {Function} callback * @returns {Event} this */ off(type, callback) { if (this._events[type]) { this._events[type] = this._events[type].filter((item) => { return callback !== item.callback; }); } return this; } /** * Execute all handlers for the given event type. * * @param {string} type * @param {*} [data] * @returns {Event} this */ trigger(type, data) { if (this._events[type]) { this._events[type].forEach((item) => { if (type === item.type) { item.callback.call(this, {type: type}, data); } }); } return this; } }
/* jshint node:true */ var RSVP = require('rsvp'); var fs = require('fs'); var path = require('path'); module.exports = { strategy: { availableOptions: [ { name: 'foo', type: String, }, ], getNextTag: function(project, tags, options) { writeFile(project.root, 'options.json', JSON.stringify(options)); return 'foo'; } } }; function writeFile(rootPath, filePath, contents) { fs.writeFileSync(path.join(rootPath, filePath), contents); }
/* eslint-disable global-require */ const express = require('express'); const path = require('path'); const compression = require('compression'); const pkg = require(path.resolve(process.cwd(), 'package.json')); const proxy = require('http-proxy-middleware'); // Dev middleware const addDevMiddlewares = (app, webpackConfig) => { const webpack = require('webpack'); const webpackDevMiddleware = require('webpack-dev-middleware'); const webpackHotMiddleware = require('webpack-hot-middleware'); const compiler = webpack(webpackConfig); const middleware = webpackDevMiddleware(compiler, { noInfo: true, publicPath: webpackConfig.output.publicPath, silent: true, stats: 'errors-only', }); const apiProxy = proxy('/api', { target: 'http://localhost:8080' }); app.use(apiProxy); app.use(middleware); app.use(webpackHotMiddleware(compiler)); // Since webpackDevMiddleware uses memory-fs internally to store build // artifacts, we use it instead const fs = middleware.fileSystem; if (pkg.dllPlugin) { app.get(/\.dll\.js$/, (req, res) => { const filename = req.path.replace(/^\//, ''); res.sendFile(path.join(process.cwd(), pkg.dllPlugin.path, filename)); }); } app.get('*', (req, res) => { fs.readFile(path.join(compiler.outputPath, 'index.html'), (err, file) => { if (err) { res.sendStatus(404); } else { res.send(file.toString()); } }); }); }; // Production middlewares const addProdMiddlewares = (app, options) => { const publicPath = options.publicPath || '/'; const outputPath = options.outputPath || path.resolve(process.cwd(), 'build'); // compression middleware compresses your server responses which makes them // smaller (applies also to assets). You can read more about that technique // and other good practices on official Express.js docs http://mxs.is/googmy app.use(compression()); app.use(publicPath, express.static(outputPath)); app.get('*', (req, res) => res.sendFile(path.resolve(outputPath, 'index.html'))); }; /** * Front-end middleware */ module.exports = (app, options) => { const isProd = process.env.NODE_ENV === 'production'; if (isProd) { addProdMiddlewares(app, options); } else { const webpackConfig = require('../../internals/webpack/webpack.dev.babel'); addDevMiddlewares(app, webpackConfig); } return app; };
/*! jQuery UI - v1.9.2 - 2015-02-01 * http://jqueryui.com * Copyright 2015 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional.ro={closeText:"Închide",prevText:"&#xAB; Luna precedentă",nextText:"Luna următoare &#xBB;",currentText:"Azi",monthNames:["Ianuarie","Februarie","Martie","Aprilie","Mai","Iunie","Iulie","August","Septembrie","Octombrie","Noiembrie","Decembrie"],monthNamesShort:["Ian","Feb","Mar","Apr","Mai","Iun","Iul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Duminică","Luni","Marţi","Miercuri","Joi","Vineri","Sâmbătă"],dayNamesShort:["Dum","Lun","Mar","Mie","Joi","Vin","Sâm"],dayNamesMin:["Du","Lu","Ma","Mi","Jo","Vi","Sâ"],weekHeader:"Săpt",dateFormat:"dd.mm.yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional.ro)});
define(["require", "exports", 'Services/Service', 'Site'], function (require, exports, services, site) { var HomeService = (function () { function HomeService() { } HomeService.prototype.getMenus = function () { /// <summary> /// 获取系统设置的菜单 /// </summary> var result = services.callMethod(services.config.siteServiceUrl, 'UI/GetMenus'); return result; }; HomeService.prototype.advertItems = function () { var result = services.callMethod(services.config.siteServiceUrl, 'Home/GetAdvertItems'); return result; }; HomeService.prototype.homeProducts = function (pageIndex) { var result = services.callMethod(services.config.siteServiceUrl, 'Home/GetHomeProducts', { pageIndex: pageIndex }); result.then(function (data) { if (data.length < site.config.pageSize) result['loadCompleted'] = true; return data; }); return result; }; HomeService.prototype.getBrands = function (args) { var result = services.callRemoteMethod('Product/GetBrands', args); return result; }; return HomeService; })(); window['services']['home'] = window['services']['home'] || new HomeService(); return window['services']['home']; });
define([ 'jquery', 'calendarData' ], function($, data){ var DSGCalendar = { options: { container: 'calendar-container', }, data: {}, activeSlot: {}, isActive: false, initialize: function(dataPath){ var that = this; // Testing - the module accepts pre-loaded data. In production, this would load the data via ajax. this.data = data; this.render(); //this.loadData(dataPath); $('.dup').on('click', function(e){ e.preventDefault(); that.duplicateLast(); }); $('.calendar-container').on('click', '.slot p' ,function(e){ e.stopPropagation(); if(!that.isActive){ that.activeSlot = $(this).parent(); that.activateSlot(); } else { if($(this).parent() != that.activeSlot){ // Out with the old that.deactivateSlot(); // In with the new that.activeSlot = $(this).parent(); that.activateSlot(); } } }); // Press the enter key $(document).keypress(function(e) { if(e.which == 13) { if(that.isActive) that.deactivateSlot(); } }); //$('.ticker').addClass('vertical-collapse'); }, loadData: function(dataPath){ var that = this; $.getJSON(dataPath, function(data){ that.data = data; that.render(); }); }, render: function(){ this.renderKey(this.data.days[0]); for(day in this.data.days){ this.renderDay(this.data.days[day]); } }, renderKey: function(day){ var dayElem = $('<div class="day key"><p class="header-block">&nbsp;</p><p class="header-block">&nbsp;</p></div>'); for(g in day.slotgroups){ var groupObj = day.slotgroups[g], groupElem = $('<div class="group ' + groupObj.name.toLowerCase().replace(/ /g, '') + ' cf"><p class="group-name">' + groupObj.name + '</p></div>'), groupKeyElem = $('<div class="key-group"></div>'); for (i in groupObj.items){ var itemObj = groupObj.items[i], itemElem = $('<div class="slot"><div class="box"><p>' + itemObj.slot +'</p></div></div>'); groupKeyElem.append(itemElem); } groupElem.append(groupKeyElem); dayElem.append(groupElem); } $('.' + this.options.container + ' .dup').before(dayElem); }, renderDay: function(day){ var dayElem = $('<div class="day"><p class="header-block">'+ day.name+'</p><p class="header-block">'+ day.date+'</p></div>'); for(g in day.slotgroups){ var groupObj = day.slotgroups[g], groupElem = $('<div class="group ' + groupObj.name.toLowerCase().replace(/ /g, '') + '"></div>'); for (i in groupObj.items){ var itemObj = groupObj.items[i], itemElem; if(itemObj.value == ''){ itemObj.value = '&nbsp;'; } itemElem = $('<div class="slot"><div class="box"><p>' + itemObj.value +'</p></div></div>'); groupElem.append(itemElem); } dayElem.append(groupElem); } $('.' + this.options.container + ' .dup').before(dayElem); }, duplicateLast: function(){ $('.calendar-container .dup').before($('.day:last').clone()); }, activateSlot: function(){ var that = this, slotElem = $(this.activeSlot), pel = slotElem.find('p'), iel = $('<input id="textEdit" />'); that.isActive = true; // Set the text value of the input iel.attr('value', pel.text()); iel.on('blur', function(){ that.deactivateSlot(); }); // Hide the P tag pel.addClass('hide'); slotElem.append(iel); iel.focus(); }, deactivateSlot: function(){ var slotElem = this.activeSlot, pel = slotElem.find('p'), iel = slotElem.find('input'); this.isActive = false; // Check the value for CHANGED if(iel.val() != pel.text()){ slotElem.addClass('change'); pel.text(iel.val()); } // Flip the display black pel.removeClass('hide'); slotElem.find('input').remove() } } return DSGCalendar; });
const express = require('express'); const values = require('object.values'); const environmentConstants = require('./constants/environment'); if (!Object.values) { values.shim(); } const environment = process.env.NODE_ENV || environmentConstants.DEVELOPMENT; process.env.NODE_ENV = environment; require('dotenv').config({ silent: true }); const app = express(); const config = require('./config'); require('./config/express')({ app, environment }); require('./routes')({ app, express, config, environment }); app.listen(config.port, () => { console.log(`Server running on port ${config.port}`); // eslint-disable-line no-console });
(function(abot) { abot.Settings = {} abot.Settings.controller = function() { var ctrl = this ctrl.save = function() { var changed = document.querySelectorAll(".input-changed") if (changed.length === 0) { return } var data = {} var ps = ctrl.props.plugins() for (var i = 0; i < ps.length; ++i) { var p = ps[i] if (p.Settings == null) { continue } data[p.Name] = {} Object.keys(p.Settings).map(function(settingName) { data[p.Name][settingName] = p.Settings[settingName] || "" }) } abot.request({ url: "/api/admin/settings.json", method: "PUT", data: data, }).then(function(resp) { ctrl.props.error("") ctrl.props.success("Success! Saved changes.") for (var i = 0; i < changed.length; ++i) { changed[i].classList.remove("input-changed") } }, function(err) { ctrl.props.success("") ctrl.props.error(err.Msg) }) } ctrl.markChanged = function(val) { this.classList.add("input-changed") var pluginIdx = this.getAttribute("data-plugin-idx") var setting = this.getAttribute("data-setting") ctrl.props.plugins()[pluginIdx].Settings[setting] = val } ctrl.discard = function() { if (document.querySelector(".input-changed") == null) { return } if (confirm("Are you sure you want to discard your changes?")) { m.route(window.location.pathname, null, true) } } ctrl.props = { plugins: m.prop([]), error: m.prop(""), success: m.prop(""), } abot.Plugins.fetch().then(function(resp) { ctrl.props.plugins(resp || []) }, function(err) { ctrl.props.error(err.Msg) }) } abot.Settings.view = function(ctrl) { return m(".body", [ m.component(abot.Header), m(".container", [ m.component(abot.Sidebar, { active: 5 }), m(".main", [ m(".topbar", "Settings"), m(".content", [ function() { if (ctrl.props.error().length > 0) { return m(".alert.alert-danger.alert-margin", ctrl.props.error()) } if (ctrl.props.success().length > 0) { return m(".alert.alert-success.alert-margin", ctrl.props.success()) } }(), function() { if (ctrl.props.plugins().length === 0) { return m("p.top-el", "No plugins installed.") } return ctrl.props.plugins().map(function(plugin, i) { var title if (i === 0) { title = m("h3.top-el", plugin.Name) } else { title = m("h3", plugin.Name) } var keys = Object.keys(plugin.Settings) if (keys.length === 0) { return [ title, m("div", "No editable settings."), ] } var ss = [] keys.map(function(setting) { ss.push(m("tr", [ m("td", [ m("label", setting), ]), m("td", [ m("input[type=text]", { oninput: m.withAttr("value", ctrl.markChanged), "data-plugin-idx": i, "data-setting": setting, value: plugin.Settings[setting], }), ]), ])) }) return m("form.form-align", [ title, m("table", [ ss ]), m("#btns.btn-container-left", [ m("input[type=button].btn", { onclick: ctrl.discard, value: "Discard Changes", }), m("input[type=button].btn.btn-primary", { onclick: ctrl.save, value: "Save", }), ]), ]) }) }(), ]), ]), ]), ]) } })(!window.abot ? window.abot={} : window.abot);
const fs = require('fs'); const path = require('path'); const fetch = require('node-fetch'); const outDir = __dirname; var includeList = [ "1016", // 4UMaps "1065", // Hike & Bike Map "1061", // Thunderforest Outdoors "1021", // kosmosnimki.ru "1017", // sputnik.ru "1023", // Osmapa.pl - Mapa OpenStreetMap Polska "1010", // OpenStreetMap.se (Hydda.Full) "1069", // MRI (maps.refuges.info), "1059" // ÖPNV Karte ]; function extract(constantsJs) { eval(constantsJs); for (let i = 0; i < includeList.length; i++) { let id = includeList[i]; let layer = getLayerDataByID(id); if (!layer) { console.warn('Layer not found: ' + id); continue; } //console.log(`${layer.id}, ${layer.name}, ${layer.address}`); layer.url = layer.address; delete layer.address; let geoJson = { geometry: null, properties: layer, type: "Feature" }; geoJson.properties.dataSource = 'LayersCollection'; const outFileName = path.join(outDir, layer.id + '.geojson'); const data = JSON.stringify(geoJson, null, 2); fs.writeFileSync(outFileName, data); } } // https://github.com/Edward17/LayersCollection/blob/gh-pages/constants.js fetch('http://edward17.github.io/LayersCollection/constants.js') .then(res => res.text()) .then(text => extract(text)) .catch(err => console.error(err));
var studentIdSequence = 10023; var gridOptions = { columnDefs: [ {headerName: 'Student ID', field: 'student'}, {headerName: 'Year Group', field: 'yearGroup', rowGroup: true}, {headerName: 'Age', field: 'age'}, {headerName: 'Course', field: 'course', pivot: true}, {headerName: 'Age Range', field: 'ageRange', valueGetter: ageRangeValueGetter, pivot: true}, {headerName: 'Points', field: 'points', aggFunc: 'sum'} ], defaultColDef: { flex: 1, minWidth: 150, sortable: true, resizable: true, cellRenderer:'agAnimateShowChangeCellRenderer', }, rowData: getRowData(), pivotMode: true, groupDefaultExpanded: 1, // enableCellChangeFlash: true, animateRows: true, getRowNodeId: function(data) { return data.student; }, onGridReady:function(params) { document.getElementById('pivot-mode').checked = true; } }; function ageRangeValueGetter(params) { var age = params.getValue('age'); if (age === undefined) { return null; } if (age < 20) { return '< 20'; } else if (age > 30) { return '> 30'; } else { return '20 to 30'; } } // pretty basic, but deterministic (so same numbers each time we run), random number generator var seed; function random() { seed = ((seed || 1) * 16807) % 2147483647; return seed; } function getRowData() { var rowData = []; for (var i = 1; i <= 100; i++) { var row = createRow(); rowData.push(row); } return rowData; } function createRow() { var randomNumber = random(); var result = { student: studentIdSequence++, points: randomNumber % 60 + 40, course: ['Science', 'History'][randomNumber % 3 === 0 ? 0 : 1], yearGroup: 'Year ' + (randomNumber % 4 + 1), // 'Year 1' to 'Year 4' age: randomNumber % 25 + 15 // 15 to 40 }; return result; } function pivotMode() { var pivotModeOn = document.getElementById('pivot-mode').checked; gridOptions.columnApi.setPivotMode(pivotModeOn); gridOptions.columnApi.applyColumnState({ state: [ {colId: 'yearGroup', rowGroup: pivotModeOn}, {colId: 'course', pivot: pivotModeOn}, {colId: 'ageRange', pivot: pivotModeOn} ] }); } function updateOneRecord() { var rowNodeToUpdate = pickExistingRowNodeAtRandom(gridOptions.api); var randomValue = createNewRandomScore(rowNodeToUpdate.data); console.log('updating points to ' + randomValue + ' on ', rowNodeToUpdate.data); rowNodeToUpdate.setDataValue('points', randomValue); } function createNewRandomScore(data) { var randomValue = createRandomNumber(); // make sure random number is not actually the same number again while (randomValue === data.points) { randomValue = createRandomNumber(); } return randomValue; } function createRandomNumber() { return Math.floor(Math.random() * 100); } function pickExistingRowNodeAtRandom(gridApi) { var allItems = []; gridApi.forEachLeafNode(function(rowNode) { allItems.push(rowNode); }); if (allItems.length === 0) { return; } var result = allItems[Math.floor(Math.random() * allItems.length)]; return result; } function pickExistingRowItemAtRandom(gridApi) { var rowNode = pickExistingRowNodeAtRandom(gridApi); return rowNode ? rowNode.data : null; } function updateUsingTransaction() { var itemToUpdate = pickExistingRowItemAtRandom(gridOptions.api); if (!itemToUpdate) { return; } console.log('updating - before', itemToUpdate); itemToUpdate.points = createRandomNumber(itemToUpdate); var transaction = { update: [itemToUpdate] }; console.log('updating - after', itemToUpdate); gridOptions.api.applyTransaction(transaction); } function addNewGroupUsingTransaction() { var item1 = createRow(); var item2 = createRow(); item1.yearGroup = 'Year 5'; item2.yearGroup = 'Year 5'; var transaction = { add: [item1, item2] }; console.log('add - ', item1); console.log('add - ', item2); gridOptions.api.applyTransaction(transaction); } function addNewCourse() { var item1 = createRow(); item1.course = 'Physics'; var transaction = { add: [item1] }; console.log('add - ', item1); gridOptions.api.applyTransaction(transaction); } function removePhysics() { var allPhysics = []; gridOptions.api.forEachLeafNode(function(rowNode) { if (rowNode.data.course === 'Physics') { allPhysics.push(rowNode.data); } }); var transaction = { remove: allPhysics }; console.log('removing ' + allPhysics.length + ' physics items.'); gridOptions.api.applyTransaction(transaction); } function moveCourse() { var item = pickExistingRowItemAtRandom(gridOptions.api); if (!item) { return; } item.course = item.course === 'History' ? 'Science' : 'History'; var transaction = { update: [item] }; console.log('moving ' + item); gridOptions.api.applyTransaction(transaction); } // setup the grid after the page has finished loading document.addEventListener('DOMContentLoaded', function() { var gridDiv = document.querySelector('#myGrid'); new agGrid.Grid(gridDiv, gridOptions); });
// Generated by CoffeeScript 1.9.3 (function() { var Adapter, Eco, W, fs, path, extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, hasProp = {}.hasOwnProperty; Adapter = require('../adapter_base'); path = require('path'); fs = require('fs'); W = require('when'); Eco = (function(superClass) { var compile; extend(Eco, superClass); function Eco() { return Eco.__super__.constructor.apply(this, arguments); } Eco.prototype.name = 'eco'; Eco.prototype.extensions = ['eco']; Eco.prototype.output = 'html'; Eco.prototype._render = function(str, options) { return compile((function(_this) { return function() { return _this.engine.render(str, options); }; })(this)); }; Eco.prototype._compile = function(str, options) { return compile((function(_this) { return function() { return _this.engine.compile(str, options); }; })(this)); }; Eco.prototype._compileClient = function(str, options) { return compile((function(_this) { return function() { return _this.engine.compile(str, options).toString().trim() + '\n'; }; })(this)); }; compile = function(fn) { var err, res; try { res = fn(); } catch (_error) { err = _error; return W.reject(err); } return W.resolve({ result: res }); }; return Eco; })(Adapter); module.exports = Eco; }).call(this);
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2020 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * Renders this Game Object with the Canvas Renderer to the given Camera. * The object will not render if any of its renderFlags are set or it is being actively filtered out by the Camera. * This method should not be called directly. It is a utility function of the Render module. * * @method Phaser.GameObjects.Sprite#renderCanvas * @since 3.0.0 * @private * * @param {Phaser.Renderer.Canvas.CanvasRenderer} renderer - A reference to the current active Canvas renderer. * @param {Phaser.GameObjects.Sprite} src - The Game Object being rendered in this call. * @param {number} interpolationPercentage - Reserved for future use and custom pipelines. * @param {Phaser.Cameras.Scene2D.Camera} camera - The Camera that is rendering the Game Object. * @param {Phaser.GameObjects.Components.TransformMatrix} parentMatrix - This transform matrix is defined if the game object is nested */ var SpriteCanvasRenderer = function (renderer, src, interpolationPercentage, camera, parentMatrix) { renderer.batchSprite(src, src.frame, camera, parentMatrix); }; module.exports = SpriteCanvasRenderer;
/** @jsx h */ import h from '../../../helpers/h' export default function (change) { change.deleteBackward() } export const input = ( <state> <document> <paragraph> wo<cursor />rd </paragraph> </document> </state> ) export const output = ( <state> <document> <paragraph> w<cursor />rd </paragraph> </document> </state> )
var f = require('util').format , MongoError = require('../error'); // Filters for classes var classFilters = {}; var filteredClasses = {}; var level = null; // Save the process id var pid = process.pid; // current logger var currentLogger = null; /** * Creates a new Logger instance * @class * @param {string} className The Class name associated with the logging instance * @param {object} [options=null] Optional settings. * @param {Function} [options.logger=null] Custom logger function; * @param {string} [options.loggerLevel=error] Override default global log level. * @return {Logger} a Logger instance. */ var Logger = function(className, options) { if(!(this instanceof Logger)) return new Logger(className, options); options = options || {}; // Current reference var self = this; this.className = className; // Current logger if(currentLogger == null && options.logger) { currentLogger = options.logger; } else if(currentLogger == null) { currentLogger = console.log; } // Set level of logging, default is error if(level == null) { level = options.loggerLevel || 'error'; } // Add all class names if(filteredClasses[this.className] == null) classFilters[this.className] = true; } /** * Log a message at the debug level * @method * @param {string} message The message to log * @param {object} object additional meta data to log * @return {null} */ Logger.prototype.debug = function(message, object) { if(this.isDebug() && classFilters[this.className] && (filteredClasses[this.className] || Object.keys(filteredClasses).length == 0)) { var dateTime = new Date().getTime(); var msg = f("[%s-%s:%s] %s %s", 'DEBUG', this.className, pid, dateTime, message); var state = { type: 'debug', message: message, className: this.className, pid: pid, date: dateTime }; if(object) state.meta = object; currentLogger(msg, state); } } /** * Log a message at the info level * @method * @param {string} message The message to log * @param {object} object additional meta data to log * @return {null} */ Logger.prototype.info = function(message, object) { if(this.isInfo() && classFilters[this.className] && (filteredClasses[this.className] || Object.keys(filteredClasses).length == 0)) { var dateTime = new Date().getTime(); var msg = f("[%s-%s:%s] %s %s", 'INFO', this.className, pid, dateTime, message); var state = { type: 'info', message: message, className: this.className, pid: pid, date: dateTime }; if(object) state.meta = object; currentLogger(msg, state); } }, /** * Log a message at the error level * @method * @param {string} message The message to log * @param {object} object additional meta data to log * @return {null} */ Logger.prototype.error = function(message, object) { if(this.isError() && classFilters[this.className] && (filteredClasses[this.className] || Object.keys(filteredClasses).length == 0)) { var dateTime = new Date().getTime(); var msg = f("[%s-%s:%s] %s %s", 'ERROR', this.className, pid, dateTime, message); var state = { type: 'error', message: message, className: this.className, pid: pid, date: dateTime }; if(object) state.meta = object; currentLogger(msg, state); } }, /** * Is the logger set at info level * @method * @return {boolean} */ Logger.prototype.isInfo = function() { return level == 'info' || level == 'debug'; }, /** * Is the logger set at error level * @method * @return {boolean} */ Logger.prototype.isError = function() { return level == 'error' || level == 'info' || level == 'debug'; }, /** * Is the logger set at debug level * @method * @return {boolean} */ Logger.prototype.isDebug = function() { return level == 'debug'; } /** * Resets the logger to default settings, error and no filtered classes * @method * @return {null} */ Logger.reset = function() { level = 'error'; filteredClasses = {}; } /** * Get the current logger function * @method * @return {function} */ Logger.currentLogger = function() { return currentLogger; } /** * Set the current logger function * @method * @param {function} logger Logger function. * @return {null} */ Logger.setCurrentLogger = function(logger) { if(typeof logger != 'function') throw new MongoError("current logger must be a function"); currentLogger = logger; } /** * Set what classes to log. * @method * @param {string} type The type of filter (currently only class) * @param {string[]} values The filters to apply * @return {null} */ Logger.filter = function(type, values) { if(type == 'class' && Array.isArray(values)) { filteredClasses = {}; values.forEach(function(x) { filteredClasses[x] = true; }); } } /** * Set the current log level * @method * @param {string} level Set current log level (debug, info, error) * @return {null} */ Logger.setLevel = function(_level) { if(_level != 'info' && _level != 'error' && _level != 'debug') throw new Error(f("%s is an illegal logging level", _level)); level = _level; } module.exports = Logger;
/** * @author Richard Davey <rich@photonstorm.com> * @copyright 2022 Photon Storm Ltd. * @license {@link https://opensource.org/licenses/MIT|MIT License} */ /** * Returns the center x coordinate from the bounds of the Game Object. * * @function Phaser.Display.Bounds.GetCenterX * @since 3.0.0 * * @param {Phaser.GameObjects.GameObject} gameObject - The Game Object to get the bounds value from. * * @return {number} The center x coordinate of the bounds of the Game Object. */ var GetCenterX = function (gameObject) { return gameObject.x - (gameObject.width * gameObject.originX) + (gameObject.width * 0.5); }; module.exports = GetCenterX;
var gulp = require('gulp'); gulp.task('dotfiles:sync', function() { var request = require('request'); var fs = require('fs'); var _ = require('lodash'); var settings = require('../config').dotfiles.src; _.each(settings, function(setting) { request({uri: setting.url, strictSSL: false}) .pipe(fs.createWriteStream(setting.dest)); }); });
import sharp from 'sharp' import request from 'request' import B64 from 'b64' import getStream from 'get-stream' const img2Buffer = (url) => { // resize to ipad size. const transformImg = sharp() .resize(2048, 2048) .jpeg({quality: 80}) const stream = request .get(url) .pipe(transformImg) return getStream.buffer(stream) } const buffer2Img = (buffer, {width, height, greyscale}) => { if (!buffer) { return null } let stream = sharp(buffer) const encoder = new B64.Encoder() if (width && height) { stream = stream.resize(width, height) } if (greyscale) { stream = stream.greyscale() } stream = stream.pipe(encoder) return getStream(stream) .then(base64Data => `data:image/jpeg;base64,${base64Data}`) } export { img2Buffer, buffer2Img }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Jetpack. * * The Initial Developer of the Original Code is Mozilla * Portions created by the Initial Developer are Copyright (C) 2010 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Irakli Gozalishvili <gozala@mozilla.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ "use strict"; const { compose: _compose, override: _override, resolve: _resolve, trait: _trait, //create: _create, required, } = require('./traits/core'); const defineProperties = Object.defineProperties, freeze = Object.freeze, create = Object.create; /** * Work around bug 608959 by defining the _create function here instead of * importing it from traits/core. For docs on this function, see the create * function in that module. * * FIXME: remove this workaround in favor of importing the function once that * bug has been fixed. */ function _create(proto, trait) { let properties = {}, keys = Object.getOwnPropertyNames(trait); for each(let key in keys) { let descriptor = trait[key]; if (descriptor.required && !Object.prototype.hasOwnProperty.call(proto, key)) throw new Error('Missing required property: ' + key); else if (descriptor.conflict) throw new Error('Remaining conflicting property: ' + key); else properties[key] = descriptor; } return Object.create(proto, properties); } /** * Placeholder for `Trait.prototype` */ let TraitProto = Object.prototype; function Get(key) this[key] function Set(key, value) this[key] = value /** * Creates anonymous trait descriptor from the passed argument, unless argument * is a trait constructor. In later case trait's already existing properties * descriptor is returned. * This is module's internal function and is used as a gateway to a trait's * internal properties descriptor. * @param {Function} $ * Composed trait's constructor. * @returns {Object} * Private trait property of the composition. */ function TraitDescriptor(object) ( 'function' == typeof object && (object.prototype == TraitProto || object.prototype instanceof Trait) ) ? object._trait(TraitDescriptor) : _trait(object) function Public(instance, trait) { let result = {}, keys = Object.getOwnPropertyNames(trait); for each (let key in keys) { if ('_' === key.charAt(0) && '__iterator__' !== key ) continue; let property = trait[key], descriptor = { configurable: property.configurable, enumerable: property.enumerable }; if (property.get) descriptor.get = property.get.bind(instance); if (property.set) descriptor.set = property.set.bind(instance); if ('value' in property) { let value = property.value; if ('function' === typeof value) { descriptor.value = property.value.bind(instance); descriptor.writable = property.writable; } else { descriptor.get = Get.bind(instance, key); descriptor.set = Set.bind(instance, key); } } result[key] = descriptor; } return result; } /** * This is private function that composes new trait with privates. */ function Composition(trait) { function Trait() { let self = _create({}, trait); self._public = create(Trait.prototype, Public(self, trait)); delete self._public.constructor; if (Object === self.constructor) self.constructor = Trait; else return self.constructor.apply(self, arguments) || self._public; return self._public; } defineProperties(Trait, { prototype: { value: freeze(create(TraitProto, { constructor: { value: constructor, writable: true } }))}, // writable is `true` to avoid getters in custom ES5 displayName: { value: (trait.constructor || constructor).name }, compose: { value: compose, enumerable: true }, override: { value: override, enumerable: true }, resolve: { value: resolve, enumerable: true }, required: { value: required, enumerable: true }, _trait: { value: function _trait(caller) caller === TraitDescriptor ? trait : undefined } }); return freeze(Trait); } /** * Composes new trait out of itself and traits / property maps passed as an * arguments. If two or more traits / property maps have properties with the * same name, the new trait will contain a "conflict" property for that name. * This is a commutative and associative operation, and the order of its * arguments is not significant. * @params {Object|Function} * List of Traits or property maps to create traits from. * @returns {Function} * New trait containing the combined properties of all the traits. */ function compose() { let traits = Array.slice(arguments, 0); traits.push(this); return Composition(_compose.apply(null, traits.map(TraitDescriptor))); } /** * Composes a new trait with all of the combined properties of `this` and the * argument traits. In contrast to `compose`, `override` immediately resolves * all conflicts resulting from this composition by overriding the properties of * later traits. Trait priority is from left to right. I.e. the properties of * the leftmost trait are never overridden. * @params {Object} trait * @returns {Object} */ function override() { let traits = Array.slice(arguments, 0); traits.push(this); return Composition(_override.apply(null, traits.map(TraitDescriptor))); } /** * Composes new resolved trait, with all the same properties as this * trait, except that all properties whose name is an own property of * `resolutions` will be renamed to `resolutions[name]`. If it is * `resolutions[name]` is `null` value is changed into a required property * descriptor. */ function resolve(resolutions) Composition(_resolve(resolutions, TraitDescriptor(this))) /** * Base Trait, that all the traits are composed of. */ const Trait = Composition({ /** * Internal property holding public API of this instance. */ _public: { value: null, configurable: true, writable: true }, toString: { value: function() '[object ' + this.constructor.name + ']' } }); TraitProto = Trait.prototype; exports.Trait = Trait;
import createSvgIcon from './utils/createSvgIcon'; import { jsx as _jsx } from "react/jsx-runtime"; export default createSvgIcon( /*#__PURE__*/_jsx("path", { d: "M1 21.98c0 .56.45 1.01 1.01 1.01H15c.56 0 1.01-.45 1.01-1.01V21H1v.98zM8.5 8.99C4.75 8.99 1 11 1 15h15c0-4-3.75-6.01-7.5-6.01zM3.62 13c1.11-1.55 3.47-2.01 4.88-2.01s3.77.46 4.88 2.01H3.62zM1 17h15v2H1zM18 5V1h-2v4h-5l.23 2h9.56l-1.4 14H18v2h1.72c.84 0 1.53-.65 1.63-1.47L23 5h-5z" }), 'FastfoodOutlined');
!function(n){function t(e){if(r[e])return r[e].exports;var o=r[e]={i:e,l:!1,exports:{}};return n[e].call(o.exports,o,o.exports,t),o.l=!0,o.exports}var r={};t.m=n,t.c=r,t.i=function(n){return n},t.d=function(n,r,e){t.o(n,r)||Object.defineProperty(n,r,{configurable:!1,enumerable:!0,get:e})},t.n=function(n){var r=n&&n.__esModule?function(){return n.default}:function(){return n};return t.d(r,"a",r),r},t.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},t.p="",t(t.s=0)}({0:function(n,t,r){r("qRWl"),r("MYfA"),n.exports=r("8MfB")},"8MfB":function(n,t){},MYfA:function(n,t){},qRWl:function(n,t){}});
ENDPOINT.Models.SearchResult = Backbone.Model.extend({ }) ENDPOINT.Models.Search = Backbone.Model.extend({ initialize: function(opts){ this.set({input: opts.input}) }, url: '/search' })
function setEleProps(element, strProps, elePrntID) { try { //strProps = "V=1|M=0|E=0|F=3|R=-1|B=-1"; var aryProps = strProps.split('|'); if (!(aryProps[0] == "V=1")) { //$(element).removeClass().addClass(getClassForElement(aryProps[5])).addClass(getClassForElement(aryProps[4])).addClass(getClassForElement(aryProps[3])); $(element).hide(); } else { var isInputNDisable = false; var isBasisField = false; var isTermField = false; // if ($(element).hasClass('basisWidget')) { // isBasisField = true; // } // else if ($(element).hasClass('termWidget')) { // isTermField = true; // } isBasisField = IsBasisWidget(aryProps[6]); isTermField = IsTermWidget(aryProps[6]); $(element).show(); if (!(aryProps[2] == "E=1")) { if ($(element).is('input')) { isInputNDisable = true; } else { $(element).attr('disabled', 'disabled'); } } else { if ($(element).is('input')) { if ($(element).hasClass('inputDisable')) { if ($(element).is('input[type="button"]')) { $(element).attr('disabled', false).removeClass("inputDisable"); } else { $(element).removeClass("inputDisable").removeAttr('readonly').css("border", ""); } } } else { if (elePrntID.indexOf('BI_CMEFuture') == -1) $(element).removeAttr('disabled'); } } $(element).removeClass().addClass(getClassForElement(aryProps[5])).addClass(getClassForElement(aryProps[4])).addClass(getClassForElement(aryProps[3])); if (isInputNDisable == true) { if ($(element).is('input[type="button"]')) { $(element).addClass('inputDisable').attr("disabled", true); } else { $(element).addClass('inputDisable').attr('readonly', 'readonly').css("border", "0px"); } } else { var isPriceWidget = UsesPriceWidget(parseInt(aryProps[3].split('=')[1])); if (isPriceWidget == true) { $(element).addClass('priceWidget').css("cursor", "pointer").attr('readonly', 'readonly'); } else if (isBasisField == true) { $(element).addClass('basisWidget').css("cursor", "pointer").attr('readonly', 'readonly'); } else if (isTermField == true) { $(element).addClass('termWidget').css("cursor", "pointer").attr('readonly', 'readonly'); } } if ($(element).is('input[type="text"]')) { setManualHighlighter(element, aryProps[1]); //setManualHighlighter } } } catch (err) { var strerrordesc = "Function:setEleProps(); Error is : " + err.description + "; Error number is " + err.number + "; Message :" + err.message; onJavascriptLog("VolSeparate.js", strerrordesc); } } function setManualHighlighter(element, manualProp) { // if ($(element).attr('id') == 'vcm_calc_SwapPX_260_807' || $(element).attr('id') == 'vcm_calc_SwapPX_260_808' || $(element).attr('id') == 'vcm_calc_SwapPX_260_809' || $(element).attr('id') == 'vcm_calc_SwapPX_260_810') { // alert($(element).attr('id') + " : " + manualProp); // } if (manualProp == "M=1") { $(element).addClass('ManualChange').trigger('ManualClassChange'); //$(element).css('border', '1px solid #996515'); } else { $(element).removeClass('ManualChange'); //$(element).css('border', ''); } } function UsesPriceWidget(nFormat) { return (nFormat >= 1200 && nFormat <= 1999) || (nFormat >= 5200 && nFormat <= 5999); } function IsTermWidget(fieldID) { if (fieldID == "T=21") return true; return false; } function IsBasisWidget(fieldID) { if (fieldID == "T=52") return true; return false; } function setEleColorProp() { } function getClassForElement(clrProp) { return clrProp.replace("=", "_"); } function getColorFromClass(clrClass) { try { var clrName = ""; var clrAry = clrClass.split('_'); var clrNum = clrAry[1]; var clrTyp = clrAry[0]; switch (parseInt(clrNum)) { case -1: if (clrTyp == "B") clrName = "RGB(255, 255, 255)"; else clrName = "RGB(47,47,47)"; //1B1B1B break; case 0: clrName = "RGB(51,51,51)"; break; case 1: clrName = "RGB(0, 0, 0)"; break; case 2: clrName = "RGB(0, 255, 255)"; break; case 3: clrName = "RGB(0, 0, 0)"; break; case 4: clrName = "RGB(0, 0, 255)"; break; case 5: clrName = "RGB(255, 255, 0)"; break; case 6: clrName = "RGB(255, 255, 255)"; break; case 7: clrName = "RGB(0, 0, 0)"; break; case 8: clrName = "RGB(0, 0, 0)"; break; case 9: clrName = "RGB(255, 0, 0)"; break; case 10: clrName = "RGB(0, 255, 255)"; break; case 11: clrName = "RGB(0, 0, 0)"; break; case 12: clrName = "RGB(0, 255, 0)"; break; case 13: clrName = "RGB(0, 0, 0)"; break; case 14: clrName = "RGB(141, 160, 216)"; break; case 15: clrName = "RGB(141, 160, 216)"; break; case 16: clrName = "RGB(141, 160, 216)"; break; case 17: clrName = "RGB(255, 255, 0)"; break; case 18: clrName = "RGB(0, 0, 0)"; break; case 19: clrName = "RGB(0, 0, 0)"; break; case 20: clrName = "RGB(255, 255, 255)"; break; case 21: clrName = "RGB(0, 0, 0)"; break; case 22: clrName = "RGB(255, 255, 255)"; break; case 23: clrName = "RGB(255, 255, 0)"; break; case 24: clrName = "RGB(255, 0, 0)"; break; case 25: clrName = "RGB(192, 192, 192)"; break; case 26: clrName = "RGB(0, 0, 255)"; break; case 27: clrName = "RGB(0, 255, 0)"; break; case 28: clrName = "RGB(0, 0, 0)"; break; case 29: clrName = "RGB(255, 255, 255)"; break; case 30: clrName = "RGB(255, 255, 0)"; break; case 31: clrName = "RGB(255, 0, 0)"; break; case 32: //clrName = "RGB(128, 255, 255)"; clrName = "RGB(91, 163, 240)"; break; case 33: clrName = "RGB(255, 128, 255)"; break; case 34: clrName = "RGB(255, 0, 0)"; break; case 35: clrName = "RGB(0, 160, 0)"; break; case 36: clrName = "RGB(0, 0, 0)"; break; case 37: clrName = "RGB(240, 240, 240)"; break; case 38: clrName = "RGB(255, 255, 0)"; break; case 39: clrName = "RGB(255, 0, 0)"; break; case 40: clrName = "RGB(0, 255, 255)"; break; case 41: clrName = "RGB(64, 64, 255)"; break; case 42: clrName = "RGB(128, 128, 255)"; break; case 43: clrName = "RGB(0, 0, 0)"; break; case 44: clrName = "RGB(192, 192, 192)"; break; case 45: clrName = "RGB(255, 0, 0)"; break; case 46: clrName = "RGB(255, 0, 0)"; break; case 47: clrName = "RGB(0, 0, 0)"; break; case 48: clrName = "RGB(0, 255, 0)"; break; case 49: clrName = "RGB(160, 255, 160)"; break; case 50: clrName = "RGB(255, 255, 255)"; break; case 51: clrName = "RGB(255, 255, 0)"; break; case 52: clrName = "RGB(192, 0, 0)"; break; case 53: //clrName = "RGB(128, 255, 128)"; clrName = "RGB(0, 128, 0)"; break; case 54: clrName = "RGB(255, 128, 128)"; break; case 55: //clrName = "RGB(128, 255, 255)"; clrName = "RGB(91, 163, 240)"; break; case 56: clrName = "RGB(255, 0, 255)"; break; case 57: //clrName = "RGB(128, 255, 255)"; clrName = "RGB(91, 163, 240)"; break; case 58: clrName = "RGB(0, 128, 0)"; break; case 59: clrName = "RGB(128, 128, 0)"; break; case 60: clrName = "RGB(128, 0, 0)"; break; case 61: clrName = "RGB(0, 255, 0)"; break; case 62: clrName = "RGB(255, 255, 0)"; break; case 63: clrName = "RGB(255, 0, 0)"; break; case 64: clrName = "RGB(0, 0, 0)"; break; case 65: clrName = "RGB(64, 64, 64)"; break; case 66: clrName = "RGB(128, 128, 128)"; break; case 67: clrName = "RGB(192, 192, 192)"; break; case 68: clrName = "RGB(255, 255, 255)"; break; case 69: clrName = "RGB(160, 160, 160)"; break; case 70: clrName = "RGB(96, 96, 96)"; break; case 71: clrName = "RGB(224, 224, 255)"; break; case 72: clrName = "RGB(255, 224, 255)"; break; case 73: clrName = "RGB(255, 224, 192)"; break; case 74: clrName = "RGB(255, 255, 192)"; break; case 75: clrName = "RGB(224, 255, 192)"; break; case 76: clrName = "RGB(224, 208, 255)"; break; case 77: clrName = "RGB(255, 208, 208)"; break; case 78: clrName = "RGB(208, 224, 255)"; break; case 79: clrName = "RGB(32, 32, 64)"; break; case 80: clrName = "RGB(64, 32, 64)"; break; case 81: clrName = "RGB(64, 32, 0)"; break; case 82: clrName = "RGB(64, 64, 0)"; break; case 83: clrName = "RGB(32, 64, 0)"; break; case 84: clrName = "RGB(32, 32, 64)"; break; case 85: clrName = "RGB(64, 32, 32)"; break; case 86: clrName = "RGB(32, 32, 64)"; break; case 87: clrName = "RGB(0, 0, 0)"; break; case 88: clrName = "RGB(0, 0, 0)"; break; case 89: clrName = "RGB(255, 255, 255)"; break; case 90: clrName = "RGB(0, 255, 0)"; break; case 91: clrName = "RGB(255, 0, 0)"; break; case 92: clrName = "RGB(255, 255, 0)"; break; case 93: clrName = "RGB(0, 0, 255)"; break; case 94: clrName = "RGB(255, 0, 0)"; break; case 95: clrName = "RGB(128, 0, 0)"; break; case 96: clrName = "RGB(255, 255, 255)"; break; case 97: clrName = "RGB(255, 255, 255)"; break; case 98: clrName = "RGB(0, 0, 255)"; break; case 99: clrName = "RGB(255, 255, 255)"; break; case 100: clrName = "RGB(0, 0, 127)"; break; case 101: clrName = "RGB(255, 255, 255)"; break; case 102: clrName = "RGB(255, 255, 192)"; break; case 103: clrName = "RGB(192, 255, 192)"; break; case 104: clrName = "RGB(255, 255, 192)"; break; case 105: clrName = "RGB(255, 192, 192)"; break; case 106: clrName = "RGB(255, 64, 64)"; break; case 107: clrName = "RGB(255, 0, 0)"; break; case 108: clrName = "RGB(240, 240, 240)"; break; case 109: clrName = "RGB(255, 192, 192)"; break; case 110: clrName = "RGB(192, 255, 192)"; break; case 111: clrName = "RGB(192, 192, 255)"; break; case 112: clrName = "RGB(255, 0, 0)"; break; case 113: clrName = "RGB(255, 255, 0)"; break; case 114: clrName = "RGB(0, 255, 0)"; break; case 115: clrName = "RGB(0, 0, 255)"; break; case 116: clrName = "RGB(0, 255, 255)"; break; case 117: clrName = "RGB(255, 0, 255)"; break; case 118: clrName = "RGB(255, 128, 128)"; break; case 119: clrName = "RGB(128, 128, 255)"; break; case 120: clrName = "RGB(128, 255, 128)"; break; case 121: clrName = "RGB(80, 80, 80)"; break; case 122: clrName = "RGB(255, 255, 255)"; break; case 123: clrName = "RGB(0, 0, 0)"; break; case 124: clrName = "RGB(0, 0, 255)"; break; case 125: clrName = "RGB(255, 0, 0)"; break; case 126: clrName = "RGB(200, 200, 200)"; break; case 127: clrName = "RGB(0, 0, 0)"; break; case 128: clrName = "RGB(255, 255, 255)"; break; case 129: clrName = "RGB(255,255,0)"; break; case 130: clrName = "RGB(255, 0,0)"; break; case 131: clrName = "RGB(0, 255,255)"; break; case 132: clrName = "RGB(200,200,200)"; break; case 133: clrName = "RGB(0, 0, 0)"; break; case 134: clrName = "RGB(0, 255,255)"; break; case 135: clrName = "RGB(255,255,0)"; break; case 136: clrName = "RGB(0, 0, 0)"; break; case 137: clrName = "RGB(128, 128, 128)"; break; case 138: clrName = "RGB(192, 192, 192)"; break; case 139: clrName = "RGB(255, 255, 255)"; break; case 140: clrName = "RGB(255, 255, 0)"; break; case 141: clrName = "RGB(0, 0, 0)"; break; case 142: clrName = "RGB(0, 255, 255)"; break; case 143: clrName = "RGB(0, 0, 0)"; break; case 144: clrName = "RGB(255, 255, 255)"; break; case 145: clrName = "RGB(255, 0, 0)"; break; case 146: clrName = "RGB(255, 255, 255)"; break; case 147: clrName = "RGB(0, 0, 255)"; break; case 148: clrName = "RGB(255, 255, 255)"; break; case 149: clrName = "RGB(255, 0, 0)"; break; case 150: clrName = "RGB(0, 0, 0)"; break; case 151: clrName = "RGB(0, 255, 255)"; break; case 152: clrName = "RGB(255, 0, 0)"; break; case 153: clrName = "RGB(255, 255, 255)"; break; case 154: clrName = "RGB(0, 0, 255)"; break; case 155: clrName = "RGB(255, 255, 255)"; break; case 156: clrName = "RGB(0, 0, 0)"; break; case 157: clrName = "RGB(0, 0, 0)"; break; case 158: clrName = "RGB(0, 255, 255)"; break; case 159: clrName = "RGB(0, 0, 0)"; break; case 160: clrName = "RGB(255, 255, 0)"; break; case 161: clrName = "RGB(0, 0, 0)"; break; case 162: clrName = "RGB(0, 255, 255)"; break; case 163: clrName = "RGB(0, 0, 0)"; break; case 164: clrName = "RGB(0, 0, 255)"; break; case 165: clrName = "RGB(255, 255, 0)"; break; case 166: clrName = "RGB(255, 255, 255)"; break; case 167: clrName = "RGB(0, 0, 255)"; break; case 168: clrName = "RGB(255, 0, 0)"; break; case 169: clrName = "RGB(255, 255, 255)"; break; case 170: clrName = "RGB(255, 255, 255)"; break; case 171: clrName = "RGB(0, 0, 0)"; break; case 172: clrName = "RGB(128, 128, 128)"; break; case 173: clrName = "RGB(0, 0, 0)"; break; case 174: clrName = "RGB(64, 128, 64)"; break; case 175: clrName = "RGB(255, 192, 0)"; break; case 176: clrName = "RGB(255, 64, 64)"; break; case 177: clrName = "RGB(0, 0, 0)"; break; case 178: clrName = "RGB(255, 255, 128)"; break; case 179: clrName = "RGB(128, 255, 128)"; break; case 180: clrName = "RGB(224, 32, 255)"; break; case 181: clrName = "RGB(255, 96, 96)"; break; case 182: clrName = "RGB(240, 240, 240)"; break; case 183: //clrName = "RGB(226, 19, 19)"; clrName = "RGB(255, 0, 0)"; break; case 184: // clrName = "RGB(0, 255, 0)"; clrName = "RGB(0, 128, 0)"; break; case 185: clrName = "RGB(65, 76, 202)"; break; case 186: clrName = "RGB(255, 255, 255)"; break; default: clrName = "RGB(255, 255, 255)"; break; } } catch (err) { var strerrordesc = "Function:getColorFromClass(); Error is : " + err.description + "; Error number is " + err.number + "; Message :" + err.message; //onJavascriptLog("VolSeparate.js", strerrordesc); } return clrName; }
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var core_1 = require("@ag-grid-community/core"); var core_2 = require("@ag-grid-enterprise/core"); var serverSideRowModel_1 = require("./serverSideRowModel/serverSideRowModel"); var storeUtils_1 = require("./serverSideRowModel/stores/storeUtils"); var blockUtils_1 = require("./serverSideRowModel/blocks/blockUtils"); var nodeManager_1 = require("./serverSideRowModel/nodeManager"); var transactionManager_1 = require("./serverSideRowModel/transactionManager"); var expandListener_1 = require("./serverSideRowModel/listeners/expandListener"); var sortListener_1 = require("./serverSideRowModel/listeners/sortListener"); var filterListener_1 = require("./serverSideRowModel/listeners/filterListener"); var storeFactory_1 = require("./serverSideRowModel/stores/storeFactory"); var listenerUtils_1 = require("./serverSideRowModel/listeners/listenerUtils"); exports.ServerSideRowModelModule = { moduleName: core_1.ModuleNames.ServerSideRowModelModule, rowModels: { serverSide: serverSideRowModel_1.ServerSideRowModel }, beans: [expandListener_1.ExpandListener, sortListener_1.SortListener, storeUtils_1.StoreUtils, blockUtils_1.BlockUtils, nodeManager_1.NodeManager, transactionManager_1.TransactionManager, filterListener_1.FilterListener, storeFactory_1.StoreFactory, listenerUtils_1.ListenerUtils], dependantModules: [ core_2.EnterpriseCoreModule ] }; //# sourceMappingURL=serverSideRowModelModule.js.map
(function () { var SyncTestZoneSpec = (function () { function SyncTestZoneSpec(namePrefix) { this.runZone = Zone.current; this.name = 'syncTestZone for ' + namePrefix; } SyncTestZoneSpec.prototype.onScheduleTask = function (delegate, current, target, task) { switch (task.type) { case 'microTask': case 'macroTask': throw new Error("Cannot call " + task.source + " from within a sync test."); case 'eventTask': task = delegate.scheduleTask(target, task); break; } return task; }; return SyncTestZoneSpec; }()); // Export the class so that new instances can be created with proper // constructor params. Zone['SyncTestZoneSpec'] = SyncTestZoneSpec; })(); //# sourceMappingURL=sync-test.js.map
import { CountableTimeInterval } from "./interval"; import { durationSecond } from "./duration"; function floor(date) { date.setTime(date.getTime() - date.getMilliseconds()); } function offset(date, seconds) { date.setTime(date.getTime() + seconds * durationSecond); } function count(start, end) { return (end.getTime() - start.getTime()) / durationSecond; } export var second = new CountableTimeInterval(floor, offset, count); export default second;
var React = require("react"); module.exports = React.createClass({ login: function() { $('#loginModal').modal({ "backdrop": "static" }); }, logout: function() { var self=this; $.ajax({ type: "DELETE", url: "/api/appuser", success: function(){ document.config = {}; window.location = window.location; } }); }, render: function(){ if (document.config.user_uuid !== undefined) { return ( <li><label>{document.config.user_alias || document.config.user_uuid}</label> <button id="logout-btn" className="navbar-btn btn btn-warning" type="button" onClick={this.logout}>Logout</button></li> ) } else { return ( <li><button id="login-btn" className="navbar-btn btn btn-warning" type="button" onClick={this.login}>Login</button></li> ) } } })
"use strict"; var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard"); var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = exports.nativeSelectIconStyles = exports.nativeSelectRootStyles = void 0; var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose")); var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var React = _interopRequireWildcard(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _clsx = _interopRequireDefault(require("clsx")); var _utils = require("@material-ui/utils"); var _unstyled = require("@material-ui/unstyled"); var _capitalize = _interopRequireDefault(require("../utils/capitalize")); var _nativeSelectClasses = _interopRequireWildcard(require("./nativeSelectClasses")); var _experimentalStyled = _interopRequireDefault(require("../styles/experimentalStyled")); var _jsxRuntime = require("react/jsx-runtime"); const useUtilityClasses = styleProps => { const { classes, variant, disabled, open } = styleProps; const slots = { root: ['root', 'select', variant, disabled && 'disabled'], icon: ['icon', `icon${(0, _capitalize.default)(variant)}`, open && 'iconOpen', disabled && 'disabled'] }; return (0, _unstyled.unstable_composeClasses)(slots, _nativeSelectClasses.getNativeSelectUtilityClasses, classes); }; const nativeSelectRootStyles = ({ styleProps, theme }) => (0, _extends2.default)({ MozAppearance: 'none', // Reset WebkitAppearance: 'none', // Reset // When interacting quickly, the text can end up selected. // Native select can't be selected either. userSelect: 'none', borderRadius: 0, // Reset cursor: 'pointer', '&:focus': { // Show that it's not an text input backgroundColor: theme.palette.mode === 'light' ? 'rgba(0, 0, 0, 0.05)' : 'rgba(255, 255, 255, 0.05)', borderRadius: 0 // Reset Chrome style }, // Remove IE11 arrow '&::-ms-expand': { display: 'none' }, [`&.${_nativeSelectClasses.default.disabled}`]: { cursor: 'default' }, '&[multiple]': { height: 'auto' }, '&:not([multiple]) option, &:not([multiple]) optgroup': { backgroundColor: theme.palette.background.paper }, // Bump specificity to allow extending custom inputs '&&&': { paddingRight: 24, minWidth: 16 // So it doesn't collapse. } }, styleProps.variant === 'filled' && { '&&&': { paddingRight: 32 } }, styleProps.variant === 'outlined' && { borderRadius: theme.shape.borderRadius, '&:focus': { borderRadius: theme.shape.borderRadius // Reset the reset for Chrome style }, '&&&': { paddingRight: 32 } }); exports.nativeSelectRootStyles = nativeSelectRootStyles; const NativeSelectRoot = (0, _experimentalStyled.default)('select', {}, { name: 'MuiNativeSelect', slot: 'Root', overridesResolver: (props, styles) => { const { styleProps } = props; return (0, _extends2.default)({}, styles.root, styles.select, styles[styleProps.variant]); } })(nativeSelectRootStyles); const nativeSelectIconStyles = ({ styleProps, theme }) => (0, _extends2.default)({ // We use a position absolute over a flexbox in order to forward the pointer events // to the input and to support wrapping tags.. position: 'absolute', right: 0, top: 'calc(50% - 12px)', // Center vertically pointerEvents: 'none', // Don't block pointer events on the select under the icon. color: theme.palette.action.active, [`&.${_nativeSelectClasses.default.disabled}`]: { color: theme.palette.action.disabled } }, styleProps.open && { right: 7 }, styleProps.variant === 'filled' && { right: 7 }, styleProps.variant === 'outlined' && { right: 7 }); exports.nativeSelectIconStyles = nativeSelectIconStyles; const NativeSelectIcon = (0, _experimentalStyled.default)('svg', {}, { name: 'MuiNativeSelect', slot: 'Icon', overridesResolver: (props, styles) => { const { styleProps } = props; return (0, _extends2.default)({}, styles.icon, styleProps.variant && styles[`icon${(0, _capitalize.default)(styleProps.variant)}`], styleProps.open && styles.iconOpen); } })(nativeSelectIconStyles); /** * @ignore - internal component. */ const NativeSelectInput = /*#__PURE__*/React.forwardRef(function NativeSelectInput(props, ref) { const { className, disabled, IconComponent, inputRef, variant = 'standard' } = props, other = (0, _objectWithoutPropertiesLoose2.default)(props, ["className", "disabled", "IconComponent", "inputRef", "variant"]); const styleProps = (0, _extends2.default)({}, props, { disabled, variant }); const classes = useUtilityClasses(styleProps); return /*#__PURE__*/(0, _jsxRuntime.jsxs)(React.Fragment, { children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(NativeSelectRoot, (0, _extends2.default)({ styleProps: styleProps, className: (0, _clsx.default)(classes.root, className), disabled: disabled, ref: inputRef || ref }, other)), props.multiple ? null : /*#__PURE__*/(0, _jsxRuntime.jsx)(NativeSelectIcon, { as: IconComponent, styleProps: styleProps, className: classes.icon })] }); }); process.env.NODE_ENV !== "production" ? NativeSelectInput.propTypes = { /** * The option elements to populate the select with. * Can be some `<option>` elements. */ children: _propTypes.default.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: _propTypes.default.object, /** * The CSS class name of the select element. */ className: _propTypes.default.string, /** * If `true`, the select is disabled. */ disabled: _propTypes.default.bool, /** * The icon that displays the arrow. */ IconComponent: _propTypes.default.elementType.isRequired, /** * Use that prop to pass a ref to the native select element. * @deprecated */ inputRef: _utils.refType, /** * @ignore */ multiple: _propTypes.default.bool, /** * Name attribute of the `select` or hidden `input` element. */ name: _propTypes.default.string, /** * Callback fired when a menu item is selected. * * @param {object} event The event source of the callback. * You can pull out the new value by accessing `event.target.value` (string). */ onChange: _propTypes.default.func, /** * The input value. */ value: _propTypes.default.any, /** * The variant to use. */ variant: _propTypes.default.oneOf(['standard', 'outlined', 'filled']) } : void 0; var _default = NativeSelectInput; exports.default = _default;
/* Highmaps JS v8.2.2 (2020-10-22) Highmaps as a plugin for Highcharts or Highstock. (c) 2011-2019 Torstein Honsi License: www.highcharts.com/license */ (function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/map",["highcharts"],function(B){a(B);a.Highcharts=B;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function B(a,n,h,q){a.hasOwnProperty(n)||(a[n]=q.apply(null,h))}a=a?a._modules:{};B(a,"Core/Axis/MapAxis.js",[a["Core/Axis/Axis.js"],a["Core/Utilities.js"]],function(a,n){var h=n.addEvent,q=n.pick,c=function(){return function(a){this.axis= a}}();n=function(){function a(){}a.compose=function(a){a.keepProps.push("mapAxis");h(a,"init",function(){this.mapAxis||(this.mapAxis=new c(this))});h(a,"getSeriesExtremes",function(){if(this.mapAxis){var a=[];this.isXAxis&&(this.series.forEach(function(c,m){c.useMapGeometry&&(a[m]=c.xData,c.xData=[])}),this.mapAxis.seriesXData=a)}});h(a,"afterGetSeriesExtremes",function(){if(this.mapAxis){var a=this.mapAxis.seriesXData||[],c;if(this.isXAxis){var m=q(this.dataMin,Number.MAX_VALUE);var k=q(this.dataMax, -Number.MAX_VALUE);this.series.forEach(function(p,u){p.useMapGeometry&&(m=Math.min(m,q(p.minX,m)),k=Math.max(k,q(p.maxX,k)),p.xData=a[u],c=!0)});c&&(this.dataMin=m,this.dataMax=k);this.mapAxis.seriesXData=void 0}}});h(a,"afterSetAxisTranslation",function(){if(this.mapAxis){var a=this.chart,c=a.plotWidth/a.plotHeight;a=a.xAxis[0];var m;"yAxis"===this.coll&&"undefined"!==typeof a.transA&&this.series.forEach(function(a){a.preserveAspectRatio&&(m=!0)});if(m&&(this.transA=a.transA=Math.min(this.transA, a.transA),c/=(a.max-a.min)/(this.max-this.min),c=1>c?this:a,a=(c.max-c.min)*c.transA,c.mapAxis.pixelPadding=c.len-a,c.minPixelPadding=c.mapAxis.pixelPadding/2,a=c.mapAxis.fixTo)){a=a[1]-c.toValue(a[0],!0);a*=c.transA;if(Math.abs(a)>c.minPixelPadding||c.min===c.dataMin&&c.max===c.dataMax)a=0;c.minPixelPadding-=a}}});h(a,"render",function(){this.mapAxis&&(this.mapAxis.fixTo=void 0)})};return a}();n.compose(a);return n});B(a,"Mixins/ColorSeries.js",[],function(){return{colorPointMixin:{setVisible:function(a){var n= this,h=a?"show":"hide";n.visible=n.options.visible=!!a;["graphic","dataLabel"].forEach(function(a){if(n[a])n[a][h]()});this.series.buildKDTree()}},colorSeriesMixin:{optionalAxis:"colorAxis",colorAxis:0,translateColors:function(){var a=this,n=this.options.nullColor,h=this.colorAxis,q=this.colorKey;(this.data.length?this.data:this.points).forEach(function(c){var r=c.getNestedProperty(q);(r=c.options.color||(c.isNull||null===c.value?n:h&&"undefined"!==typeof r?h.toColor(r,c):c.color||a.color))&&c.color!== r&&(c.color=r,"point"===a.options.legendType&&c.legendItem&&a.chart.legend.colorizeItem(c,c.visible))})}}}});B(a,"Core/Axis/ColorAxis.js",[a["Core/Axis/Axis.js"],a["Core/Chart/Chart.js"],a["Core/Color/Color.js"],a["Mixins/ColorSeries.js"],a["Core/Animation/Fx.js"],a["Core/Globals.js"],a["Core/Legend.js"],a["Mixins/LegendSymbol.js"],a["Series/LineSeries.js"],a["Core/Series/Point.js"],a["Core/Utilities.js"]],function(a,n,h,q,c,r,D,y,A,m,k){var p=this&&this.__extends||function(){var b=function(f,l){b= Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(l,f){l.__proto__=f}||function(l,f){for(var b in f)f.hasOwnProperty(b)&&(l[b]=f[b])};return b(f,l)};return function(f,l){function e(){this.constructor=f}b(f,l);f.prototype=null===l?Object.create(l):(e.prototype=l.prototype,new e)}}(),u=h.parse;h=q.colorPointMixin;q=q.colorSeriesMixin;var E=r.noop,x=k.addEvent,C=k.erase,g=k.extend,e=k.isNumber,b=k.merge,t=k.pick,d=k.splat;"";g(A.prototype,q);g(m.prototype,h);n.prototype.collectionsWithUpdate.push("colorAxis"); n.prototype.collectionsWithInit.colorAxis=[n.prototype.addColorAxis];var z=function(d){function f(l,f){var b=d.call(this,l,f)||this;b.beforePadding=!1;b.chart=void 0;b.coll="colorAxis";b.dataClasses=void 0;b.legendItem=void 0;b.legendItems=void 0;b.name="";b.options=void 0;b.stops=void 0;b.visible=!0;b.init(l,f);return b}p(f,d);f.buildOptions=function(l,f,e){l=l.options.legend||{};var d=e.layout?"vertical"!==e.layout:"vertical"!==l.layout;return b(f,{side:d?2:1,reversed:!d},e,{opposite:!d,showEmpty:!1, title:null,visible:l.enabled&&(e?!1!==e.visible:!0)})};f.prototype.init=function(l,b){var e=f.buildOptions(l,f.defaultOptions,b);this.coll="colorAxis";d.prototype.init.call(this,l,e);b.dataClasses&&this.initDataClasses(b);this.initStops();this.horiz=!e.opposite;this.zoomEnabled=!1};f.prototype.initDataClasses=function(l){var f=this.chart,e,d=0,t=f.options.chart.colorCount,g=this.options,a=l.dataClasses.length;this.dataClasses=e=[];this.legendItems=[];l.dataClasses.forEach(function(l,p){l=b(l);e.push(l); if(f.styledMode||!l.color)"category"===g.dataClassColor?(f.styledMode||(p=f.options.colors,t=p.length,l.color=p[d]),l.colorIndex=d,d++,d===t&&(d=0)):l.color=u(g.minColor).tweenTo(u(g.maxColor),2>a?.5:p/(a-1))})};f.prototype.hasData=function(){return!!(this.tickPositions||[]).length};f.prototype.setTickPositions=function(){if(!this.dataClasses)return d.prototype.setTickPositions.call(this)};f.prototype.initStops=function(){this.stops=this.options.stops||[[0,this.options.minColor],[1,this.options.maxColor]]; this.stops.forEach(function(l){l.color=u(l[1])})};f.prototype.setOptions=function(l){d.prototype.setOptions.call(this,l);this.options.crosshair=this.options.marker};f.prototype.setAxisSize=function(){var l=this.legendSymbol,b=this.chart,e=b.options.legend||{},d,t;l?(this.left=e=l.attr("x"),this.top=d=l.attr("y"),this.width=t=l.attr("width"),this.height=l=l.attr("height"),this.right=b.chartWidth-e-t,this.bottom=b.chartHeight-d-l,this.len=this.horiz?t:l,this.pos=this.horiz?e:d):this.len=(this.horiz? e.symbolWidth:e.symbolHeight)||f.defaultLegendLength};f.prototype.normalizedValue=function(l){this.logarithmic&&(l=this.logarithmic.log2lin(l));return 1-(this.max-l)/(this.max-this.min||1)};f.prototype.toColor=function(l,f){var b=this.dataClasses,e=this.stops,d;if(b)for(d=b.length;d--;){var t=b[d];var g=t.from;e=t.to;if(("undefined"===typeof g||l>=g)&&("undefined"===typeof e||l<=e)){var a=t.color;f&&(f.dataClass=d,f.colorIndex=t.colorIndex);break}}else{l=this.normalizedValue(l);for(d=e.length;d--&& !(l>e[d][0]););g=e[d]||e[d+1];e=e[d+1]||g;l=1-(e[0]-l)/(e[0]-g[0]||1);a=g.color.tweenTo(e.color,l)}return a};f.prototype.getOffset=function(){var l=this.legendGroup,f=this.chart.axisOffset[this.side];l&&(this.axisParent=l,d.prototype.getOffset.call(this),this.added||(this.added=!0,this.labelLeft=0,this.labelRight=this.width),this.chart.axisOffset[this.side]=f)};f.prototype.setLegendColor=function(){var l=this.reversed,f=l?1:0;l=l?0:1;f=this.horiz?[f,0,l,0]:[0,l,0,f];this.legendColor={linearGradient:{x1:f[0], y1:f[1],x2:f[2],y2:f[3]},stops:this.stops}};f.prototype.drawLegendSymbol=function(l,b){var e=l.padding,d=l.options,g=this.horiz,a=t(d.symbolWidth,g?f.defaultLegendLength:12),p=t(d.symbolHeight,g?12:f.defaultLegendLength),c=t(d.labelPadding,g?16:30);d=t(d.itemDistance,10);this.setLegendColor();b.legendSymbol=this.chart.renderer.rect(0,l.baseline-11,a,p).attr({zIndex:1}).add(b.legendGroup);this.legendItemWidth=a+e+(g?d:c);this.legendItemHeight=p+e+(g?c:0)};f.prototype.setState=function(f){this.series.forEach(function(l){l.setState(f)})}; f.prototype.setVisible=function(){};f.prototype.getSeriesExtremes=function(){var f=this.series,b=f.length,e;this.dataMin=Infinity;for(this.dataMax=-Infinity;b--;){var d=f[b];var g=d.colorKey=t(d.options.colorKey,d.colorKey,d.pointValKey,d.zoneAxis,"y");var a=d.pointArrayMap;var p=d[g+"Min"]&&d[g+"Max"];if(d[g+"Data"])var c=d[g+"Data"];else if(a){c=[];a=a.indexOf(g);var k=d.yData;if(0<=a&&k)for(e=0;e<k.length;e++)c.push(t(k[e][a],k[e]))}else c=d.yData;p?(d.minColorValue=d[g+"Min"],d.maxColorValue= d[g+"Max"]):(c=A.prototype.getExtremes.call(d,c),d.minColorValue=c.dataMin,d.maxColorValue=c.dataMax);"undefined"!==typeof d.minColorValue&&(this.dataMin=Math.min(this.dataMin,d.minColorValue),this.dataMax=Math.max(this.dataMax,d.maxColorValue));p||A.prototype.applyExtremes.call(d)}};f.prototype.drawCrosshair=function(f,b){var l=b&&b.plotX,e=b&&b.plotY,g=this.pos,t=this.len;if(b){var a=this.toPixels(b.getNestedProperty(b.series.colorKey));a<g?a=g-2:a>g+t&&(a=g+t+2);b.plotX=a;b.plotY=this.len-a;d.prototype.drawCrosshair.call(this, f,b);b.plotX=l;b.plotY=e;this.cross&&!this.cross.addedToColorAxis&&this.legendGroup&&(this.cross.addClass("highcharts-coloraxis-marker").add(this.legendGroup),this.cross.addedToColorAxis=!0,!this.chart.styledMode&&this.crosshair&&this.cross.attr({fill:this.crosshair.color}))}};f.prototype.getPlotLinePath=function(f){var l=this.left,b=f.translatedValue,g=this.top;return e(b)?this.horiz?[["M",b-4,g-6],["L",b+4,g-6],["L",b,g],["Z"]]:[["M",l,b],["L",l-6,b+6],["L",l-6,b-6],["Z"]]:d.prototype.getPlotLinePath.call(this, f)};f.prototype.update=function(l,e){var g=this.chart,t=g.legend,a=f.buildOptions(g,{},l);this.series.forEach(function(f){f.isDirtyData=!0});(l.dataClasses&&t.allItems||this.dataClasses)&&this.destroyItems();g.options[this.coll]=b(this.userOptions,a);d.prototype.update.call(this,a,e);this.legendItem&&(this.setLegendColor(),t.colorizeItem(this,!0))};f.prototype.destroyItems=function(){var f=this.chart;this.legendItem?f.legend.destroyItem(this):this.legendItems&&this.legendItems.forEach(function(l){f.legend.destroyItem(l)}); f.isDirtyLegend=!0};f.prototype.remove=function(f){this.destroyItems();d.prototype.remove.call(this,f)};f.prototype.getDataClassLegendSymbols=function(){var f=this,b=f.chart,d=f.legendItems,e=b.options.legend,t=e.valueDecimals,a=e.valueSuffix||"",p;d.length||f.dataClasses.forEach(function(l,e){var c=!0,k=l.from,v=l.to,z=b.numberFormatter;p="";"undefined"===typeof k?p="< ":"undefined"===typeof v&&(p="> ");"undefined"!==typeof k&&(p+=z(k,t)+a);"undefined"!==typeof k&&"undefined"!==typeof v&&(p+=" - "); "undefined"!==typeof v&&(p+=z(v,t)+a);d.push(g({chart:b,name:p,options:{},drawLegendSymbol:y.drawRectangle,visible:!0,setState:E,isDataClass:!0,setVisible:function(){c=f.visible=!c;f.series.forEach(function(f){f.points.forEach(function(f){f.dataClass===e&&f.setVisible(c)})});b.legend.colorizeItem(this,c)}},l))});return d};f.defaultLegendLength=200;f.defaultOptions={lineWidth:0,minPadding:0,maxPadding:0,gridLineWidth:1,tickPixelInterval:72,startOnTick:!0,endOnTick:!0,offset:0,marker:{animation:{duration:50}, width:.01,color:"#999999"},labels:{overflow:"justify",rotation:0},minColor:"#e6ebf5",maxColor:"#003399",tickLength:5,showInLegend:!0};f.keepProps=["legendGroup","legendItemHeight","legendItemWidth","legendItem","legendSymbol"];return f}(a);Array.prototype.push.apply(a.keepProps,z.keepProps);r.ColorAxis=z;["fill","stroke"].forEach(function(b){c.prototype[b+"Setter"]=function(){this.elem.attr(b,u(this.start).tweenTo(u(this.end),this.pos),null,!0)}});x(n,"afterGetAxes",function(){var b=this,f=b.options; this.colorAxis=[];f.colorAxis&&(f.colorAxis=d(f.colorAxis),f.colorAxis.forEach(function(f,d){f.index=d;new z(b,f)}))});x(A,"bindAxes",function(){var b=this.axisTypes;b?-1===b.indexOf("colorAxis")&&b.push("colorAxis"):this.axisTypes=["colorAxis"]});x(D,"afterGetAllItems",function(b){var f=[],l,d;(this.chart.colorAxis||[]).forEach(function(d){(l=d.options)&&l.showInLegend&&(l.dataClasses&&l.visible?f=f.concat(d.getDataClassLegendSymbols()):l.visible&&f.push(d),d.series.forEach(function(f){if(!f.options.showInLegend|| l.dataClasses)"point"===f.options.legendType?f.points.forEach(function(f){C(b.allItems,f)}):C(b.allItems,f)}))});for(d=f.length;d--;)b.allItems.unshift(f[d])});x(D,"afterColorizeItem",function(b){b.visible&&b.item.legendColor&&b.item.legendSymbol.attr({fill:b.item.legendColor})});x(D,"afterUpdate",function(){var b=this.chart.colorAxis;b&&b.forEach(function(f,b,d){f.update({},d)})});x(A,"afterTranslate",function(){(this.chart.colorAxis&&this.chart.colorAxis.length||this.colorAttribs)&&this.translateColors()}); return z});B(a,"Mixins/ColorMapSeries.js",[a["Core/Globals.js"],a["Core/Series/Point.js"],a["Core/Utilities.js"]],function(a,n,h){var q=h.defined;return{colorMapPointMixin:{dataLabelOnNull:!0,isValid:function(){return null!==this.value&&Infinity!==this.value&&-Infinity!==this.value},setState:function(a){n.prototype.setState.call(this,a);this.graphic&&this.graphic.attr({zIndex:"hover"===a?1:0})}},colorMapSeriesMixin:{pointArrayMap:["value"],axisTypes:["xAxis","yAxis","colorAxis"],trackerGroups:["group", "markerGroup","dataLabelsGroup"],getSymbol:a.noop,parallelArrays:["x","y","value"],colorKey:"value",pointAttribs:a.seriesTypes.column.prototype.pointAttribs,colorAttribs:function(a){var c={};q(a.color)&&(c[this.colorProp||"fill"]=a.color);return c}}}});B(a,"Maps/MapNavigation.js",[a["Core/Chart/Chart.js"],a["Core/Globals.js"],a["Core/Utilities.js"]],function(a,n,h){function q(a){a&&(a.preventDefault&&a.preventDefault(),a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)}function c(a){this.init(a)} var r=n.doc,D=h.addEvent,y=h.extend,w=h.merge,m=h.objectEach,k=h.pick;c.prototype.init=function(a){this.chart=a;a.mapNavButtons=[]};c.prototype.update=function(a){var p=this.chart,c=p.options.mapNavigation,r,h,g,e,b,t=function(b){this.handler.call(p,b);q(b)},d=p.mapNavButtons;a&&(c=p.options.mapNavigation=w(p.options.mapNavigation,a));for(;d.length;)d.pop().destroy();k(c.enableButtons,c.enabled)&&!p.renderer.forExport&&m(c.buttons,function(a,k){r=w(c.buttonOptions,a);p.styledMode||(h=r.theme,h.style= w(r.theme.style,r.style),e=(g=h.states)&&g.hover,b=g&&g.select);a=p.renderer.button(r.text,0,0,t,h,e,b,0,"zoomIn"===k?"topbutton":"bottombutton").addClass("highcharts-map-navigation highcharts-"+{zoomIn:"zoom-in",zoomOut:"zoom-out"}[k]).attr({width:r.width,height:r.height,title:p.options.lang[k],padding:r.padding,zIndex:5}).add();a.handler=r.onclick;D(a.element,"dblclick",q);d.push(a);var f=r,l=D(p,"load",function(){a.align(y(f,{width:a.width,height:2*a.height}),null,f.alignTo);l()})});this.updateEvents(c)}; c.prototype.updateEvents=function(a){var c=this.chart;k(a.enableDoubleClickZoom,a.enabled)||a.enableDoubleClickZoomTo?this.unbindDblClick=this.unbindDblClick||D(c.container,"dblclick",function(a){c.pointer.onContainerDblClick(a)}):this.unbindDblClick&&(this.unbindDblClick=this.unbindDblClick());k(a.enableMouseWheelZoom,a.enabled)?this.unbindMouseWheel=this.unbindMouseWheel||D(c.container,"undefined"===typeof r.onmousewheel?"DOMMouseScroll":"mousewheel",function(a){c.pointer.onContainerMouseWheel(a); q(a);return!1}):this.unbindMouseWheel&&(this.unbindMouseWheel=this.unbindMouseWheel())};y(a.prototype,{fitToBox:function(a,c){[["x","width"],["y","height"]].forEach(function(p){var k=p[0];p=p[1];a[k]+a[p]>c[k]+c[p]&&(a[p]>c[p]?(a[p]=c[p],a[k]=c[k]):a[k]=c[k]+c[p]-a[p]);a[p]>c[p]&&(a[p]=c[p]);a[k]<c[k]&&(a[k]=c[k])});return a},mapZoom:function(a,c,r,m,h){var g=this.xAxis[0],e=g.max-g.min,b=k(c,g.min+e/2),t=e*a;e=this.yAxis[0];var d=e.max-e.min,p=k(r,e.min+d/2);d*=a;b=this.fitToBox({x:b-t*(m?(m-g.pos)/ g.len:.5),y:p-d*(h?(h-e.pos)/e.len:.5),width:t,height:d},{x:g.dataMin,y:e.dataMin,width:g.dataMax-g.dataMin,height:e.dataMax-e.dataMin});t=b.x<=g.dataMin&&b.width>=g.dataMax-g.dataMin&&b.y<=e.dataMin&&b.height>=e.dataMax-e.dataMin;m&&g.mapAxis&&(g.mapAxis.fixTo=[m-g.pos,c]);h&&e.mapAxis&&(e.mapAxis.fixTo=[h-e.pos,r]);"undefined"===typeof a||t?(g.setExtremes(void 0,void 0,!1),e.setExtremes(void 0,void 0,!1)):(g.setExtremes(b.x,b.x+b.width,!1),e.setExtremes(b.y,b.y+b.height,!1));this.redraw()}});D(a, "beforeRender",function(){this.mapNavigation=new c(this);this.mapNavigation.update()});n.MapNavigation=c});B(a,"Maps/MapPointer.js",[a["Core/Pointer.js"],a["Core/Utilities.js"]],function(a,n){var h=n.extend,q=n.pick;n=n.wrap;h(a.prototype,{onContainerDblClick:function(a){var c=this.chart;a=this.normalize(a);c.options.mapNavigation.enableDoubleClickZoomTo?c.pointer.inClass(a.target,"highcharts-tracker")&&c.hoverPoint&&c.hoverPoint.zoomTo():c.isInsidePlot(a.chartX-c.plotLeft,a.chartY-c.plotTop)&&c.mapZoom(.5, c.xAxis[0].toValue(a.chartX),c.yAxis[0].toValue(a.chartY),a.chartX,a.chartY)},onContainerMouseWheel:function(a){var c=this.chart;a=this.normalize(a);var h=a.detail||-(a.wheelDelta/120);c.isInsidePlot(a.chartX-c.plotLeft,a.chartY-c.plotTop)&&c.mapZoom(Math.pow(c.options.mapNavigation.mouseWheelSensitivity,h),c.xAxis[0].toValue(a.chartX),c.yAxis[0].toValue(a.chartY),a.chartX,a.chartY)}});n(a.prototype,"zoomOption",function(a){var c=this.chart.options.mapNavigation;q(c.enableTouchZoom,c.enabled)&&(this.chart.options.chart.pinchType= "xy");a.apply(this,[].slice.call(arguments,1))});n(a.prototype,"pinchTranslate",function(a,h,n,q,w,m,k){a.call(this,h,n,q,w,m,k);"map"===this.chart.options.chart.type&&this.hasZoom&&(a=q.scaleX>q.scaleY,this.pinchTranslateDirection(!a,h,n,q,w,m,k,a?q.scaleX:q.scaleY))})});B(a,"Maps/Map.js",[a["Core/Chart/Chart.js"],a["Core/Globals.js"],a["Core/Options.js"],a["Core/Renderer/SVG/SVGRenderer.js"],a["Core/Utilities.js"]],function(a,n,h,q,c){function r(a,c,k,m,h,g,e,b){return[["M",a+h,c],["L",a+k-g,c], ["C",a+k-g/2,c,a+k,c+g/2,a+k,c+g],["L",a+k,c+m-e],["C",a+k,c+m-e/2,a+k-e/2,c+m,a+k-e,c+m],["L",a+b,c+m],["C",a+b/2,c+m,a,c+m-b/2,a,c+m-b],["L",a,c+h],["C",a,c+h/2,a+h/2,c,a+h,c],["Z"]]}h=h.defaultOptions;var D=c.extend,w=c.getOptions,A=c.merge,m=c.pick;c=n.Renderer;var k=n.VMLRenderer;D(h.lang,{zoomIn:"Zoom in",zoomOut:"Zoom out"});h.mapNavigation={buttonOptions:{alignTo:"plotBox",align:"left",verticalAlign:"top",x:0,width:18,height:18,padding:5,style:{fontSize:"15px",fontWeight:"bold"},theme:{"stroke-width":1, "text-align":"center"}},buttons:{zoomIn:{onclick:function(){this.mapZoom(.5)},text:"+",y:0},zoomOut:{onclick:function(){this.mapZoom(2)},text:"-",y:28}},mouseWheelSensitivity:1.1};h=n.splitPath=function(a){"string"===typeof a&&(a=a.replace(/([A-Za-z])/g," $1 ").replace(/^\s*/,"").replace(/\s*$/,""),a=a.split(/[ ,;]+/).map(function(a){return/[A-za-z]/.test(a)?a:parseFloat(a)}));return q.prototype.pathToSegments(a)};n.maps={};q.prototype.symbols.topbutton=function(a,c,k,m,h){h=h&&h.r||0;return r(a- 1,c-1,k,m,h,h,0,0)};q.prototype.symbols.bottombutton=function(a,c,k,m,h){h=h&&h.r||0;return r(a-1,c-1,k,m,0,0,h,h)};c===k&&["topbutton","bottombutton"].forEach(function(a){k.prototype.symbols[a]=q.prototype.symbols[a]});return{mapChart:n.Map=n.mapChart=function(c,k,h){var p="string"===typeof c||c.nodeName,n=arguments[p?1:0],g=n,e={endOnTick:!1,visible:!1,minPadding:0,maxPadding:0,startOnTick:!1},b=w().credits;var t=n.series;n.series=null;n=A({chart:{panning:{enabled:!0,type:"xy"},type:"map"},credits:{mapText:m(b.mapText, ' \u00a9 <a href="{geojson.copyrightUrl}">{geojson.copyrightShort}</a>'),mapTextFull:m(b.mapTextFull,"{geojson.copyright}")},tooltip:{followTouchMove:!1},xAxis:e,yAxis:A(e,{reversed:!0})},n,{chart:{inverted:!1,alignTicks:!1}});n.series=g.series=t;return p?new a(c,n,h):new a(n,k)},maps:n.maps,splitPath:h}});B(a,"Series/MapSeries.js",[a["Core/Series/Series.js"],a["Mixins/ColorMapSeries.js"],a["Core/Globals.js"],a["Mixins/LegendSymbol.js"],a["Maps/Map.js"],a["Core/Series/Point.js"],a["Core/Renderer/SVG/SVGRenderer.js"], a["Core/Utilities.js"]],function(a,n,h,q,c,r,D,y){var w=n.colorMapPointMixin,m=h.noop,k=c.maps,p=c.splitPath,u=y.extend,E=y.fireEvent,x=y.getNestedProperty,C=y.isArray,g=y.isNumber,e=y.merge,b=y.objectEach,t=y.pick,d=y.splat,z=h.Series,v=a.seriesTypes;a.seriesType("map","scatter",{animation:!1,dataLabels:{crop:!1,formatter:function(){return this.point.value},inside:!0,overflow:!1,padding:0,verticalAlign:"middle"},marker:null,nullColor:"#f7f7f7",stickyTracking:!1,tooltip:{followPointer:!0,pointFormat:"{point.name}: {point.value}<br/>"}, turboThreshold:0,allAreas:!0,borderColor:"#cccccc",borderWidth:1,joinBy:"hc-key",states:{hover:{halo:null,brightness:.2},normal:{animation:!0},select:{color:"#cccccc"},inactive:{opacity:1}}},e(n.colorMapSeriesMixin,{type:"map",getExtremesFromAll:!0,useMapGeometry:!0,forceDL:!0,searchPoint:m,directTouch:!0,preserveAspectRatio:!0,pointArrayMap:["value"],setOptions:function(a){a=z.prototype.setOptions.call(this,a);var f=a.joinBy;null===f&&(f="_i");f=this.joinBy=d(f);f[1]||(f[1]=f[0]);return a},getBox:function(a){var f= Number.MAX_VALUE,b=-f,d=f,e=-f,g=f,c=f,k=this.xAxis,h=this.yAxis,z;(a||[]).forEach(function(a){if(a.path){"string"===typeof a.path?a.path=p(a.path):"M"===a.path[0]&&(a.path=D.prototype.pathToSegments(a.path));var l=a.path||[],k=-f,h=f,m=-f,v=f,n=a.properties;a._foundBox||(l.forEach(function(a){var f=a[a.length-2];a=a[a.length-1];"number"===typeof f&&"number"===typeof a&&(h=Math.min(h,f),k=Math.max(k,f),v=Math.min(v,a),m=Math.max(m,a))}),a._midX=h+(k-h)*t(a.middleX,n&&n["hc-middle-x"],.5),a._midY= v+(m-v)*t(a.middleY,n&&n["hc-middle-y"],.5),a._maxX=k,a._minX=h,a._maxY=m,a._minY=v,a.labelrank=t(a.labelrank,(k-h)*(m-v)),a._foundBox=!0);b=Math.max(b,a._maxX);d=Math.min(d,a._minX);e=Math.max(e,a._maxY);g=Math.min(g,a._minY);c=Math.min(a._maxX-a._minX,a._maxY-a._minY,c);z=!0}});z&&(this.minY=Math.min(g,t(this.minY,f)),this.maxY=Math.max(e,t(this.maxY,-f)),this.minX=Math.min(d,t(this.minX,f)),this.maxX=Math.max(b,t(this.maxX,-f)),k&&"undefined"===typeof k.options.minRange&&(k.minRange=Math.min(5* c,(this.maxX-this.minX)/5,k.minRange||f)),h&&"undefined"===typeof h.options.minRange&&(h.minRange=Math.min(5*c,(this.maxY-this.minY)/5,h.minRange||f)))},hasData:function(){return!!this.processedXData.length},getExtremes:function(){var a=z.prototype.getExtremes.call(this,this.valueData),b=a.dataMin;a=a.dataMax;this.chart.hasRendered&&this.isDirtyData&&this.getBox(this.options.data);g(b)&&(this.valueMin=b);g(a)&&(this.valueMax=a);return{dataMin:this.minY,dataMax:this.maxY}},translatePath:function(a){var f= this.xAxis,b=this.yAxis,d=f.min,e=f.transA,g=f.minPixelPadding,c=b.min,t=b.transA,k=b.minPixelPadding,h=[];a&&a.forEach(function(a){"M"===a[0]?h.push(["M",(a[1]-(d||0))*e+g,(a[2]-(c||0))*t+k]):"L"===a[0]?h.push(["L",(a[1]-(d||0))*e+g,(a[2]-(c||0))*t+k]):"C"===a[0]?h.push(["C",(a[1]-(d||0))*e+g,(a[2]-(c||0))*t+k,(a[3]-(d||0))*e+g,(a[4]-(c||0))*t+k,(a[5]-(d||0))*e+g,(a[6]-(c||0))*t+k]):"Q"===a[0]?h.push(["Q",(a[1]-(d||0))*e+g,(a[2]-(c||0))*t+k,(a[3]-(d||0))*e+g,(a[4]-(c||0))*t+k]):"Z"===a[0]&&h.push(["Z"])}); return h},setData:function(a,d,c,t){var f=this.options,l=this.chart.options.chart,p=l&&l.map,m=f.mapData,v=this.joinBy,n=f.keys||this.pointArrayMap,F=[],q={},u=this.chart.mapTransforms;!m&&p&&(m="string"===typeof p?k[p]:p);a&&a.forEach(function(b,d){var e=0;if(g(b))a[d]={value:b};else if(C(b)){a[d]={};!f.keys&&b.length>n.length&&"string"===typeof b[0]&&(a[d]["hc-key"]=b[0],++e);for(var l=0;l<n.length;++l,++e)n[l]&&"undefined"!==typeof b[e]&&(0<n[l].indexOf(".")?r.prototype.setNestedProperty(a[d], b[e],n[l]):a[d][n[l]]=b[e])}v&&"_i"===v[0]&&(a[d]._i=d)});this.getBox(a);(this.chart.mapTransforms=u=l&&l.mapTransforms||m&&m["hc-transform"]||u)&&b(u,function(a){a.rotation&&(a.cosAngle=Math.cos(a.rotation),a.sinAngle=Math.sin(a.rotation))});if(m){"FeatureCollection"===m.type&&(this.mapTitle=m.title,m=h.geojson(m,this.type,this));this.mapData=m;this.mapMap={};for(u=0;u<m.length;u++)l=m[u],p=l.properties,l._i=u,v[0]&&p&&p[v[0]]&&(l[v[0]]=p[v[0]]),q[l[v[0]]]=l;this.mapMap=q;if(a&&v[1]){var G=v[1]; a.forEach(function(a){a=x(G,a);q[a]&&F.push(q[a])})}if(f.allAreas){this.getBox(m);a=a||[];if(v[1]){var w=v[1];a.forEach(function(a){F.push(x(w,a))})}F="|"+F.map(function(a){return a&&a[v[0]]}).join("|")+"|";m.forEach(function(f){v[0]&&-1!==F.indexOf("|"+f[v[0]]+"|")||(a.push(e(f,{value:null})),t=!1)})}else this.getBox(F)}z.prototype.setData.call(this,a,d,c,t)},drawGraph:m,drawDataLabels:m,doFullTranslate:function(){return this.isDirtyData||this.chart.isResizing||this.chart.renderer.isVML||!this.baseTrans}, translate:function(){var a=this,b=a.xAxis,d=a.yAxis,e=a.doFullTranslate();a.generatePoints();a.data.forEach(function(f){g(f._midX)&&g(f._midY)&&(f.plotX=b.toPixels(f._midX,!0),f.plotY=d.toPixels(f._midY,!0));e&&(f.shapeType="path",f.shapeArgs={d:a.translatePath(f.path)})});E(a,"afterTranslate")},pointAttribs:function(a,b){b=a.series.chart.styledMode?this.colorAttribs(a):v.column.prototype.pointAttribs.call(this,a,b);b["stroke-width"]=t(a.options[this.pointAttrToOptions&&this.pointAttrToOptions["stroke-width"]|| "borderWidth"],"inherit");return b},drawPoints:function(){var a=this,b=a.xAxis,d=a.yAxis,e=a.group,g=a.chart,c=g.renderer,k=this.baseTrans;a.transformGroup||(a.transformGroup=c.g().attr({scaleX:1,scaleY:1}).add(e),a.transformGroup.survive=!0);if(a.doFullTranslate())g.hasRendered&&!g.styledMode&&a.points.forEach(function(b){b.shapeArgs&&(b.shapeArgs.fill=a.pointAttribs(b,b.state).fill)}),a.group=a.transformGroup,v.column.prototype.drawPoints.apply(a),a.group=e,a.points.forEach(function(b){if(b.graphic){var f= "";b.name&&(f+="highcharts-name-"+b.name.replace(/ /g,"-").toLowerCase());b.properties&&b.properties["hc-key"]&&(f+=" highcharts-key-"+b.properties["hc-key"].toLowerCase());f&&b.graphic.addClass(f);g.styledMode&&b.graphic.css(a.pointAttribs(b,b.selected&&"select"||void 0))}}),this.baseTrans={originX:b.min-b.minPixelPadding/b.transA,originY:d.min-d.minPixelPadding/d.transA+(d.reversed?0:d.len/d.transA),transAX:b.transA,transAY:d.transA},this.transformGroup.animate({translateX:0,translateY:0,scaleX:1, scaleY:1});else{var h=b.transA/k.transAX;var m=d.transA/k.transAY;var p=b.toPixels(k.originX,!0);var z=d.toPixels(k.originY,!0);.99<h&&1.01>h&&.99<m&&1.01>m&&(m=h=1,p=Math.round(p),z=Math.round(z));var n=this.transformGroup;if(g.renderer.globalAnimation){var r=n.attr("translateX");var q=n.attr("translateY");var u=n.attr("scaleX");var w=n.attr("scaleY");n.attr({animator:0}).animate({animator:1},{step:function(a,b){n.attr({translateX:r+(p-r)*b.pos,translateY:q+(z-q)*b.pos,scaleX:u+(h-u)*b.pos,scaleY:w+ (m-w)*b.pos})}})}else n.attr({translateX:p,translateY:z,scaleX:h,scaleY:m})}g.styledMode||e.element.setAttribute("stroke-width",t(a.options[a.pointAttrToOptions&&a.pointAttrToOptions["stroke-width"]||"borderWidth"],1)/(h||1));this.drawMapDataLabels()},drawMapDataLabels:function(){z.prototype.drawDataLabels.call(this);this.dataLabelsGroup&&this.dataLabelsGroup.clip(this.chart.clipRect)},render:function(){var a=this,b=z.prototype.render;a.chart.renderer.isVML&&3E3<a.data.length?setTimeout(function(){b.call(a)}): b.call(a)},animate:function(a){var b=this.options.animation,d=this.group,f=this.xAxis,e=this.yAxis,g=f.pos,c=e.pos;this.chart.renderer.isSVG&&(!0===b&&(b={duration:1E3}),a?d.attr({translateX:g+f.len/2,translateY:c+e.len/2,scaleX:.001,scaleY:.001}):d.animate({translateX:g,translateY:c,scaleX:1,scaleY:1},b))},animateDrilldown:function(a){var b=this.chart.plotBox,d=this.chart.drilldownLevels[this.chart.drilldownLevels.length-1],f=d.bBox,e=this.chart.options.drilldown.animation;a||(a=Math.min(f.width/ b.width,f.height/b.height),d.shapeArgs={scaleX:a,scaleY:a,translateX:f.x,translateY:f.y},this.points.forEach(function(a){a.graphic&&a.graphic.attr(d.shapeArgs).animate({scaleX:1,scaleY:1,translateX:0,translateY:0},e)}))},drawLegendSymbol:q.drawRectangle,animateDrillupFrom:function(a){v.column.prototype.animateDrillupFrom.call(this,a)},animateDrillupTo:function(a){v.column.prototype.animateDrillupTo.call(this,a)}}),u({applyOptions:function(a,b){var d=this.series;a=r.prototype.applyOptions.call(this, a,b);b=d.joinBy;d.mapData&&d.mapMap&&(b=r.prototype.getNestedProperty.call(a,b[1]),(b="undefined"!==typeof b&&d.mapMap[b])?(d.xyFromShape&&(a.x=b._midX,a.y=b._midY),u(a,b)):a.value=a.value||null);return a},onMouseOver:function(a){y.clearTimeout(this.colorInterval);if(null!==this.value||this.series.options.nullInteraction)r.prototype.onMouseOver.call(this,a);else this.series.onMouseOut(a)},zoomTo:function(){var a=this.series;a.xAxis.setExtremes(this._minX,this._maxX,!1);a.yAxis.setExtremes(this._minY, this._maxY,!1);a.chart.redraw()}},w));""});B(a,"Series/MapLineSeries.js",[a["Core/Series/Series.js"]],function(a){var n=a.seriesTypes;a.seriesType("mapline","map",{lineWidth:1,fillColor:"none"},{type:"mapline",colorProp:"stroke",pointAttrToOptions:{stroke:"color","stroke-width":"lineWidth"},pointAttribs:function(a,q){a=n.map.prototype.pointAttribs.call(this,a,q);a.fill=this.options.fillColor;return a},drawLegendSymbol:n.line.prototype.drawLegendSymbol});""});B(a,"Series/MapPointSeries.js",[a["Core/Series/Series.js"], a["Core/Globals.js"],a["Core/Series/Point.js"],a["Core/Utilities.js"]],function(a,n,h,q){var c=q.merge,r=n.Series;a.seriesType("mappoint","scatter",{dataLabels:{crop:!1,defer:!1,enabled:!0,formatter:function(){return this.point.name},overflow:!1,style:{color:"#000000"}}},{type:"mappoint",forceDL:!0,drawDataLabels:function(){r.prototype.drawDataLabels.call(this);this.dataLabelsGroup&&this.dataLabelsGroup.clip(this.chart.clipRect)}},{applyOptions:function(a,n){a="undefined"!==typeof a.lat&&"undefined"!== typeof a.lon?c(a,this.series.chart.fromLatLonToPoint(a)):a;return h.prototype.applyOptions.call(this,a,n)}});""});B(a,"Series/Bubble/BubbleLegend.js",[a["Core/Chart/Chart.js"],a["Core/Color/Color.js"],a["Core/Globals.js"],a["Core/Legend.js"],a["Core/Utilities.js"]],function(a,n,h,q,c){var r=n.parse;n=c.addEvent;var w=c.arrayMax,y=c.arrayMin,A=c.isNumber,m=c.merge,k=c.objectEach,p=c.pick,u=c.setOptions,E=c.stableSort,x=c.wrap;"";var C=h.Series,g=h.noop;u({legend:{bubbleLegend:{borderColor:void 0,borderWidth:2, className:void 0,color:void 0,connectorClassName:void 0,connectorColor:void 0,connectorDistance:60,connectorWidth:1,enabled:!1,labels:{className:void 0,allowOverlap:!1,format:"",formatter:void 0,align:"right",style:{fontSize:10,color:void 0},x:0,y:0},maxSize:60,minSize:10,legendIndex:0,ranges:{value:void 0,borderColor:void 0,color:void 0,connectorColor:void 0},sizeBy:"area",sizeByAbsoluteValue:!1,zIndex:1,zThreshold:0}}});u=function(){function a(a,e){this.options=this.symbols=this.visible=this.ranges= this.movementX=this.maxLabel=this.legendSymbol=this.legendItemWidth=this.legendItemHeight=this.legendItem=this.legendGroup=this.legend=this.fontMetrics=this.chart=void 0;this.setState=g;this.init(a,e)}a.prototype.init=function(a,e){this.options=a;this.visible=!0;this.chart=e.chart;this.legend=e};a.prototype.addToLegend=function(a){a.splice(this.options.legendIndex,0,this)};a.prototype.drawLegendSymbol=function(a){var b=this.chart,d=this.options,e=p(a.options.itemDistance,20),g=d.ranges;var f=d.connectorDistance; this.fontMetrics=b.renderer.fontMetrics(d.labels.style.fontSize.toString()+"px");g&&g.length&&A(g[0].value)?(E(g,function(a,b){return b.value-a.value}),this.ranges=g,this.setOptions(),this.render(),b=this.getMaxLabelSize(),g=this.ranges[0].radius,a=2*g,f=f-g+b.width,f=0<f?f:0,this.maxLabel=b,this.movementX="left"===d.labels.align?f:0,this.legendItemWidth=a+f+e,this.legendItemHeight=a+this.fontMetrics.h/2):a.options.bubbleLegend.autoRanges=!0};a.prototype.setOptions=function(){var a=this.ranges,e= this.options,d=this.chart.series[e.seriesIndex],g=this.legend.baseline,c={"z-index":e.zIndex,"stroke-width":e.borderWidth},f={"z-index":e.zIndex,"stroke-width":e.connectorWidth},l=this.getLabelStyles(),k=d.options.marker.fillOpacity,h=this.chart.styledMode;a.forEach(function(b,t){h||(c.stroke=p(b.borderColor,e.borderColor,d.color),c.fill=p(b.color,e.color,1!==k?r(d.color).setOpacity(k).get("rgba"):d.color),f.stroke=p(b.connectorColor,e.connectorColor,d.color));a[t].radius=this.getRangeRadius(b.value); a[t]=m(a[t],{center:a[0].radius-a[t].radius+g});h||m(!0,a[t],{bubbleStyle:m(!1,c),connectorStyle:m(!1,f),labelStyle:l})},this)};a.prototype.getLabelStyles=function(){var a=this.options,e={},d="left"===a.labels.align,g=this.legend.options.rtl;k(a.labels.style,function(a,b){"color"!==b&&"fontSize"!==b&&"z-index"!==b&&(e[b]=a)});return m(!1,e,{"font-size":a.labels.style.fontSize,fill:p(a.labels.style.color,"#000000"),"z-index":a.zIndex,align:g||d?"right":"left"})};a.prototype.getRangeRadius=function(a){var b= this.options;return this.chart.series[this.options.seriesIndex].getRadius.call(this,b.ranges[b.ranges.length-1].value,b.ranges[0].value,b.minSize,b.maxSize,a)};a.prototype.render=function(){var a=this.chart.renderer,e=this.options.zThreshold;this.symbols||(this.symbols={connectors:[],bubbleItems:[],labels:[]});this.legendSymbol=a.g("bubble-legend");this.legendItem=a.g("bubble-legend-item");this.legendSymbol.translateX=0;this.legendSymbol.translateY=0;this.ranges.forEach(function(a){a.value>=e&&this.renderRange(a)}, this);this.legendSymbol.add(this.legendItem);this.legendItem.add(this.legendGroup);this.hideOverlappingLabels()};a.prototype.renderRange=function(a){var b=this.options,d=b.labels,e=this.chart.renderer,g=this.symbols,f=g.labels,c=a.center,k=Math.abs(a.radius),h=b.connectorDistance||0,m=d.align,p=d.style.fontSize;h=this.legend.options.rtl||"left"===m?-h:h;d=b.connectorWidth;var n=this.ranges[0].radius||0,r=c-k-b.borderWidth/2+d/2;p=p/2-(this.fontMetrics.h-p)/2;var q=e.styledMode;"center"===m&&(h=0, b.connectorDistance=0,a.labelStyle.align="center");m=r+b.labels.y;var u=n+h+b.labels.x;g.bubbleItems.push(e.circle(n,c+((r%1?1:.5)-(d%2?0:.5)),k).attr(q?{}:a.bubbleStyle).addClass((q?"highcharts-color-"+this.options.seriesIndex+" ":"")+"highcharts-bubble-legend-symbol "+(b.className||"")).add(this.legendSymbol));g.connectors.push(e.path(e.crispLine([["M",n,r],["L",n+h,r]],b.connectorWidth)).attr(q?{}:a.connectorStyle).addClass((q?"highcharts-color-"+this.options.seriesIndex+" ":"")+"highcharts-bubble-legend-connectors "+ (b.connectorClassName||"")).add(this.legendSymbol));a=e.text(this.formatLabel(a),u,m+p).attr(q?{}:a.labelStyle).addClass("highcharts-bubble-legend-labels "+(b.labels.className||"")).add(this.legendSymbol);f.push(a);a.placed=!0;a.alignAttr={x:u,y:m+p}};a.prototype.getMaxLabelSize=function(){var a,e;this.symbols.labels.forEach(function(b){e=b.getBBox(!0);a=a?e.width>a.width?e:a:e});return a||{}};a.prototype.formatLabel=function(a){var b=this.options,d=b.labels.formatter;b=b.labels.format;var e=this.chart.numberFormatter; return b?c.format(b,a):d?d.call(a):e(a.value,1)};a.prototype.hideOverlappingLabels=function(){var a=this.chart,e=this.symbols;!this.options.labels.allowOverlap&&e&&(a.hideOverlappingLabels(e.labels),e.labels.forEach(function(a,b){a.newOpacity?a.newOpacity!==a.oldOpacity&&e.connectors[b].show():e.connectors[b].hide()}))};a.prototype.getRanges=function(){var a=this.legend.bubbleLegend,e=a.options.ranges,d,g=Number.MAX_VALUE,c=-Number.MAX_VALUE;a.chart.series.forEach(function(a){a.isBubble&&!a.ignoreSeries&& (d=a.zData.filter(A),d.length&&(g=p(a.options.zMin,Math.min(g,Math.max(y(d),!1===a.options.displayNegative?a.options.zThreshold:-Number.MAX_VALUE))),c=p(a.options.zMax,Math.max(c,w(d)))))});var f=g===c?[{value:c}]:[{value:g},{value:(g+c)/2},{value:c,autoRanges:!0}];e.length&&e[0].radius&&f.reverse();f.forEach(function(a,b){e&&e[b]&&(f[b]=m(!1,e[b],a))});return f};a.prototype.predictBubbleSizes=function(){var a=this.chart,e=this.fontMetrics,d=a.legend.options,g="horizontal"===d.layout,c=g?a.legend.lastLineHeight: 0,f=a.plotSizeX,k=a.plotSizeY,h=a.series[this.options.seriesIndex];a=Math.ceil(h.minPxSize);var m=Math.ceil(h.maxPxSize);h=h.options.maxSize;var p=Math.min(k,f);if(d.floating||!/%$/.test(h))e=m;else if(h=parseFloat(h),e=(p+c-e.h/2)*h/100/(h/100+1),g&&k-e>=f||!g&&f-e>=k)e=m;return[a,Math.ceil(e)]};a.prototype.updateRanges=function(a,e){var b=this.legend.options.bubbleLegend;b.minSize=a;b.maxSize=e;b.ranges=this.getRanges()};a.prototype.correctSizes=function(){var a=this.legend,e=this.chart.series[this.options.seriesIndex]; 1<Math.abs(Math.ceil(e.maxPxSize)-this.options.maxSize)&&(this.updateRanges(this.options.minSize,e.maxPxSize),a.render())};return a}();n(q,"afterGetAllItems",function(a){var b=this.bubbleLegend,e=this.options,d=e.bubbleLegend,g=this.chart.getVisibleBubbleSeriesIndex();b&&b.ranges&&b.ranges.length&&(d.ranges.length&&(d.autoRanges=!!d.ranges[0].autoRanges),this.destroyItem(b));0<=g&&e.enabled&&d.enabled&&(d.seriesIndex=g,this.bubbleLegend=new h.BubbleLegend(d,this),this.bubbleLegend.addToLegend(a.allItems))}); a.prototype.getVisibleBubbleSeriesIndex=function(){for(var a=this.series,b=0;b<a.length;){if(a[b]&&a[b].isBubble&&a[b].visible&&a[b].zData.length)return b;b++}return-1};q.prototype.getLinesHeights=function(){var a=this.allItems,b=[],g=a.length,d,c=0;for(d=0;d<g;d++)if(a[d].legendItemHeight&&(a[d].itemHeight=a[d].legendItemHeight),a[d]===a[g-1]||a[d+1]&&a[d]._legendItemPos[1]!==a[d+1]._legendItemPos[1]){b.push({height:0});var k=b[b.length-1];for(c;c<=d;c++)a[c].itemHeight>k.height&&(k.height=a[c].itemHeight); k.step=d}return b};q.prototype.retranslateItems=function(a){var b,e,d,g=this.options.rtl,c=0;this.allItems.forEach(function(f,k){b=f.legendGroup.translateX;e=f._legendItemPos[1];if((d=f.movementX)||g&&f.ranges)d=g?b-f.options.maxSize/2:b+d,f.legendGroup.attr({translateX:d});k>a[c].step&&c++;f.legendGroup.attr({translateY:Math.round(e+a[c].height/2)});f._legendItemPos[1]=e+a[c].height/2})};n(C,"legendItemClick",function(){var a=this.chart,b=this.visible,g=this.chart.legend;g&&g.bubbleLegend&&(this.visible= !b,this.ignoreSeries=b,a=0<=a.getVisibleBubbleSeriesIndex(),g.bubbleLegend.visible!==a&&(g.update({bubbleLegend:{enabled:a}}),g.bubbleLegend.visible=a),this.visible=b)});x(a.prototype,"drawChartBox",function(a,b,g){var d=this.legend,e=0<=this.getVisibleBubbleSeriesIndex();if(d&&d.options.enabled&&d.bubbleLegend&&d.options.bubbleLegend.autoRanges&&e){var c=d.bubbleLegend.options;e=d.bubbleLegend.predictBubbleSizes();d.bubbleLegend.updateRanges(e[0],e[1]);c.placed||(d.group.placed=!1,d.allItems.forEach(function(a){a.legendGroup.translateY= null}));d.render();this.getMargins();this.axes.forEach(function(a){a.visible&&a.render();c.placed||(a.setScale(),a.updateNames(),k(a.ticks,function(a){a.isNew=!0;a.isNewLabel=!0}))});c.placed=!0;this.getMargins();a.call(this,b,g);d.bubbleLegend.correctSizes();d.retranslateItems(d.getLinesHeights())}else a.call(this,b,g),d&&d.options.enabled&&d.bubbleLegend&&(d.render(),d.retranslateItems(d.getLinesHeights()))});h.BubbleLegend=u;return h.BubbleLegend});B(a,"Series/Bubble/BubbleSeries.js",[a["Core/Axis/Axis.js"], a["Core/Series/Series.js"],a["Core/Color/Color.js"],a["Core/Globals.js"],a["Core/Series/Point.js"],a["Core/Utilities.js"]],function(a,n,h,q,c,r){var w=h.parse;h=q.noop;var y=r.arrayMax,A=r.arrayMin,m=r.clamp,k=r.extend,p=r.isNumber,u=r.pick,E=r.pInt,x=q.Series,C=n.seriesTypes;"";n.seriesType("bubble","scatter",{dataLabels:{formatter:function(){return this.point.z},inside:!0,verticalAlign:"middle"},animationLimit:250,marker:{lineColor:null,lineWidth:1,fillOpacity:.5,radius:null,states:{hover:{radiusPlus:0}}, symbol:"circle"},minSize:8,maxSize:"20%",softThreshold:!1,states:{hover:{halo:{size:5}}},tooltip:{pointFormat:"({point.x}, {point.y}), Size: {point.z}"},turboThreshold:0,zThreshold:0,zoneAxis:"z"},{pointArrayMap:["y","z"],parallelArrays:["x","y","z"],trackerGroups:["group","dataLabelsGroup"],specialGroup:"group",bubblePadding:!0,zoneAxis:"z",directTouch:!0,isBubble:!0,pointAttribs:function(a,e){var b=this.options.marker.fillOpacity;a=x.prototype.pointAttribs.call(this,a,e);1!==b&&(a.fill=w(a.fill).setOpacity(b).get("rgba")); return a},getRadii:function(a,e,b){var g=this.zData,d=this.yData,c=b.minPxSize,k=b.maxPxSize,f=[];var l=0;for(b=g.length;l<b;l++){var h=g[l];f.push(this.getRadius(a,e,c,k,h,d[l]))}this.radii=f},getRadius:function(a,e,b,c,d,k){var g=this.options,f="width"!==g.sizeBy,l=g.zThreshold,h=e-a,m=.5;if(null===k||null===d)return null;if(p(d)){g.sizeByAbsoluteValue&&(d=Math.abs(d-l),h=Math.max(e-l,Math.abs(a-l)),a=0);if(d<a)return b/2-1;0<h&&(m=(d-a)/h)}f&&0<=m&&(m=Math.sqrt(m));return Math.ceil(b+m*(c-b))/ 2},animate:function(a){!a&&this.points.length<this.options.animationLimit&&this.points.forEach(function(a){var b=a.graphic;b&&b.width&&(this.hasRendered||b.attr({x:a.plotX,y:a.plotY,width:1,height:1}),b.animate(this.markerAttribs(a),this.options.animation))},this)},hasData:function(){return!!this.processedXData.length},translate:function(){var a,e=this.data,b=this.radii;C.scatter.prototype.translate.call(this);for(a=e.length;a--;){var c=e[a];var d=b?b[a]:0;p(d)&&d>=this.minPxSize/2?(c.marker=k(c.marker, {radius:d,width:2*d,height:2*d}),c.dlBox={x:c.plotX-d,y:c.plotY-d,width:2*d,height:2*d}):c.shapeArgs=c.plotY=c.dlBox=void 0}},alignDataLabel:C.column.prototype.alignDataLabel,buildKDTree:h,applyZones:h},{haloPath:function(a){return c.prototype.haloPath.call(this,0===a?0:(this.marker?this.marker.radius||0:0)+a)},ttBelow:!1});a.prototype.beforePadding=function(){var a=this,e=this.len,b=this.chart,c=0,d=e,k=this.isXAxis,h=k?"xData":"yData",f=this.min,l={},n=Math.min(b.plotWidth,b.plotHeight),r=Number.MAX_VALUE, q=-Number.MAX_VALUE,w=this.max-f,x=e/w,C=[];this.series.forEach(function(d){var e=d.options;!d.bubblePadding||!d.visible&&b.options.chart.ignoreHiddenSeries||(a.allowZoomOutside=!0,C.push(d),k&&(["minSize","maxSize"].forEach(function(a){var b=e[a],d=/%$/.test(b);b=E(b);l[a]=d?n*b/100:b}),d.minPxSize=l.minSize,d.maxPxSize=Math.max(l.maxSize,l.minSize),d=d.zData.filter(p),d.length&&(r=u(e.zMin,m(A(d),!1===e.displayNegative?e.zThreshold:-Number.MAX_VALUE,r)),q=u(e.zMax,Math.max(q,y(d))))))});C.forEach(function(b){var e= b[h],g=e.length;k&&b.getRadii(r,q,b);if(0<w)for(;g--;)if(p(e[g])&&a.dataMin<=e[g]&&e[g]<=a.max){var l=b.radii?b.radii[g]:0;c=Math.min((e[g]-f)*x-l,c);d=Math.max((e[g]-f)*x+l,d)}});C.length&&0<w&&!this.logarithmic&&(d-=e,x*=(e+Math.max(0,c)-Math.min(d,e))/e,[["min","userMin",c],["max","userMax",d]].forEach(function(b){"undefined"===typeof u(a.options[b[0]],a[b[1]])&&(a[b[0]]+=b[2]/x)}))};""});B(a,"Series/MapBubbleSeries.js",[a["Core/Series/Series.js"],a["Core/Series/Point.js"],a["Core/Utilities.js"]], function(a,n,h){var q=h.merge,c=a.seriesTypes;c.bubble&&a.seriesType("mapbubble","bubble",{animationLimit:500,tooltip:{pointFormat:"{point.name}: {point.z}"}},{xyFromShape:!0,type:"mapbubble",pointArrayMap:["z"],getMapData:c.map.prototype.getMapData,getBox:c.map.prototype.getBox,setData:c.map.prototype.setData,setOptions:c.map.prototype.setOptions},{applyOptions:function(a,h){return a&&"undefined"!==typeof a.lat&&"undefined"!==typeof a.lon?n.prototype.applyOptions.call(this,q(a,this.series.chart.fromLatLonToPoint(a)), h):c.map.prototype.pointClass.prototype.applyOptions.call(this,a,h)},isValid:function(){return"number"===typeof this.z},ttBelow:!1});""});B(a,"Series/HeatmapSeries.js",[a["Core/Series/Series.js"],a["Mixins/ColorMapSeries.js"],a["Core/Globals.js"],a["Mixins/LegendSymbol.js"],a["Core/Renderer/SVG/SVGRenderer.js"],a["Core/Utilities.js"]],function(a,n,h,q,c,r){var w=n.colorMapPointMixin;n=n.colorMapSeriesMixin;var y=h.noop,A=r.clamp,m=r.extend,k=r.fireEvent,p=r.isNumber,u=r.merge,E=r.pick,x=h.Series; r=a.seriesTypes;var C=c.prototype.symbols;"";a.seriesType("heatmap","scatter",{animation:!1,borderWidth:0,nullColor:"#f7f7f7",dataLabels:{formatter:function(){return this.point.value},inside:!0,verticalAlign:"middle",crop:!1,overflow:!1,padding:0},marker:{symbol:"rect",radius:0,lineColor:void 0,states:{hover:{lineWidthPlus:0},select:{}}},clip:!0,pointRange:null,tooltip:{pointFormat:"{point.x}, {point.y}: {point.value}<br/>"},states:{hover:{halo:!1,brightness:.2}}},u(n,{pointArrayMap:["y","value"], hasPointSpecificOptions:!0,getExtremesFromAll:!0,directTouch:!0,init:function(){x.prototype.init.apply(this,arguments);var a=this.options;a.pointRange=E(a.pointRange,a.colsize||1);this.yAxis.axisPointRange=a.rowsize||1;m(C,{ellipse:C.circle,rect:C.square})},getSymbol:x.prototype.getSymbol,setClip:function(a){var e=this.chart;x.prototype.setClip.apply(this,arguments);(!1!==this.options.clip||a)&&this.markerGroup.clip((a||this.clipBox)&&this.sharedClipKey?e[this.sharedClipKey]:e.clipRect)},translate:function(){var a= this.options,e=a.marker&&a.marker.symbol||"",b=C[e]?e:"rect";a=this.options;var c=-1!==["circle","square"].indexOf(b);this.generatePoints();this.points.forEach(function(a){var d=a.getCellAttributes(),g={x:Math.min(d.x1,d.x2),y:Math.min(d.y1,d.y2),width:Math.max(Math.abs(d.x2-d.x1),0),height:Math.max(Math.abs(d.y2-d.y1),0)};var f=a.hasImage=0===(a.marker&&a.marker.symbol||e||"").indexOf("url");if(c){var k=Math.abs(g.width-g.height);g.x=Math.min(d.x1,d.x2)+(g.width<g.height?0:k/2);g.y=Math.min(d.y1, d.y2)+(g.width<g.height?k/2:0);g.width=g.height=Math.min(g.width,g.height)}k={plotX:(d.x1+d.x2)/2,plotY:(d.y1+d.y2)/2,clientX:(d.x1+d.x2)/2,shapeType:"path",shapeArgs:u(!0,g,{d:C[b](g.x,g.y,g.width,g.height)})};f&&(a.marker={width:g.width,height:g.height});m(a,k)});k(this,"afterTranslate")},pointAttribs:function(a,e){var b=x.prototype.pointAttribs.call(this,a,e),c=this.options||{},d=this.chart.options.plotOptions||{},g=d.series||{},k=d.heatmap||{};d=c.borderColor||k.borderColor||g.borderColor;g=c.borderWidth|| k.borderWidth||g.borderWidth||b["stroke-width"];b.stroke=a&&a.marker&&a.marker.lineColor||c.marker&&c.marker.lineColor||d||this.color;b["stroke-width"]=g;e&&(a=u(c.states[e],c.marker&&c.marker.states[e],a.options.states&&a.options.states[e]||{}),e=a.brightness,b.fill=a.color||h.color(b.fill).brighten(e||0).get(),b.stroke=a.lineColor);return b},markerAttribs:function(a,e){var b=a.marker||{},c=this.options.marker||{},d=a.shapeArgs||{},g={};if(a.hasImage)return{x:a.plotX,y:a.plotY};if(e){var k=c.states[e]|| {};var f=b.states&&b.states[e]||{};[["width","x"],["height","y"]].forEach(function(a){g[a[0]]=(f[a[0]]||k[a[0]]||d[a[0]])+(f[a[0]+"Plus"]||k[a[0]+"Plus"]||0);g[a[1]]=d[a[1]]+(d[a[0]]-g[a[0]])/2})}return e?g:d},drawPoints:function(){var a=this;if((this.options.marker||{}).enabled||this._hasPointMarkers)x.prototype.drawPoints.call(this),this.points.forEach(function(e){e.graphic&&e.graphic[a.chart.styledMode?"css":"animate"](a.colorAttribs(e))})},hasData:function(){return!!this.processedXData.length}, getValidPoints:function(a,e){return x.prototype.getValidPoints.call(this,a,e,!0)},getBox:y,drawLegendSymbol:q.drawRectangle,alignDataLabel:r.column.prototype.alignDataLabel,getExtremes:function(){var a=x.prototype.getExtremes.call(this,this.valueData),e=a.dataMin;a=a.dataMax;p(e)&&(this.valueMin=e);p(a)&&(this.valueMax=a);return x.prototype.getExtremes.call(this)}}),u(w,{applyOptions:function(a,e){a=h.Point.prototype.applyOptions.call(this,a,e);a.formatPrefix=a.isNull||null===a.value?"null":"point"; return a},isValid:function(){return Infinity!==this.value&&-Infinity!==this.value},haloPath:function(a){if(!a)return[];var e=this.shapeArgs;return["M",e.x-a,e.y-a,"L",e.x-a,e.y+e.height+a,e.x+e.width+a,e.y+e.height+a,e.x+e.width+a,e.y-a,"Z"]},getCellAttributes:function(){var a=this.series,e=a.options,b=(e.colsize||1)/2,c=(e.rowsize||1)/2,d=a.xAxis,k=a.yAxis,h=this.options.marker||a.options.marker;a=a.pointPlacementToXValue();var f=E(this.pointPadding,e.pointPadding,0),l={x1:A(Math.round(d.len-(d.translate(this.x- b,!1,!0,!1,!0,-a)||0)),-d.len,2*d.len),x2:A(Math.round(d.len-(d.translate(this.x+b,!1,!0,!1,!0,-a)||0)),-d.len,2*d.len),y1:A(Math.round(k.translate(this.y-c,!1,!0,!1,!0)||0),-k.len,2*k.len),y2:A(Math.round(k.translate(this.y+c,!1,!0,!1,!0)||0),-k.len,2*k.len)};[["width","x"],["height","y"]].forEach(function(a){var b=a[0];a=a[1];var d=a+"1",e=a+"2",c=Math.abs(l[d]-l[e]),k=h&&h.lineWidth||0,g=Math.abs(l[d]+l[e])/2;h[b]&&h[b]<c&&(l[d]=g-h[b]/2-k/2,l[e]=g+h[b]/2+k/2);f&&("y"===a&&(d=e,e=a+"1"),l[d]+= f,l[e]-=f)});return l}}));""});B(a,"Extensions/GeoJSON.js",[a["Core/Chart/Chart.js"],a["Core/Globals.js"],a["Core/Utilities.js"]],function(a,n,h){function q(a,c){var k,h=!1,m=a.x,n=a.y;a=0;for(k=c.length-1;a<c.length;k=a++){var q=c[a][1]>n;var g=c[k][1]>n;q!==g&&m<(c[k][0]-c[a][0])*(n-c[a][1])/(c[k][1]-c[a][1])+c[a][0]&&(h=!h)}return h}var c=n.win,r=h.error,w=h.extend,y=h.format,A=h.merge;h=h.wrap;"";a.prototype.transformFromLatLon=function(a,k){var h,m=(null===(h=this.userOptions.chart)||void 0=== h?void 0:h.proj4)||c.proj4;if(!m)return r(21,!1,this),{x:0,y:null};a=m(k.crs,[a.lon,a.lat]);h=k.cosAngle||k.rotation&&Math.cos(k.rotation);m=k.sinAngle||k.rotation&&Math.sin(k.rotation);a=k.rotation?[a[0]*h+a[1]*m,-a[0]*m+a[1]*h]:a;return{x:((a[0]-(k.xoffset||0))*(k.scale||1)+(k.xpan||0))*(k.jsonres||1)+(k.jsonmarginX||0),y:(((k.yoffset||0)-a[1])*(k.scale||1)+(k.ypan||0))*(k.jsonres||1)-(k.jsonmarginY||0)}};a.prototype.transformToLatLon=function(a,k){if("undefined"===typeof c.proj4)r(21,!1,this); else{a={x:((a.x-(k.jsonmarginX||0))/(k.jsonres||1)-(k.xpan||0))/(k.scale||1)+(k.xoffset||0),y:((-a.y-(k.jsonmarginY||0))/(k.jsonres||1)+(k.ypan||0))/(k.scale||1)+(k.yoffset||0)};var h=k.cosAngle||k.rotation&&Math.cos(k.rotation),m=k.sinAngle||k.rotation&&Math.sin(k.rotation);k=c.proj4(k.crs,"WGS84",k.rotation?{x:a.x*h+a.y*-m,y:a.x*m+a.y*h}:a);return{lat:k.y,lon:k.x}}};a.prototype.fromPointToLatLon=function(a){var c=this.mapTransforms,h;if(c){for(h in c)if(Object.hasOwnProperty.call(c,h)&&c[h].hitZone&& q({x:a.x,y:-a.y},c[h].hitZone.coordinates[0]))return this.transformToLatLon(a,c[h]);return this.transformToLatLon(a,c["default"])}r(22,!1,this)};a.prototype.fromLatLonToPoint=function(a){var c=this.mapTransforms,h;if(!c)return r(22,!1,this),{x:0,y:null};for(h in c)if(Object.hasOwnProperty.call(c,h)&&c[h].hitZone){var m=this.transformFromLatLon(a,c[h]);if(q({x:m.x,y:-m.y},c[h].hitZone.coordinates[0]))return m}return this.transformFromLatLon(a,c["default"])};n.geojson=function(a,c,h){var k=[],m=[], n=function(a){a.forEach(function(a,c){0===c?m.push(["M",a[0],-a[1]]):m.push(["L",a[0],-a[1]])})};c=c||"map";a.features.forEach(function(a){var g=a.geometry,e=g.type;g=g.coordinates;a=a.properties;var b;m=[];"map"===c||"mapbubble"===c?("Polygon"===e?(g.forEach(n),m.push(["Z"])):"MultiPolygon"===e&&(g.forEach(function(a){a.forEach(n)}),m.push(["Z"])),m.length&&(b={path:m})):"mapline"===c?("LineString"===e?n(g):"MultiLineString"===e&&g.forEach(n),m.length&&(b={path:m})):"mappoint"===c&&"Point"===e&& (b={x:g[0],y:-g[1]});b&&k.push(w(b,{name:a.name||a.NAME,properties:a}))});h&&a.copyrightShort&&(h.chart.mapCredits=y(h.chart.options.credits.mapText,{geojson:a}),h.chart.mapCreditsFull=y(h.chart.options.credits.mapTextFull,{geojson:a}));return k};h(a.prototype,"addCredits",function(a,c){c=A(!0,this.options.credits,c);this.mapCredits&&(c.href=null);a.call(this,c);this.credits&&this.mapCreditsFull&&this.credits.attr({title:this.mapCreditsFull})})});B(a,"masters/modules/map.src.js",[],function(){})}); //# sourceMappingURL=map.js.map
/* Highstock JS v9.3.2 (2021-11-29) Advanced Highcharts Stock tools (c) 2010-2021 Highsoft AS Author: Torstein Honsi License: www.highcharts.com/license */ 'use strict';(function(a){"object"===typeof module&&module.exports?(a["default"]=a,module.exports=a):"function"===typeof define&&define.amd?define("highcharts/modules/price-indicator",["highcharts","highcharts/modules/stock"],function(c){a(c);a.Highcharts=c;return a}):a("undefined"!==typeof Highcharts?Highcharts:void 0)})(function(a){function c(a,d,c,f){a.hasOwnProperty(d)||(a[d]=f.apply(null,c))}a=a?a._modules:{};c(a,"Extensions/PriceIndication.js",[a["Core/Series/Series.js"],a["Core/Utilities.js"]], function(a,c){var d=c.addEvent,f=c.isArray,m=c.merge;d(a,"afterRender",function(){var a=this.options,c=a.pointRange,d=a.lastVisiblePrice,e=a.lastPrice;if((d||e)&&"highcharts-navigator-series"!==a.id){var n=this.xAxis,b=this.yAxis,p=b.crosshair,q=b.cross,r=b.crossLabel,g=this.points,h=g.length,k=this.xData[this.xData.length-1],l=this.yData[this.yData.length-1];e&&e.enabled&&(b.crosshair=b.options.crosshair=a.lastPrice,!this.chart.styledMode&&b.crosshair&&b.options.crosshair&&a.lastPrice&&(b.crosshair.color= b.options.crosshair.color=a.lastPrice.color||this.color),b.cross=this.lastPrice,e=f(l)?l[3]:l,b.drawCrosshair(null,{x:k,y:e,plotX:n.toPixels(k,!0),plotY:b.toPixels(e,!0)}),this.yAxis.cross&&(this.lastPrice=this.yAxis.cross,this.lastPrice.addClass("highcharts-color-"+this.colorIndex),this.lastPrice.y=e));d&&d.enabled&&0<h&&(c=g[h-1].x===k||null===c?1:2,b.crosshair=b.options.crosshair=m({color:"transparent"},a.lastVisiblePrice),b.cross=this.lastVisiblePrice,a=g[h-c],this.crossLabel&&this.crossLabel.destroy(), delete b.crossLabel,b.drawCrosshair(null,a),b.cross&&(this.lastVisiblePrice=b.cross,"number"===typeof a.y&&(this.lastVisiblePrice.y=a.y)),this.crossLabel=b.crossLabel);b.crosshair=b.options.crosshair=p;b.cross=q;b.crossLabel=r}})});c(a,"masters/modules/price-indicator.src.js",[],function(){})}); //# sourceMappingURL=price-indicator.js.map
// @flow import { StyleSheet } from 'react-native' import { Colors, Metrics, Fonts, ApplicationStyles } from '../../Themes/' export default StyleSheet.create({ ...ApplicationStyles.screen, cardTitle: { alignSelf: 'center', fontSize: Fonts.size.regular, fontWeight: 'bold', marginVertical: Metrics.baseMargin, color: Colors.snow }, cardContainer: { backgroundColor: Colors.ember, borderColor: 'black', borderWidth: 1, borderRadius: 2, shadowColor: Colors.panther, shadowOffset: { height: 7, width: 7 }, shadowRadius: 2, paddingBottom: Metrics.baseMargin, margin: Metrics.baseMargin }, rowContainer: { flexDirection: 'row', borderColor: Colors.windowTint, borderWidth: 0.5, borderRadius: 2, marginHorizontal: Metrics.baseMargin }, rowLabelContainer: { flex: 1, justifyContent: 'center', backgroundColor: Colors.snow }, rowLabel: { fontWeight: 'bold', fontSize: Fonts.size.medium, marginVertical: Metrics.baseMargin, marginLeft: Metrics.baseMargin }, rowInfoContainer: { flex: 2, justifyContent: 'center', backgroundColor: Colors.silver }, rowInfo: { fontSize: Fonts.size.regular, margin: Metrics.baseMargin } })
this.onmessage = function (msg) { this.postMessage(msg.data); };
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v1.1.0-rc4-master-f9738f5 */ (function( window, angular, undefined ){ "use strict"; (function() { 'use strict'; angular.module('material.components.fabShared', ['material.core']) .controller('MdFabController', MdFabController); function MdFabController($scope, $element, $animate, $mdUtil, $mdConstant, $timeout) { var vm = this; // NOTE: We use async eval(s) below to avoid conflicts with any existing digest loops vm.open = function() { $scope.$evalAsync("vm.isOpen = true"); }; vm.close = function() { // Async eval to avoid conflicts with existing digest loops $scope.$evalAsync("vm.isOpen = false"); // Focus the trigger when the element closes so users can still tab to the next item $element.find('md-fab-trigger')[0].focus(); }; // Toggle the open/close state when the trigger is clicked vm.toggle = function() { $scope.$evalAsync("vm.isOpen = !vm.isOpen"); }; setupDefaults(); setupListeners(); setupWatchers(); var initialAnimationAttempts = 0; fireInitialAnimations(); function setupDefaults() { // Set the default direction to 'down' if none is specified vm.direction = vm.direction || 'down'; // Set the default to be closed vm.isOpen = vm.isOpen || false; // Start the keyboard interaction at the first action resetActionIndex(); // Add an animations waiting class so we know not to run $element.addClass('_md-animations-waiting'); } function setupListeners() { var eventTypes = [ 'click', 'focusin', 'focusout' ]; // Add our listeners angular.forEach(eventTypes, function(eventType) { $element.on(eventType, parseEvents); }); // Remove our listeners when destroyed $scope.$on('$destroy', function() { angular.forEach(eventTypes, function(eventType) { $element.off(eventType, parseEvents); }); // remove any attached keyboard handlers in case element is removed while // speed dial is open disableKeyboard(); }); } var closeTimeout; function parseEvents(event) { // If the event is a click, just handle it if (event.type == 'click') { handleItemClick(event); } // If we focusout, set a timeout to close the element if (event.type == 'focusout' && !closeTimeout) { closeTimeout = $timeout(function() { vm.close(); }, 100, false); } // If we see a focusin and there is a timeout about to run, cancel it so we stay open if (event.type == 'focusin' && closeTimeout) { $timeout.cancel(closeTimeout); closeTimeout = null; } } function resetActionIndex() { vm.currentActionIndex = -1; } function setupWatchers() { // Watch for changes to the direction and update classes/attributes $scope.$watch('vm.direction', function(newDir, oldDir) { // Add the appropriate classes so we can target the direction in the CSS $animate.removeClass($element, 'md-' + oldDir); $animate.addClass($element, 'md-' + newDir); // Reset the action index since it may have changed resetActionIndex(); }); var trigger, actions; // Watch for changes to md-open $scope.$watch('vm.isOpen', function(isOpen) { // Reset the action index since it may have changed resetActionIndex(); // We can't get the trigger/actions outside of the watch because the component hasn't been // linked yet, so we wait until the first watch fires to cache them. if (!trigger || !actions) { trigger = getTriggerElement(); actions = getActionsElement(); } if (isOpen) { enableKeyboard(); } else { disableKeyboard(); } var toAdd = isOpen ? 'md-is-open' : ''; var toRemove = isOpen ? '' : 'md-is-open'; // Set the proper ARIA attributes trigger.attr('aria-haspopup', true); trigger.attr('aria-expanded', isOpen); actions.attr('aria-hidden', !isOpen); // Animate the CSS classes $animate.setClass($element, toAdd, toRemove); }); } function fireInitialAnimations() { // If the element is actually visible on the screen if ($element[0].scrollHeight > 0) { // Fire our animation $animate.addClass($element, '_md-animations-ready').then(function() { // Remove the waiting class $element.removeClass('_md-animations-waiting'); }); } // Otherwise, try for up to 1 second before giving up else if (initialAnimationAttempts < 10) { $timeout(fireInitialAnimations, 100); // Increment our counter initialAnimationAttempts = initialAnimationAttempts + 1; } } function enableKeyboard() { $element.on('keydown', keyPressed); // On the next tick, setup a check for outside clicks; we do this on the next tick to avoid // clicks/touches that result in the isOpen attribute changing (e.g. a bound radio button) $mdUtil.nextTick(function() { angular.element(document).on('click touchend', checkForOutsideClick); }); // TODO: On desktop, we should be able to reset the indexes so you cannot tab through, but // this breaks accessibility, especially on mobile, since you have no arrow keys to press //resetActionTabIndexes(); } function disableKeyboard() { $element.off('keydown', keyPressed); angular.element(document).off('click touchend', checkForOutsideClick); } function checkForOutsideClick(event) { if (event.target) { var closestTrigger = $mdUtil.getClosest(event.target, 'md-fab-trigger'); var closestActions = $mdUtil.getClosest(event.target, 'md-fab-actions'); if (!closestTrigger && !closestActions) { vm.close(); } } } function keyPressed(event) { switch (event.which) { case $mdConstant.KEY_CODE.ESCAPE: vm.close(); event.preventDefault(); return false; case $mdConstant.KEY_CODE.LEFT_ARROW: doKeyLeft(event); return false; case $mdConstant.KEY_CODE.UP_ARROW: doKeyUp(event); return false; case $mdConstant.KEY_CODE.RIGHT_ARROW: doKeyRight(event); return false; case $mdConstant.KEY_CODE.DOWN_ARROW: doKeyDown(event); return false; } } function doActionPrev(event) { focusAction(event, -1); } function doActionNext(event) { focusAction(event, 1); } function focusAction(event, direction) { var actions = resetActionTabIndexes(); // Increment/decrement the counter with restrictions vm.currentActionIndex = vm.currentActionIndex + direction; vm.currentActionIndex = Math.min(actions.length - 1, vm.currentActionIndex); vm.currentActionIndex = Math.max(0, vm.currentActionIndex); // Focus the element var focusElement = angular.element(actions[vm.currentActionIndex]).children()[0]; angular.element(focusElement).attr('tabindex', 0); focusElement.focus(); // Make sure the event doesn't bubble and cause something else event.preventDefault(); event.stopImmediatePropagation(); } function resetActionTabIndexes() { // Grab all of the actions var actions = getActionsElement()[0].querySelectorAll('.md-fab-action-item'); // Disable all other actions for tabbing angular.forEach(actions, function(action) { angular.element(angular.element(action).children()[0]).attr('tabindex', -1); }); return actions; } function doKeyLeft(event) { if (vm.direction === 'left') { doActionNext(event); } else { doActionPrev(event); } } function doKeyUp(event) { if (vm.direction === 'down') { doActionPrev(event); } else { doActionNext(event); } } function doKeyRight(event) { if (vm.direction === 'left') { doActionPrev(event); } else { doActionNext(event); } } function doKeyDown(event) { if (vm.direction === 'up') { doActionPrev(event); } else { doActionNext(event); } } function isTrigger(element) { return $mdUtil.getClosest(element, 'md-fab-trigger'); } function isAction(element) { return $mdUtil.getClosest(element, 'md-fab-actions'); } function handleItemClick(event) { if (isTrigger(event.target)) { vm.toggle(); } if (isAction(event.target)) { vm.close(); } } function getTriggerElement() { return $element.find('md-fab-trigger'); } function getActionsElement() { return $element.find('md-fab-actions'); } } MdFabController.$inject = ["$scope", "$element", "$animate", "$mdUtil", "$mdConstant", "$timeout"]; })(); (function() { 'use strict'; /** * The duration of the CSS animation in milliseconds. * * @type {number} */ var cssAnimationDuration = 300; /** * @ngdoc module * @name material.components.fabSpeedDial */ angular // Declare our module .module('material.components.fabSpeedDial', [ 'material.core', 'material.components.fabShared', 'material.components.fabTrigger', 'material.components.fabActions' ]) // Register our directive .directive('mdFabSpeedDial', MdFabSpeedDialDirective) // Register our custom animations .animation('.md-fling', MdFabSpeedDialFlingAnimation) .animation('.md-scale', MdFabSpeedDialScaleAnimation) // Register a service for each animation so that we can easily inject them into unit tests .service('mdFabSpeedDialFlingAnimation', MdFabSpeedDialFlingAnimation) .service('mdFabSpeedDialScaleAnimation', MdFabSpeedDialScaleAnimation); /** * @ngdoc directive * @name mdFabSpeedDial * @module material.components.fabSpeedDial * * @restrict E * * @description * The `<md-fab-speed-dial>` directive is used to present a series of popup elements (usually * `<md-button>`s) for quick access to common actions. * * There are currently two animations available by applying one of the following classes to * the component: * * - `md-fling` - The speed dial items appear from underneath the trigger and move into their * appropriate positions. * - `md-scale` - The speed dial items appear in their proper places by scaling from 0% to 100%. * * You may also easily position the trigger by applying one one of the following classes to the * `<md-fab-speed-dial>` element: * - `md-fab-top-left` * - `md-fab-top-right` * - `md-fab-bottom-left` * - `md-fab-bottom-right` * * These CSS classes use `position: absolute`, so you need to ensure that the container element * also uses `position: absolute` or `position: relative` in order for them to work. * * Additionally, you may use the standard `ng-mouseenter` and `ng-mouseleave` directives to * open or close the speed dial. However, if you wish to allow users to hover over the empty * space where the actions will appear, you must also add the `md-hover-full` class to the speed * dial element. Without this, the hover effect will only occur on top of the trigger. * * See the demos for more information. * * ## Troubleshooting * * If your speed dial shows the closing animation upon launch, you may need to use `ng-cloak` on * the parent container to ensure that it is only visible once ready. We have plans to remove this * necessity in the future. * * @usage * <hljs lang="html"> * <md-fab-speed-dial md-direction="up" class="md-fling"> * <md-fab-trigger> * <md-button aria-label="Add..."><md-icon icon="/img/icons/plus.svg"></md-icon></md-button> * </md-fab-trigger> * * <md-fab-actions> * <md-button aria-label="Add User"> * <md-icon icon="/img/icons/user.svg"></md-icon> * </md-button> * * <md-button aria-label="Add Group"> * <md-icon icon="/img/icons/group.svg"></md-icon> * </md-button> * </md-fab-actions> * </md-fab-speed-dial> * </hljs> * * @param {string} md-direction From which direction you would like the speed dial to appear * relative to the trigger element. * @param {expression=} md-open Programmatically control whether or not the speed-dial is visible. */ function MdFabSpeedDialDirective() { return { restrict: 'E', scope: { direction: '@?mdDirection', isOpen: '=?mdOpen' }, bindToController: true, controller: 'MdFabController', controllerAs: 'vm', link: FabSpeedDialLink }; function FabSpeedDialLink(scope, element) { // Prepend an element to hold our CSS variables so we can use them in the animations below element.prepend('<div class="_md-css-variables"></div>'); } } function MdFabSpeedDialFlingAnimation($timeout) { function delayDone(done) { $timeout(done, cssAnimationDuration, false); } function runAnimation(element) { // Don't run if we are still waiting and we are not ready if (element.hasClass('_md-animations-waiting') && !element.hasClass('_md-animations-ready')) { return; } var el = element[0]; var ctrl = element.controller('mdFabSpeedDial'); var items = el.querySelectorAll('.md-fab-action-item'); // Grab our trigger element var triggerElement = el.querySelector('md-fab-trigger'); // Grab our element which stores CSS variables var variablesElement = el.querySelector('._md-css-variables'); // Setup JS variables based on our CSS variables var startZIndex = parseInt(window.getComputedStyle(variablesElement).zIndex); // Always reset the items to their natural position/state angular.forEach(items, function(item, index) { var styles = item.style; styles.transform = styles.webkitTransform = ''; styles.transitionDelay = ''; styles.opacity = 1; // Make the items closest to the trigger have the highest z-index styles.zIndex = (items.length - index) + startZIndex; }); // Set the trigger to be above all of the actions so they disappear behind it. triggerElement.style.zIndex = startZIndex + items.length + 1; // If the control is closed, hide the items behind the trigger if (!ctrl.isOpen) { angular.forEach(items, function(item, index) { var newPosition, axis; var styles = item.style; // Make sure to account for differences in the dimensions of the trigger verses the items // so that we can properly center everything; this helps hide the item's shadows behind // the trigger. var triggerItemHeightOffset = (triggerElement.clientHeight - item.clientHeight) / 2; var triggerItemWidthOffset = (triggerElement.clientWidth - item.clientWidth) / 2; switch (ctrl.direction) { case 'up': newPosition = (item.scrollHeight * (index + 1) + triggerItemHeightOffset); axis = 'Y'; break; case 'down': newPosition = -(item.scrollHeight * (index + 1) + triggerItemHeightOffset); axis = 'Y'; break; case 'left': newPosition = (item.scrollWidth * (index + 1) + triggerItemWidthOffset); axis = 'X'; break; case 'right': newPosition = -(item.scrollWidth * (index + 1) + triggerItemWidthOffset); axis = 'X'; break; } var newTranslate = 'translate' + axis + '(' + newPosition + 'px)'; styles.transform = styles.webkitTransform = newTranslate; }); } } return { addClass: function(element, className, done) { if (element.hasClass('md-fling')) { runAnimation(element); delayDone(done); } else { done(); } }, removeClass: function(element, className, done) { runAnimation(element); delayDone(done); } } } MdFabSpeedDialFlingAnimation.$inject = ["$timeout"]; function MdFabSpeedDialScaleAnimation($timeout) { function delayDone(done) { $timeout(done, cssAnimationDuration, false); } var delay = 65; function runAnimation(element) { var el = element[0]; var ctrl = element.controller('mdFabSpeedDial'); var items = el.querySelectorAll('.md-fab-action-item'); // Grab our element which stores CSS variables var variablesElement = el.querySelector('._md-css-variables'); // Setup JS variables based on our CSS variables var startZIndex = parseInt(window.getComputedStyle(variablesElement).zIndex); // Always reset the items to their natural position/state angular.forEach(items, function(item, index) { var styles = item.style, offsetDelay = index * delay; styles.opacity = ctrl.isOpen ? 1 : 0; styles.transform = styles.webkitTransform = ctrl.isOpen ? 'scale(1)' : 'scale(0)'; styles.transitionDelay = (ctrl.isOpen ? offsetDelay : (items.length - offsetDelay)) + 'ms'; // Make the items closest to the trigger have the highest z-index styles.zIndex = (items.length - index) + startZIndex; }); } return { addClass: function(element, className, done) { runAnimation(element); delayDone(done); }, removeClass: function(element, className, done) { runAnimation(element); delayDone(done); } } } MdFabSpeedDialScaleAnimation.$inject = ["$timeout"]; })(); })(window, window.angular);
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var common = require('../common.js'); var R = require('_stream_readable'); var assert = require('assert'); var util = require('util'); var EE = require('events').EventEmitter; function TestReader(n) { R.apply(this); this._buffer = new Buffer(n || 100); this._buffer.fill('x'); this._pos = 0; this._bufs = 10; } util.inherits(TestReader, R); TestReader.prototype._read = function(n) { var max = this._buffer.length - this._pos; n = Math.max(n, 0); var toRead = Math.min(n, max); if (toRead === 0) { // simulate the read buffer filling up with some more bytes some time // in the future. setTimeout(function() { this._pos = 0; this._bufs -= 1; if (this._bufs <= 0) { // read them all! if (!this.ended) this.push(null); } else { // now we have more. // kinda cheating by calling _read, but whatever, // it's just fake anyway. this._read(n); } }.bind(this), 10); return; } var ret = this._buffer.slice(this._pos, this._pos + toRead); this._pos += toRead; this.push(ret); }; ///// function TestWriter() { EE.apply(this); this.received = []; this.flush = false; } util.inherits(TestWriter, EE); TestWriter.prototype.write = function(c) { this.received.push(c.toString()); this.emit('write', c); return true; }; TestWriter.prototype.end = function(c) { if (c) this.write(c); this.emit('end', this.received); }; //////// // tiny node-tap lookalike. var tests = []; var count = 0; function test(name, fn) { count++; tests.push([name, fn]); } function run() { var next = tests.shift(); if (!next) return console.error('ok'); var name = next[0]; var fn = next[1]; console.log('# %s', name); fn({ same: assert.deepEqual, ok: assert, equal: assert.equal, end: function () { count--; run(); } }); } // ensure all tests have run process.on("exit", function () { assert.equal(count, 0); }); process.nextTick(run); test('a most basic test', function(t) { var r = new TestReader(20); var reads = []; var expect = [ 'x', 'xx', 'xxx', 'xxxx', 'xxxxx', 'xxxxxxxxx', 'xxxxxxxxxx', 'xxxxxxxxxxxx', 'xxxxxxxxxxxxx', 'xxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxxxxxxx', 'xxxxxxxxxxxxxxxxxxxxx' ]; r.on('end', function() { t.same(reads, expect); t.end(); }); var readSize = 1; function flow() { var res; while (null !== (res = r.read(readSize++))) { reads.push(res.toString()); } r.once('readable', flow); } flow(); }); test('pipe', function(t) { var r = new TestReader(5); var expect = [ 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx' ] var w = new TestWriter; var flush = true; w.on('end', function(received) { t.same(received, expect); t.end(); }); r.pipe(w); }); [1,2,3,4,5,6,7,8,9].forEach(function(SPLIT) { test('unpipe', function(t) { var r = new TestReader(5); // unpipe after 3 writes, then write to another stream instead. var expect = [ 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx' ]; expect = [ expect.slice(0, SPLIT), expect.slice(SPLIT) ]; var w = [ new TestWriter(), new TestWriter() ]; var writes = SPLIT; w[0].on('write', function() { if (--writes === 0) { r.unpipe(); t.equal(r._readableState.pipes, null); w[0].end(); r.pipe(w[1]); t.equal(r._readableState.pipes, w[1]); } }); var ended = 0; var ended0 = false; var ended1 = false; w[0].on('end', function(results) { t.equal(ended0, false); ended0 = true; ended++; t.same(results, expect[0]); }); w[1].on('end', function(results) { t.equal(ended1, false); ended1 = true; ended++; t.equal(ended, 2); t.same(results, expect[1]); t.end(); }); r.pipe(w[0]); }); }); // both writers should get the same exact data. test('multipipe', function(t) { var r = new TestReader(5); var w = [ new TestWriter, new TestWriter ]; var expect = [ 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx' ]; var c = 2; w[0].on('end', function(received) { t.same(received, expect, 'first'); if (--c === 0) t.end(); }); w[1].on('end', function(received) { t.same(received, expect, 'second'); if (--c === 0) t.end(); }); r.pipe(w[0]); r.pipe(w[1]); }); [1,2,3,4,5,6,7,8,9].forEach(function(SPLIT) { test('multi-unpipe', function(t) { var r = new TestReader(5); // unpipe after 3 writes, then write to another stream instead. var expect = [ 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx', 'xxxxx' ]; expect = [ expect.slice(0, SPLIT), expect.slice(SPLIT) ]; var w = [ new TestWriter(), new TestWriter(), new TestWriter() ]; var writes = SPLIT; w[0].on('write', function() { if (--writes === 0) { r.unpipe(); w[0].end(); r.pipe(w[1]); } }); var ended = 0; w[0].on('end', function(results) { ended++; t.same(results, expect[0]); }); w[1].on('end', function(results) { ended++; t.equal(ended, 2); t.same(results, expect[1]); t.end(); }); r.pipe(w[0]); r.pipe(w[2]); }); }); test('back pressure respected', function (t) { function noop() {} var r = new R({ objectMode: true }); r._read = noop; var counter = 0; r.push(["one"]); r.push(["two"]); r.push(["three"]); r.push(["four"]); r.push(null); var w1 = new R(); w1.write = function (chunk) { console.error('w1.emit("close")'); assert.equal(chunk[0], "one"); w1.emit("close"); process.nextTick(function () { r.pipe(w2); r.pipe(w3); }) }; w1.end = noop; r.pipe(w1); var expected = ["two", "two", "three", "three", "four", "four"]; var w2 = new R(); w2.write = function (chunk) { console.error('w2 write', chunk, counter); assert.equal(chunk[0], expected.shift()); assert.equal(counter, 0); counter++; if (chunk[0] === "four") { return true; } setTimeout(function () { counter--; console.error("w2 drain"); w2.emit("drain"); }, 10); return false; } w2.end = noop; var w3 = new R(); w3.write = function (chunk) { console.error('w3 write', chunk, counter); assert.equal(chunk[0], expected.shift()); assert.equal(counter, 1); counter++; if (chunk[0] === "four") { return true; } setTimeout(function () { counter--; console.error("w3 drain"); w3.emit("drain"); }, 50); return false; }; w3.end = function () { assert.equal(counter, 2); assert.equal(expected.length, 0); t.end(); }; }); test('read(0) for ended streams', function (t) { var r = new R(); var written = false; var ended = false; r._read = function (n) {}; r.push(new Buffer("foo")); r.push(null); var v = r.read(0); assert.equal(v, null); var w = new R(); w.write = function (buffer) { written = true; assert.equal(ended, false); assert.equal(buffer.toString(), "foo") }; w.end = function () { ended = true; assert.equal(written, true); t.end(); }; r.pipe(w); }) test('sync _read ending', function (t) { var r = new R(); var called = false; r._read = function (n) { r.push(null); }; r.once('end', function () { called = true; }) r.read(); process.nextTick(function () { assert.equal(called, true); t.end(); }) }); test('adding readable triggers data flow', function(t) { var r = new R({ highWaterMark: 5 }); var onReadable = false; var readCalled = 0; r._read = function(n) { if (readCalled++ === 2) r.push(null); else r.push(new Buffer('asdf')); }; var called = false; r.on('readable', function() { onReadable = true; r.read(); }); r.on('end', function() { t.equal(readCalled, 3); t.ok(onReadable); t.end(); }); }); test('chainable', function(t) { var r = new R(); r._read = function() {}; var r2 = r.setEncoding('utf8').pause().resume().pause(); t.equal(r, r2); t.end(); });
/** * A slider for numeric inputs. * * @see {@link module:pageflow/ui.pageflow.inputView pageflow.inputView} for options * @class * @memberof module:pageflow/ui */ pageflow.SliderInputView = Backbone.Marionette.ItemView.extend({ mixins: [pageflow.inputView], className: 'slider_input', template: 'pageflow/ui/templates/inputs/slider_input', ui: { widget: '.slider', value: '.value' }, events: { 'slidechange': 'save' }, onRender: function() { this.ui.widget.slider({ animate: 'fast', min: 'minValue' in this.options ? this.options.minValue : 0, max: 'maxValue' in this.options ? this.options.maxValue : 100, }); this.load(); }, save: function() { var value = this.ui.widget.slider('option', 'value'); var unit = 'unit' in this.options ? this.options.unit : '%'; this.ui.value.text(value + unit); this.model.set(this.options.propertyName, value); }, load: function() { var value; if (this.model.has(this.options.propertyName)) { value = this.model.get(this.options.propertyName) } else { value = 'defaultValue' in this.options ? this.options.defaultValue : 0 } this.ui.widget.slider('option', 'value', value); } });
'use strict'; var debug = require('debug')('eddystone'); var bleno = require('bleno'); var beacon = require('eddystone-beacon'); var uid = require('eddystone-uid'); var RandomMeasure = require('random-measure'); var PulseBeat = require('pulsebeat'); var assign = require('object-assign'); var TX_POWER_MODE_LOW = 1; var BEACON_PERIOD_LOWEST = 10; var defaultBeaconConfig = {}; var beaconConfig = {}; function createMeasurer(range) { return RandomMeasure.isRange(range) ? new RandomMeasure(range) : { measure: function() { return range; } }; } function advertise(opts) { var voltMeasurer = createMeasurer(opts.voltage); var tempMeasurer = createMeasurer(opts.temperature); var namespace = uid.toNamespace(opts.nid); var instanceId = uid.toBeaconId(opts.bid); var advertiseOpts = { tlmCount: 2, tlmPeriod: 10, txPowerLevel: beaconConfig.txPowerLevel }; var advertiers = new PulseBeat([ function() { debug('UID advertising with namespace: %s, instance ID: %s', namespace, instanceId); beacon.advertiseUid(namespace, instanceId, advertiseOpts); }, function() { debug('URL advertising with url: %s', beaconConfig.uri); beacon.advertiseUrl(beaconConfig.uri, advertiseOpts); }, function() { var volt = voltMeasurer.measure(); var temp = tempMeasurer.measure(); debug('TLM data has been updated, voltage: %s, temprature: %s', volt, temp); beacon.setBatteryVoltage(volt); beacon.setTemperature(temp); } ]); // start TLM advertising beacon.advertiseTlm(); // loop UID / URL advertising advertiers.beat({timeout: 2000, interval:true}); // bind to bleno events bleno.on('advertisingError', function (err) { debug('advertising has been failed', err); }); debug('UID / URL / TLM advertising has been started'); } function resetConfig() { beaconConfig = assign(defaultBeaconConfig); return beaconConfig; } function configure(done) { var config = require('eddystone-beacon-config'); // handle update event from configuration config.on('update', function (e) { if (e.name === 'reset' && e.value === 1) { debug('have got reset request, all of values will be updated to defaults'); config.configure(resetConfig()); } else { debug('%s has been updated %s', e.name, e.value); beaconConfig[e.name] = e.value; if (e.name === 'uriData') { debug('have got uri request, configuration mode will be terminated'); done(); } } }); config.on('disable', function (e) { debug('Have got zero-beacon-period to stop transmitting URL'); }); // change lock state to false config.unlock(); // starter advertising for configuration debug('beacon configuration service is starting'); config.advertise(beaconConfig, { periodLowest: BEACON_PERIOD_LOWEST }); } function start(opts) { // configure default data with options passing from cli beaconConfig = defaultBeaconConfig = assign({ config: false, name: 'Eddystone beacon emulator', uriData: opts.uri || 'https://goo.gl/r8iJqW', nid: '8b0ca750-e7a7-4e14-bd99-095477cb3e77', bid: 'bid001', voltage: 0, temperature: -128, flags: 0, txPowerMode: TX_POWER_MODE_LOW, txPowerLevel: -18, beaconPeriod: 1000 }, opts); // run advertising or configuration service if (opts.config) { configure(function () { advertise(beaconConfig); }); } else { advertise(beaconConfig); } } module.exports = { advertise: start };
'use strict'; describe('ngMock', function() { var noop = angular.noop; describe('TzDate', function() { function minutes(min) { return min * 60 * 1000; } it('should look like a Date', function() { var date = new angular.mock.TzDate(0,0); expect(angular.isDate(date)).toBe(true); }); it('should take millis as constructor argument', function() { expect(new angular.mock.TzDate(0, 0).getTime()).toBe(0); expect(new angular.mock.TzDate(0, 1283555108000).getTime()).toBe(1283555108000); }); it('should take dateString as constructor argument', function() { expect(new angular.mock.TzDate(0, '1970-01-01T00:00:00.000Z').getTime()).toBe(0); expect(new angular.mock.TzDate(0, '2010-09-03T23:05:08.023Z').getTime()).toBe(1283555108023); }); it('should fake getLocalDateString method', function() { //0 in -3h var t0 = new angular.mock.TzDate(-3, 0); expect(t0.toLocaleDateString()).toMatch('1970'); //0 in +0h var t1 = new angular.mock.TzDate(0, 0); expect(t1.toLocaleDateString()).toMatch('1970'); //0 in +3h var t2 = new angular.mock.TzDate(3, 0); expect(t2.toLocaleDateString()).toMatch('1969'); }); it('should fake toISOString method', function() { var date = new angular.mock.TzDate(-1, '2009-10-09T01:02:03.027Z'); if (new Date().toISOString) { expect(date.toISOString()).toEqual('2009-10-09T01:02:03.027Z'); } else { expect(date.toISOString).toBeUndefined(); } }); it('should fake getHours method', function() { // avoid going negative due to #5017, so use Jan 2, 1970 00:00 UTC var jan2 = 24 * 60 * 60 * 1000; //0:00 in -3h var t0 = new angular.mock.TzDate(-3, jan2); expect(t0.getHours()).toBe(3); //0:00 in +0h var t1 = new angular.mock.TzDate(0, jan2); expect(t1.getHours()).toBe(0); //0:00 in +3h var t2 = new angular.mock.TzDate(3, jan2); expect(t2.getHours()).toMatch(21); }); it('should fake getMinutes method', function() { //0:15 in -3h var t0 = new angular.mock.TzDate(-3, minutes(15)); expect(t0.getMinutes()).toBe(15); //0:15 in -3.25h var t0a = new angular.mock.TzDate(-3.25, minutes(15)); expect(t0a.getMinutes()).toBe(30); //0 in +0h var t1 = new angular.mock.TzDate(0, minutes(0)); expect(t1.getMinutes()).toBe(0); //0:15 in +0h var t1a = new angular.mock.TzDate(0, minutes(15)); expect(t1a.getMinutes()).toBe(15); //0:15 in +3h var t2 = new angular.mock.TzDate(3, minutes(15)); expect(t2.getMinutes()).toMatch(15); //0:15 in +3.25h var t2a = new angular.mock.TzDate(3.25, minutes(15)); expect(t2a.getMinutes()).toMatch(0); }); it('should fake getSeconds method', function() { //0 in -3h var t0 = new angular.mock.TzDate(-3, 0); expect(t0.getSeconds()).toBe(0); //0 in +0h var t1 = new angular.mock.TzDate(0, 0); expect(t1.getSeconds()).toBe(0); //0 in +3h var t2 = new angular.mock.TzDate(3, 0); expect(t2.getSeconds()).toMatch(0); }); it('should fake getMilliseconds method', function() { expect(new angular.mock.TzDate(0, '2010-09-03T23:05:08.003Z').getMilliseconds()).toBe(3); expect(new angular.mock.TzDate(0, '2010-09-03T23:05:08.023Z').getMilliseconds()).toBe(23); expect(new angular.mock.TzDate(0, '2010-09-03T23:05:08.123Z').getMilliseconds()).toBe(123); }); it('should create a date representing new year in Bratislava', function() { var newYearInBratislava = new angular.mock.TzDate(-1, '2009-12-31T23:00:00.000Z'); expect(newYearInBratislava.getTimezoneOffset()).toBe(-60); expect(newYearInBratislava.getFullYear()).toBe(2010); expect(newYearInBratislava.getMonth()).toBe(0); expect(newYearInBratislava.getDate()).toBe(1); expect(newYearInBratislava.getHours()).toBe(0); expect(newYearInBratislava.getMinutes()).toBe(0); expect(newYearInBratislava.getSeconds()).toBe(0); }); it('should delegate all the UTC methods to the original UTC Date object', function() { //from when created from string var date1 = new angular.mock.TzDate(-1, '2009-12-31T23:00:00.000Z'); expect(date1.getUTCFullYear()).toBe(2009); expect(date1.getUTCMonth()).toBe(11); expect(date1.getUTCDate()).toBe(31); expect(date1.getUTCHours()).toBe(23); expect(date1.getUTCMinutes()).toBe(0); expect(date1.getUTCSeconds()).toBe(0); //from when created from millis var date2 = new angular.mock.TzDate(-1, date1.getTime()); expect(date2.getUTCFullYear()).toBe(2009); expect(date2.getUTCMonth()).toBe(11); expect(date2.getUTCDate()).toBe(31); expect(date2.getUTCHours()).toBe(23); expect(date2.getUTCMinutes()).toBe(0); expect(date2.getUTCSeconds()).toBe(0); }); it('should throw error when no third param but toString called', function() { expect(function() { new angular.mock.TzDate(0,0).toString(); }). toThrow('Method \'toString\' is not implemented in the TzDate mock'); }); }); describe('$log', function() { angular.forEach([true, false], function(debugEnabled) { describe('debug ' + debugEnabled, function() { beforeEach(module(function($logProvider) { $logProvider.debugEnabled(debugEnabled); })); afterEach(inject(function($log) { $log.reset(); })); it("should skip debugging output if disabled (" + debugEnabled + ")", inject(function($log) { $log.log('fake log'); $log.info('fake log'); $log.warn('fake log'); $log.error('fake log'); $log.debug('fake log'); expect($log.log.logs).toContain(['fake log']); expect($log.info.logs).toContain(['fake log']); expect($log.warn.logs).toContain(['fake log']); expect($log.error.logs).toContain(['fake log']); if (debugEnabled) { expect($log.debug.logs).toContain(['fake log']); } else { expect($log.debug.logs).toEqual([]); } })); }); }); describe('debug enabled (default)', function() { var $log; beforeEach(inject(['$log', function(log) { $log = log; }])); afterEach(inject(function($log) { $log.reset(); })); it('should provide the log method', function() { expect(function() { $log.log(''); }).not.toThrow(); }); it('should provide the info method', function() { expect(function() { $log.info(''); }).not.toThrow(); }); it('should provide the warn method', function() { expect(function() { $log.warn(''); }).not.toThrow(); }); it('should provide the error method', function() { expect(function() { $log.error(''); }).not.toThrow(); }); it('should provide the debug method', function() { expect(function() { $log.debug(''); }).not.toThrow(); }); it('should store log messages', function() { $log.log('fake log'); expect($log.log.logs).toContain(['fake log']); }); it('should store info messages', function() { $log.info('fake log'); expect($log.info.logs).toContain(['fake log']); }); it('should store warn messages', function() { $log.warn('fake log'); expect($log.warn.logs).toContain(['fake log']); }); it('should store error messages', function() { $log.error('fake log'); expect($log.error.logs).toContain(['fake log']); }); it('should store debug messages', function() { $log.debug('fake log'); expect($log.debug.logs).toContain(['fake log']); }); it('should assertEmpty', function() { try { $log.error(new Error('MyError')); $log.warn(new Error('MyWarn')); $log.info(new Error('MyInfo')); $log.log(new Error('MyLog')); $log.debug(new Error('MyDebug')); $log.assertEmpty(); } catch (error) { var err = error.message || error; expect(err).toMatch(/Error: MyError/m); expect(err).toMatch(/Error: MyWarn/m); expect(err).toMatch(/Error: MyInfo/m); expect(err).toMatch(/Error: MyLog/m); expect(err).toMatch(/Error: MyDebug/m); } finally { $log.reset(); } }); it('should reset state', function() { $log.error(new Error('MyError')); $log.warn(new Error('MyWarn')); $log.info(new Error('MyInfo')); $log.log(new Error('MyLog')); $log.reset(); var passed = false; try { $log.assertEmpty(); // should not throw error! passed = true; } catch (e) { passed = e; } expect(passed).toBe(true); }); }); }); describe('$interval', function() { it('should run tasks repeatedly', inject(function($interval) { var counter = 0; $interval(function() { counter++; }, 1000); expect(counter).toBe(0); $interval.flush(1000); expect(counter).toBe(1); $interval.flush(1000); expect(counter).toBe(2); })); it('should call $apply after each task is executed', inject(function($interval, $rootScope) { var applySpy = spyOn($rootScope, '$apply').andCallThrough(); $interval(noop, 1000); expect(applySpy).not.toHaveBeenCalled(); $interval.flush(1000); expect(applySpy).toHaveBeenCalledOnce(); applySpy.reset(); $interval(noop, 1000); $interval(noop, 1000); $interval.flush(1000); expect(applySpy.callCount).toBe(3); })); it('should NOT call $apply if invokeApply is set to false', inject(function($interval, $rootScope) { var applySpy = spyOn($rootScope, '$apply').andCallThrough(); var counter = 0; $interval(function increment() { counter++; }, 1000, 0, false); expect(applySpy).not.toHaveBeenCalled(); expect(counter).toBe(0); $interval.flush(2000); expect(applySpy).not.toHaveBeenCalled(); expect(counter).toBe(2); })); it('should allow you to specify the delay time', inject(function($interval) { var counter = 0; $interval(function() { counter++; }, 123); expect(counter).toBe(0); $interval.flush(122); expect(counter).toBe(0); $interval.flush(1); expect(counter).toBe(1); })); it('should allow you to specify a number of iterations', inject(function($interval) { var counter = 0; $interval(function() {counter++;}, 1000, 2); $interval.flush(1000); expect(counter).toBe(1); $interval.flush(1000); expect(counter).toBe(2); $interval.flush(1000); expect(counter).toBe(2); })); describe('flush', function() { it('should move the clock forward by the specified time', inject(function($interval) { var counterA = 0; var counterB = 0; $interval(function() { counterA++; }, 100); $interval(function() { counterB++; }, 401); $interval.flush(200); expect(counterA).toEqual(2); $interval.flush(201); expect(counterA).toEqual(4); expect(counterB).toEqual(1); })); }); it('should return a promise which will be updated with the count on each iteration', inject(function($interval) { var log = [], promise = $interval(function() { log.push('tick'); }, 1000); promise.then(function(value) { log.push('promise success: ' + value); }, function(err) { log.push('promise error: ' + err); }, function(note) { log.push('promise update: ' + note); }); expect(log).toEqual([]); $interval.flush(1000); expect(log).toEqual(['tick', 'promise update: 0']); $interval.flush(1000); expect(log).toEqual(['tick', 'promise update: 0', 'tick', 'promise update: 1']); })); it('should return a promise which will be resolved after the specified number of iterations', inject(function($interval) { var log = [], promise = $interval(function() { log.push('tick'); }, 1000, 2); promise.then(function(value) { log.push('promise success: ' + value); }, function(err) { log.push('promise error: ' + err); }, function(note) { log.push('promise update: ' + note); }); expect(log).toEqual([]); $interval.flush(1000); expect(log).toEqual(['tick', 'promise update: 0']); $interval.flush(1000); expect(log).toEqual([ 'tick', 'promise update: 0', 'tick', 'promise update: 1', 'promise success: 2' ]); })); describe('exception handling', function() { beforeEach(module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); })); it('should delegate exception to the $exceptionHandler service', inject( function($interval, $exceptionHandler) { $interval(function() { throw "Test Error"; }, 1000); expect($exceptionHandler.errors).toEqual([]); $interval.flush(1000); expect($exceptionHandler.errors).toEqual(["Test Error"]); $interval.flush(1000); expect($exceptionHandler.errors).toEqual(["Test Error", "Test Error"]); })); it('should call $apply even if an exception is thrown in callback', inject( function($interval, $rootScope) { var applySpy = spyOn($rootScope, '$apply').andCallThrough(); $interval(function() { throw "Test Error"; }, 1000); expect(applySpy).not.toHaveBeenCalled(); $interval.flush(1000); expect(applySpy).toHaveBeenCalled(); })); it('should still update the interval promise when an exception is thrown', inject(function($interval) { var log = [], promise = $interval(function() { throw "Some Error"; }, 1000); promise.then(function(value) { log.push('promise success: ' + value); }, function(err) { log.push('promise error: ' + err); }, function(note) { log.push('promise update: ' + note); }); $interval.flush(1000); expect(log).toEqual(['promise update: 0']); })); }); describe('cancel', function() { it('should cancel tasks', inject(function($interval) { var task1 = jasmine.createSpy('task1', 1000), task2 = jasmine.createSpy('task2', 1000), task3 = jasmine.createSpy('task3', 1000), promise1, promise3; promise1 = $interval(task1, 200); $interval(task2, 1000); promise3 = $interval(task3, 333); $interval.cancel(promise3); $interval.cancel(promise1); $interval.flush(1000); expect(task1).not.toHaveBeenCalled(); expect(task2).toHaveBeenCalledOnce(); expect(task3).not.toHaveBeenCalled(); })); it('should cancel the promise', inject(function($interval, $rootScope) { var promise = $interval(noop, 1000), log = []; promise.then(function(value) { log.push('promise success: ' + value); }, function(err) { log.push('promise error: ' + err); }, function(note) { log.push('promise update: ' + note); }); expect(log).toEqual([]); $interval.flush(1000); $interval.cancel(promise); $interval.flush(1000); $rootScope.$apply(); // For resolving the promise - // necessary since q uses $rootScope.evalAsync. expect(log).toEqual(['promise update: 0', 'promise error: canceled']); })); it('should return true if a task was successfully canceled', inject(function($interval) { var task1 = jasmine.createSpy('task1'), task2 = jasmine.createSpy('task2'), promise1, promise2; promise1 = $interval(task1, 1000, 1); $interval.flush(1000); promise2 = $interval(task2, 1000, 1); expect($interval.cancel(promise1)).toBe(false); expect($interval.cancel(promise2)).toBe(true); })); it('should not throw a runtime exception when given an undefined promise', inject(function($interval) { var task1 = jasmine.createSpy('task1'), promise1; promise1 = $interval(task1, 1000, 1); expect($interval.cancel()).toBe(false); })); }); }); describe('defer', function() { var browser, log; beforeEach(inject(function($browser) { browser = $browser; log = ''; })); function logFn(text) { return function() { log += text + ';'; }; } it('should flush', function() { browser.defer(logFn('A')); expect(log).toEqual(''); browser.defer.flush(); expect(log).toEqual('A;'); }); it('should flush delayed', function() { browser.defer(logFn('A')); browser.defer(logFn('B'), 10); browser.defer(logFn('C'), 20); expect(log).toEqual(''); expect(browser.defer.now).toEqual(0); browser.defer.flush(0); expect(log).toEqual('A;'); browser.defer.flush(); expect(log).toEqual('A;B;C;'); }); it('should defer and flush over time', function() { browser.defer(logFn('A'), 1); browser.defer(logFn('B'), 2); browser.defer(logFn('C'), 3); browser.defer.flush(0); expect(browser.defer.now).toEqual(0); expect(log).toEqual(''); browser.defer.flush(1); expect(browser.defer.now).toEqual(1); expect(log).toEqual('A;'); browser.defer.flush(2); expect(browser.defer.now).toEqual(3); expect(log).toEqual('A;B;C;'); }); it('should throw an exception if there is nothing to be flushed', function() { expect(function() {browser.defer.flush();}).toThrow('No deferred tasks to be flushed'); }); }); describe('$exceptionHandler', function() { it('should rethrow exceptions', inject(function($exceptionHandler) { expect(function() { $exceptionHandler('myException'); }).toThrow('myException'); })); it('should log exceptions', function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('log'); }); inject(function($exceptionHandler) { $exceptionHandler('MyError'); expect($exceptionHandler.errors).toEqual(['MyError']); $exceptionHandler('MyError', 'comment'); expect($exceptionHandler.errors[1]).toEqual(['MyError', 'comment']); }); }); it('should log and rethrow exceptions', function() { module(function($exceptionHandlerProvider) { $exceptionHandlerProvider.mode('rethrow'); }); inject(function($exceptionHandler) { expect(function() { $exceptionHandler('MyError'); }).toThrow('MyError'); expect($exceptionHandler.errors).toEqual(['MyError']); expect(function() { $exceptionHandler('MyError', 'comment'); }).toThrow('MyError'); expect($exceptionHandler.errors[1]).toEqual(['MyError', 'comment']); }); }); it('should throw on wrong argument', function() { module(function($exceptionHandlerProvider) { expect(function() { $exceptionHandlerProvider.mode('XXX'); }).toThrow("Unknown mode 'XXX', only 'log'/'rethrow' modes are allowed!"); }); inject(); // Trigger the tests in `module` }); }); describe('$timeout', function() { it('should expose flush method that will flush the pending queue of tasks', inject( function($timeout) { var logger = [], logFn = function(msg) { return function() { logger.push(msg); }; }; $timeout(logFn('t1')); $timeout(logFn('t2'), 200); $timeout(logFn('t3')); expect(logger).toEqual([]); $timeout.flush(); expect(logger).toEqual(['t1', 't3', 't2']); })); it('should throw an exception when not flushed', inject(function($timeout) { $timeout(noop); var expectedError = 'Deferred tasks to flush (1): {id: 0, time: 0}'; expect(function() {$timeout.verifyNoPendingTasks();}).toThrow(expectedError); })); it('should do nothing when all tasks have been flushed', inject(function($timeout) { $timeout(noop); $timeout.flush(); expect(function() {$timeout.verifyNoPendingTasks();}).not.toThrow(); })); it('should check against the delay if provided within timeout', inject(function($timeout) { $timeout(noop, 100); $timeout.flush(100); expect(function() {$timeout.verifyNoPendingTasks();}).not.toThrow(); $timeout(noop, 1000); $timeout.flush(100); expect(function() {$timeout.verifyNoPendingTasks();}).toThrow(); $timeout.flush(900); expect(function() {$timeout.verifyNoPendingTasks();}).not.toThrow(); })); it('should assert against the delay value', inject(function($timeout) { var count = 0; var iterate = function() { count++; }; $timeout(iterate, 100); $timeout(iterate, 123); $timeout.flush(100); expect(count).toBe(1); $timeout.flush(123); expect(count).toBe(2); })); }); describe('angular.mock.dump', function() { var d = angular.mock.dump; it('should serialize primitive types', function() { expect(d(undefined)).toEqual('undefined'); expect(d(1)).toEqual('1'); expect(d(null)).toEqual('null'); expect(d('abc')).toEqual('abc'); }); it('should serialize element', function() { var e = angular.element('<div>abc</div><span>xyz</span>'); expect(d(e).toLowerCase()).toEqual('<div>abc</div><span>xyz</span>'); expect(d(e[0]).toLowerCase()).toEqual('<div>abc</div>'); }); it('should serialize scope', inject(function($rootScope) { $rootScope.obj = {abc:'123'}; expect(d($rootScope)).toMatch(/Scope\(.*\): \{/); expect(d($rootScope)).toMatch(/{"abc":"123"}/); })); it('should serialize scope that has overridden "hasOwnProperty"', inject(function($rootScope, $sniffer) { /* jshint -W001 */ $rootScope.hasOwnProperty = 'X'; expect(d($rootScope)).toMatch(/Scope\(.*\): \{/); expect(d($rootScope)).toMatch(/hasOwnProperty: "X"/); })); }); describe('jasmine module and inject', function() { var log; beforeEach(function() { log = ''; }); describe('module', function() { describe('object literal format', function() { var mock = { log: 'module' }; beforeEach(function() { module({ 'service': mock, 'other': { some: 'replacement'} }, 'ngResource', function($provide) { $provide.value('example', 'win'); } ); }); it('should inject the mocked module', function() { inject(function(service) { expect(service).toEqual(mock); }); }); it('should support multiple key value pairs', function() { inject(function(service, other) { expect(other.some).toEqual('replacement'); expect(service).toEqual(mock); }); }); it('should integrate with string and function', function() { inject(function(service, $resource, example) { expect(service).toEqual(mock); expect($resource).toBeDefined(); expect(example).toEqual('win'); }); }); describe('module cleanup', function() { function testFn() { } it('should add hashKey to module function', function() { module(testFn); inject(function() { expect(testFn.$$hashKey).toBeDefined(); }); }); it('should cleanup hashKey after previous test', function() { expect(testFn.$$hashKey).toBeUndefined(); }); }); describe('$inject cleanup', function() { function testFn() { } it('should add $inject when invoking test function', inject(function($injector) { $injector.invoke(testFn); expect(testFn.$inject).toBeDefined(); })); it('should cleanup $inject after previous test', function() { expect(testFn.$inject).toBeUndefined(); }); it('should add $inject when annotating test function', inject(function($injector) { $injector.annotate(testFn); expect(testFn.$inject).toBeDefined(); })); it('should cleanup $inject after previous test', function() { expect(testFn.$inject).toBeUndefined(); }); it('should invoke an already annotated function', inject(function($injector) { testFn.$inject = []; $injector.invoke(testFn); })); it('should not cleanup $inject after previous test', function() { expect(testFn.$inject).toBeDefined(); }); }); }); describe('in DSL', function() { it('should load module', module(function() { log += 'module'; })); afterEach(function() { inject(); expect(log).toEqual('module'); }); }); describe('nested calls', function() { it('should invoke nested module calls immediately', function() { module(function($provide) { $provide.constant('someConst', 'blah'); module(function(someConst) { log = someConst; }); }); inject(function() { expect(log).toBe('blah'); }); }); }); describe('inline in test', function() { it('should load module', function() { module(function() { log += 'module'; }); inject(); }); afterEach(function() { expect(log).toEqual('module'); }); }); }); describe('inject', function() { describe('in DSL', function() { it('should load module', inject(function() { log += 'inject'; })); afterEach(function() { expect(log).toEqual('inject'); }); }); describe('inline in test', function() { it('should load module', function() { inject(function() { log += 'inject'; }); }); afterEach(function() { expect(log).toEqual('inject'); }); }); describe('module with inject', function() { beforeEach(module(function() { log += 'module;'; })); it('should inject', inject(function() { log += 'inject;'; })); afterEach(function() { expect(log).toEqual('module;inject;'); }); }); describe('this', function() { it('should set `this` to be the jasmine context', inject(function() { expect(this instanceof jasmine.Spec).toBe(true); })); it('should set `this` to be the jasmine context when inlined in a test', function() { var tested = false; inject(function() { expect(this instanceof jasmine.Spec).toBe(true); tested = true; }); expect(tested).toBe(true); }); }); it('should not change thrown Errors', inject(function($sniffer) { expect(function() { inject(function() { throw new Error('test message'); }); }).toThrow('test message'); })); it('should not change thrown strings', inject(function($sniffer) { expect(function() { inject(function() { throw 'test message'; }); }).toThrow('test message'); })); }); }); describe('$httpBackend', function() { var hb, callback, realBackendSpy; beforeEach(inject(function($httpBackend) { callback = jasmine.createSpy('callback'); hb = $httpBackend; })); it('should provide "expect" methods for each HTTP verb', function() { expect(typeof hb.expectGET).toBe("function"); expect(typeof hb.expectPOST).toBe("function"); expect(typeof hb.expectPUT).toBe("function"); expect(typeof hb.expectPATCH).toBe("function"); expect(typeof hb.expectDELETE).toBe("function"); expect(typeof hb.expectHEAD).toBe("function"); }); it('should provide "when" methods for each HTTP verb', function() { expect(typeof hb.whenGET).toBe("function"); expect(typeof hb.whenPOST).toBe("function"); expect(typeof hb.whenPUT).toBe("function"); expect(typeof hb.whenPATCH).toBe("function"); expect(typeof hb.whenDELETE).toBe("function"); expect(typeof hb.whenHEAD).toBe("function"); }); it('should provide "route" shortcuts for expect and when', function() { expect(typeof hb.whenRoute).toBe("function"); expect(typeof hb.expectRoute).toBe("function"); }); it('should respond with first matched definition', function() { hb.when('GET', '/url1').respond(200, 'content', {}); hb.when('GET', '/url1').respond(201, 'another', {}); callback.andCallFake(function(status, response) { expect(status).toBe(200); expect(response).toBe('content'); }); hb('GET', '/url1', null, callback); expect(callback).not.toHaveBeenCalled(); hb.flush(); expect(callback).toHaveBeenCalledOnce(); }); it('should respond with a copy of the mock data', function() { var mockObject = {a: 'b'}; hb.when('GET', '/url1').respond(200, mockObject, {}); callback.andCallFake(function(status, response) { expect(status).toBe(200); expect(response).toEqual({a: 'b'}); expect(response).not.toBe(mockObject); response.a = 'c'; }); hb('GET', '/url1', null, callback); hb.flush(); expect(callback).toHaveBeenCalledOnce(); // Fire it again and verify that the returned mock data has not been // modified. callback.reset(); hb('GET', '/url1', null, callback); hb.flush(); expect(callback).toHaveBeenCalledOnce(); expect(mockObject).toEqual({a: 'b'}); }); it('should throw error when unexpected request', function() { hb.when('GET', '/url1').respond(200, 'content'); expect(function() { hb('GET', '/xxx'); }).toThrow('Unexpected request: GET /xxx\nNo more request expected'); }); it('should match headers if specified', function() { hb.when('GET', '/url', null, {'X': 'val1'}).respond(201, 'content1'); hb.when('GET', '/url', null, {'X': 'val2'}).respond(202, 'content2'); hb.when('GET', '/url').respond(203, 'content3'); hb('GET', '/url', null, function(status, response) { expect(status).toBe(203); expect(response).toBe('content3'); }); hb('GET', '/url', null, function(status, response) { expect(status).toBe(201); expect(response).toBe('content1'); }, {'X': 'val1'}); hb('GET', '/url', null, function(status, response) { expect(status).toBe(202); expect(response).toBe('content2'); }, {'X': 'val2'}); hb.flush(); }); it('should match data if specified', function() { hb.when('GET', '/a/b', '{a: true}').respond(201, 'content1'); hb.when('GET', '/a/b').respond(202, 'content2'); hb('GET', '/a/b', '{a: true}', function(status, response) { expect(status).toBe(201); expect(response).toBe('content1'); }); hb('GET', '/a/b', null, function(status, response) { expect(status).toBe(202); expect(response).toBe('content2'); }); hb.flush(); }); it('should match data object if specified', function() { hb.when('GET', '/a/b', {a: 1, b: 2}).respond(201, 'content1'); hb.when('GET', '/a/b').respond(202, 'content2'); hb('GET', '/a/b', '{"a":1,"b":2}', function(status, response) { expect(status).toBe(201); expect(response).toBe('content1'); }); hb('GET', '/a/b', '{"b":2,"a":1}', function(status, response) { expect(status).toBe(201); expect(response).toBe('content1'); }); hb('GET', '/a/b', null, function(status, response) { expect(status).toBe(202); expect(response).toBe('content2'); }); hb.flush(); }); it('should match only method', function() { hb.when('GET').respond(202, 'c'); callback.andCallFake(function(status, response) { expect(status).toBe(202); expect(response).toBe('c'); }); hb('GET', '/some', null, callback, {}); hb('GET', '/another', null, callback, {'X-Fake': 'Header'}); hb('GET', '/third', 'some-data', callback, {}); hb.flush(); expect(callback).toHaveBeenCalled(); }); it('should preserve the order of requests', function() { hb.when('GET', '/url1').respond(200, 'first'); hb.when('GET', '/url2').respond(201, 'second'); hb('GET', '/url2', null, callback); hb('GET', '/url1', null, callback); hb.flush(); expect(callback.callCount).toBe(2); expect(callback.argsForCall[0]).toEqual([201, 'second', '', '']); expect(callback.argsForCall[1]).toEqual([200, 'first', '', '']); }); describe('respond()', function() { it('should take values', function() { hb.expect('GET', '/url1').respond(200, 'first', {'header': 'val'}, 'OK'); hb('GET', '/url1', undefined, callback); hb.flush(); expect(callback).toHaveBeenCalledOnceWith(200, 'first', 'header: val', 'OK'); }); it('should default status code to 200', function() { callback.andCallFake(function(status, response) { expect(status).toBe(200); expect(response).toBe('some-data'); }); hb.expect('GET', '/url1').respond('some-data'); hb.expect('GET', '/url2').respond('some-data', {'X-Header': 'true'}); hb('GET', '/url1', null, callback); hb('GET', '/url2', null, callback); hb.flush(); expect(callback).toHaveBeenCalled(); expect(callback.callCount).toBe(2); }); it('should default status code to 200 and provide status text', function() { hb.expect('GET', '/url1').respond('first', {'header': 'val'}, 'OK'); hb('GET', '/url1', null, callback); hb.flush(); expect(callback).toHaveBeenCalledOnceWith(200, 'first', 'header: val', 'OK'); }); it('should take function', function() { hb.expect('GET', '/some?q=s').respond(function(m, u, d, h, p) { return [301, m + u + ';' + d + ';a=' + h.a + ';q=' + p.q, {'Connection': 'keep-alive'}, 'Moved Permanently']; }); hb('GET', '/some?q=s', 'data', callback, {a: 'b'}); hb.flush(); expect(callback).toHaveBeenCalledOnceWith(301, 'GET/some?q=s;data;a=b;q=s', 'Connection: keep-alive', 'Moved Permanently'); }); it('should decode query parameters in respond() function', function() { hb.expect('GET', '/url?query=l%E2%80%A2ng%20string%20w%2F%20spec%5Eal%20char%24&id=1234&orderBy=-name') .respond(function(m, u, d, h, p) { return [200, "id=" + p.id + ";orderBy=" + p.orderBy + ";query=" + p.query]; }); hb('GET', '/url?query=l%E2%80%A2ng%20string%20w%2F%20spec%5Eal%20char%24&id=1234&orderBy=-name', null, callback); hb.flush(); expect(callback).toHaveBeenCalledOnceWith(200, 'id=1234;orderBy=-name;query=l•ng string w/ spec^al char$', '', ''); }); it('should include regex captures in respond() params when keys provided', function() { hb.expect('GET', /\/(.+)\/article\/(.+)/, undefined, undefined, ['id', 'name']) .respond(function(m, u, d, h, p) { return [200, "id=" + p.id + ";name=" + p.name]; }); hb('GET', '/1234/article/cool-angular-article', null, callback); hb.flush(); expect(callback).toHaveBeenCalledOnceWith(200, 'id=1234;name=cool-angular-article', '', ''); }); it('should default response headers to ""', function() { hb.expect('GET', '/url1').respond(200, 'first'); hb.expect('GET', '/url2').respond('second'); hb('GET', '/url1', null, callback); hb('GET', '/url2', null, callback); hb.flush(); expect(callback.callCount).toBe(2); expect(callback.argsForCall[0]).toEqual([200, 'first', '', '']); expect(callback.argsForCall[1]).toEqual([200, 'second', '', '']); }); it('should be able to override response of expect definition', function() { var definition = hb.expect('GET', '/url1'); definition.respond('first'); definition.respond('second'); hb('GET', '/url1', null, callback); hb.flush(); expect(callback).toHaveBeenCalledOnceWith(200, 'second', '', ''); }); it('should be able to override response of when definition', function() { var definition = hb.when('GET', '/url1'); definition.respond('first'); definition.respond('second'); hb('GET', '/url1', null, callback); hb.flush(); expect(callback).toHaveBeenCalledOnceWith(200, 'second', '', ''); }); it('should be able to override response of expect definition with chaining', function() { var definition = hb.expect('GET', '/url1').respond('first'); definition.respond('second'); hb('GET', '/url1', null, callback); hb.flush(); expect(callback).toHaveBeenCalledOnceWith(200, 'second', '', ''); }); it('should be able to override response of when definition with chaining', function() { var definition = hb.when('GET', '/url1').respond('first'); definition.respond('second'); hb('GET', '/url1', null, callback); hb.flush(); expect(callback).toHaveBeenCalledOnceWith(200, 'second', '', ''); }); }); describe('expect()', function() { it('should require specified order', function() { hb.expect('GET', '/url1').respond(200, ''); hb.expect('GET', '/url2').respond(200, ''); expect(function() { hb('GET', '/url2', null, noop, {}); }).toThrow('Unexpected request: GET /url2\nExpected GET /url1'); }); it('should have precedence over when()', function() { callback.andCallFake(function(status, response) { expect(status).toBe(300); expect(response).toBe('expect'); }); hb.when('GET', '/url').respond(200, 'when'); hb.expect('GET', '/url').respond(300, 'expect'); hb('GET', '/url', null, callback, {}); hb.flush(); expect(callback).toHaveBeenCalledOnce(); }); it('should throw exception when only headers differs from expectation', function() { hb.when('GET').respond(200, '', {}); hb.expect('GET', '/match', undefined, {'Content-Type': 'application/json'}); expect(function() { hb('GET', '/match', null, noop, {}); }).toThrow('Expected GET /match with different headers\n' + 'EXPECTED: {"Content-Type":"application/json"}\nGOT: {}'); }); it('should throw exception when only data differs from expectation', function() { hb.when('GET').respond(200, '', {}); hb.expect('GET', '/match', 'some-data'); expect(function() { hb('GET', '/match', 'different', noop, {}); }).toThrow('Expected GET /match with different data\n' + 'EXPECTED: some-data\nGOT: different'); }); it('should not throw an exception when parsed body is equal to expected body object', function() { hb.when('GET').respond(200, '', {}); hb.expect('GET', '/match', {a: 1, b: 2}); expect(function() { hb('GET', '/match', '{"a":1,"b":2}', noop, {}); }).not.toThrow(); hb.expect('GET', '/match', {a: 1, b: 2}); expect(function() { hb('GET', '/match', '{"b":2,"a":1}', noop, {}); }).not.toThrow(); }); it('should throw exception when only parsed body differs from expected body object', function() { hb.when('GET').respond(200, '', {}); hb.expect('GET', '/match', {a: 1, b: 2}); expect(function() { hb('GET', '/match', '{"a":1,"b":3}', noop, {}); }).toThrow('Expected GET /match with different data\n' + 'EXPECTED: {"a":1,"b":2}\nGOT: {"a":1,"b":3}'); }); it("should use when's respond() when no expect() respond is defined", function() { callback.andCallFake(function(status, response) { expect(status).toBe(201); expect(response).toBe('data'); }); hb.when('GET', '/some').respond(201, 'data'); hb.expect('GET', '/some'); hb('GET', '/some', null, callback); hb.flush(); expect(callback).toHaveBeenCalled(); expect(function() { hb.verifyNoOutstandingExpectation(); }).not.toThrow(); }); }); describe('flush()', function() { it('flush() should flush requests fired during callbacks', function() { hb.when('GET').respond(200, ''); hb('GET', '/some', null, function() { hb('GET', '/other', null, callback); }); hb.flush(); expect(callback).toHaveBeenCalled(); }); it('should flush given number of pending requests', function() { hb.when('GET').respond(200, ''); hb('GET', '/some', null, callback); hb('GET', '/some', null, callback); hb('GET', '/some', null, callback); hb.flush(2); expect(callback).toHaveBeenCalled(); expect(callback.callCount).toBe(2); }); it('should throw exception when flushing more requests than pending', function() { hb.when('GET').respond(200, ''); hb('GET', '/url', null, callback); expect(function() {hb.flush(2);}).toThrow('No more pending request to flush !'); expect(callback).toHaveBeenCalledOnce(); }); it('should throw exception when no request to flush', function() { expect(function() {hb.flush();}).toThrow('No pending request to flush !'); hb.when('GET').respond(200, ''); hb('GET', '/some', null, callback); hb.flush(); expect(function() {hb.flush();}).toThrow('No pending request to flush !'); }); it('should throw exception if not all expectations satisfied', function() { hb.expect('GET', '/url1').respond(); hb.expect('GET', '/url2').respond(); hb('GET', '/url1', null, angular.noop); expect(function() {hb.flush();}).toThrow('Unsatisfied requests: GET /url2'); }); }); it('should abort requests when timeout promise resolves', function() { hb.expect('GET', '/url1').respond(200); var canceler, then = jasmine.createSpy('then').andCallFake(function(fn) { canceler = fn; }); hb('GET', '/url1', null, callback, null, {then: then}); expect(typeof canceler).toBe('function'); canceler(); // simulate promise resolution expect(callback).toHaveBeenCalledWith(-1, undefined, ''); hb.verifyNoOutstandingExpectation(); hb.verifyNoOutstandingRequest(); }); it('should abort requests when timeout passed as a numeric value', inject(function($timeout) { hb.expect('GET', '/url1').respond(200); hb('GET', '/url1', null, callback, null, 200); $timeout.flush(300); expect(callback).toHaveBeenCalledWith(-1, undefined, ''); hb.verifyNoOutstandingExpectation(); hb.verifyNoOutstandingRequest(); })); it('should throw an exception if no response defined', function() { hb.when('GET', '/test'); expect(function() { hb('GET', '/test', null, callback); }).toThrow('No response defined !'); }); it('should throw an exception if no response for exception and no definition', function() { hb.expect('GET', '/url'); expect(function() { hb('GET', '/url', null, callback); }).toThrow('No response defined !'); }); it('should respond undefined when JSONP method', function() { hb.when('JSONP', '/url1').respond(200); hb.expect('JSONP', '/url2').respond(200); expect(hb('JSONP', '/url1')).toBeUndefined(); expect(hb('JSONP', '/url2')).toBeUndefined(); }); it('should not have passThrough method', function() { expect(hb.passThrough).toBeUndefined(); }); describe('verifyExpectations', function() { it('should throw exception if not all expectations were satisfied', function() { hb.expect('POST', '/u1', 'ddd').respond(201, '', {}); hb.expect('GET', '/u2').respond(200, '', {}); hb.expect('POST', '/u3').respond(201, '', {}); hb('POST', '/u1', 'ddd', noop, {}); expect(function() {hb.verifyNoOutstandingExpectation();}). toThrow('Unsatisfied requests: GET /u2, POST /u3'); }); it('should do nothing when no expectation', function() { hb.when('DELETE', '/some').respond(200, ''); expect(function() {hb.verifyNoOutstandingExpectation();}).not.toThrow(); }); it('should do nothing when all expectations satisfied', function() { hb.expect('GET', '/u2').respond(200, '', {}); hb.expect('POST', '/u3').respond(201, '', {}); hb.when('DELETE', '/some').respond(200, ''); hb('GET', '/u2', noop); hb('POST', '/u3', noop); expect(function() {hb.verifyNoOutstandingExpectation();}).not.toThrow(); }); }); describe('verifyRequests', function() { it('should throw exception if not all requests were flushed', function() { hb.when('GET').respond(200); hb('GET', '/some', null, noop, {}); expect(function() { hb.verifyNoOutstandingRequest(); }).toThrow('Unflushed requests: 1'); }); }); describe('resetExpectations', function() { it('should remove all expectations', function() { hb.expect('GET', '/u2').respond(200, '', {}); hb.expect('POST', '/u3').respond(201, '', {}); hb.resetExpectations(); expect(function() {hb.verifyNoOutstandingExpectation();}).not.toThrow(); }); it('should remove all pending responses', function() { var cancelledClb = jasmine.createSpy('cancelled'); hb.expect('GET', '/url').respond(200, ''); hb('GET', '/url', null, cancelledClb); hb.resetExpectations(); hb.expect('GET', '/url').respond(300, ''); hb('GET', '/url', null, callback, {}); hb.flush(); expect(callback).toHaveBeenCalledOnce(); expect(cancelledClb).not.toHaveBeenCalled(); }); it('should not remove definitions', function() { var cancelledClb = jasmine.createSpy('cancelled'); hb.when('GET', '/url').respond(200, 'success'); hb('GET', '/url', null, cancelledClb); hb.resetExpectations(); hb('GET', '/url', null, callback, {}); hb.flush(); expect(callback).toHaveBeenCalledOnce(); expect(cancelledClb).not.toHaveBeenCalled(); }); }); describe('expect/when shortcuts', function() { angular.forEach(['expect', 'when'], function(prefix) { angular.forEach(['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'JSONP'], function(method) { var shortcut = prefix + method; it('should provide ' + shortcut + ' shortcut method', function() { hb[shortcut]('/foo').respond('bar'); hb(method, '/foo', undefined, callback); hb.flush(); expect(callback).toHaveBeenCalledOnceWith(200, 'bar', '', ''); }); }); }); }); describe('expectRoute/whenRoute shortcuts', function() { angular.forEach(['expectRoute', 'whenRoute'], function(routeShortcut) { var methods = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'JSONP']; they('should provide ' + routeShortcut + ' shortcut with $prop method', methods, function() { hb[routeShortcut](this, '/route').respond('path'); hb(this, '/route', undefined, callback); hb.flush(); expect(callback).toHaveBeenCalledOnceWith(200, 'path', '', ''); } ); they('should match colon deliminated parameters in ' + routeShortcut + ' $prop method', methods, function() { hb[routeShortcut](this, '/route/:id/path/:s_id').respond('path'); hb(this, '/route/123/path/456', undefined, callback); hb.flush(); expect(callback).toHaveBeenCalledOnceWith(200, 'path', '', ''); } ); they('should ignore query param when matching in ' + routeShortcut + ' $prop method', methods, function() { hb[routeShortcut](this, '/route/:id').respond('path'); hb(this, '/route/123?q=str&foo=bar', undefined, callback); hb.flush(); expect(callback).toHaveBeenCalledOnceWith(200, 'path', '', ''); } ); }); }); describe('MockHttpExpectation', function() { /* global MockHttpExpectation */ it('should accept url as regexp', function() { var exp = new MockHttpExpectation('GET', /^\/x/); expect(exp.match('GET', '/x')).toBe(true); expect(exp.match('GET', '/xxx/x')).toBe(true); expect(exp.match('GET', 'x')).toBe(false); expect(exp.match('GET', 'a/x')).toBe(false); }); it('should accept url as function', function() { var urlValidator = function(url) { return url !== '/not-accepted'; }; var exp = new MockHttpExpectation('POST', urlValidator); expect(exp.match('POST', '/url')).toBe(true); expect(exp.match('POST', '/not-accepted')).toBe(false); }); it('should accept data as regexp', function() { var exp = new MockHttpExpectation('POST', '/url', /\{.*?\}/); expect(exp.match('POST', '/url', '{"a": "aa"}')).toBe(true); expect(exp.match('POST', '/url', '{"one": "two"}')).toBe(true); expect(exp.match('POST', '/url', '{"one"')).toBe(false); }); it('should accept data as function', function() { var dataValidator = function(data) { var json = angular.fromJson(data); return !!json.id && json.status === 'N'; }; var exp = new MockHttpExpectation('POST', '/url', dataValidator); expect(exp.matchData({})).toBe(false); expect(exp.match('POST', '/url', '{"id": "xxx", "status": "N"}')).toBe(true); expect(exp.match('POST', '/url', {"id": "xxx", "status": "N"})).toBe(true); }); it('should ignore data only if undefined (not null or false)', function() { var exp = new MockHttpExpectation('POST', '/url', null); expect(exp.matchData(null)).toBe(true); expect(exp.matchData('some-data')).toBe(false); exp = new MockHttpExpectation('POST', '/url', undefined); expect(exp.matchData(null)).toBe(true); expect(exp.matchData('some-data')).toBe(true); }); it('should accept headers as function', function() { var exp = new MockHttpExpectation('GET', '/url', undefined, function(h) { return h['Content-Type'] == 'application/json'; }); expect(exp.matchHeaders({})).toBe(false); expect(exp.matchHeaders({'Content-Type': 'application/json', 'X-Another': 'true'})).toBe(true); }); }); }); describe('$rootElement', function() { it('should create mock application root', inject(function($rootElement) { expect($rootElement.text()).toEqual(''); })); }); describe('$rootScope', function() { var destroyed = false; var oldRootScope; it('should destroy $rootScope after each test', inject(function($rootScope) { $rootScope.$on('$destroy', function() { destroyed = true; }); oldRootScope = $rootScope; })); it('should have destroyed the $rootScope from the previous test', inject(function($rootScope) { expect(destroyed).toBe(true); expect($rootScope).not.toBe(oldRootScope); expect(oldRootScope.$$destroyed).toBe(true); })); }); describe('$rootScopeDecorator', function() { describe('$countChildScopes', function() { it('should return 0 when no child scopes', inject(function($rootScope) { expect($rootScope.$countChildScopes()).toBe(0); var childScope = $rootScope.$new(); expect($rootScope.$countChildScopes()).toBe(1); expect(childScope.$countChildScopes()).toBe(0); var grandChildScope = childScope.$new(); expect(childScope.$countChildScopes()).toBe(1); expect(grandChildScope.$countChildScopes()).toBe(0); })); it('should correctly navigate complex scope tree', inject(function($rootScope) { var child; $rootScope.$new(); $rootScope.$new().$new().$new(); child = $rootScope.$new().$new(); child.$new(); child.$new(); child.$new().$new().$new(); expect($rootScope.$countChildScopes()).toBe(11); })); it('should provide the current count even after child destructions', inject(function($rootScope) { expect($rootScope.$countChildScopes()).toBe(0); var childScope1 = $rootScope.$new(); expect($rootScope.$countChildScopes()).toBe(1); var childScope2 = $rootScope.$new(); expect($rootScope.$countChildScopes()).toBe(2); childScope1.$destroy(); expect($rootScope.$countChildScopes()).toBe(1); childScope2.$destroy(); expect($rootScope.$countChildScopes()).toBe(0); })); it('should work with isolate scopes', inject(function($rootScope) { /* RS | CIS / \ GCS GCIS */ var childIsolateScope = $rootScope.$new(true); expect($rootScope.$countChildScopes()).toBe(1); var grandChildScope = childIsolateScope.$new(); expect($rootScope.$countChildScopes()).toBe(2); expect(childIsolateScope.$countChildScopes()).toBe(1); var grandChildIsolateScope = childIsolateScope.$new(true); expect($rootScope.$countChildScopes()).toBe(3); expect(childIsolateScope.$countChildScopes()).toBe(2); childIsolateScope.$destroy(); expect($rootScope.$countChildScopes()).toBe(0); })); }); describe('$countWatchers', function() { it('should return the sum of watchers for the current scope and all of its children', inject( function($rootScope) { expect($rootScope.$countWatchers()).toBe(0); var childScope = $rootScope.$new(); expect($rootScope.$countWatchers()).toBe(0); childScope.$watch('foo'); expect($rootScope.$countWatchers()).toBe(1); expect(childScope.$countWatchers()).toBe(1); $rootScope.$watch('bar'); childScope.$watch('baz'); expect($rootScope.$countWatchers()).toBe(3); expect(childScope.$countWatchers()).toBe(2); })); it('should correctly navigate complex scope tree', inject(function($rootScope) { var child; $rootScope.$watch('foo1'); $rootScope.$new(); $rootScope.$new().$new().$new(); child = $rootScope.$new().$new(); child.$watch('foo2'); child.$new(); child.$new(); child = child.$new().$new().$new(); child.$watch('foo3'); child.$watch('foo4'); expect($rootScope.$countWatchers()).toBe(4); })); it('should provide the current count even after child destruction and watch deregistration', inject(function($rootScope) { var deregisterWatch1 = $rootScope.$watch('exp1'); var childScope = $rootScope.$new(); childScope.$watch('exp2'); expect($rootScope.$countWatchers()).toBe(2); childScope.$destroy(); expect($rootScope.$countWatchers()).toBe(1); deregisterWatch1(); expect($rootScope.$countWatchers()).toBe(0); })); it('should work with isolate scopes', inject(function($rootScope) { /* RS=1 | CIS=1 / \ GCS=1 GCIS=1 */ $rootScope.$watch('exp1'); expect($rootScope.$countWatchers()).toBe(1); var childIsolateScope = $rootScope.$new(true); childIsolateScope.$watch('exp2'); expect($rootScope.$countWatchers()).toBe(2); expect(childIsolateScope.$countWatchers()).toBe(1); var grandChildScope = childIsolateScope.$new(); grandChildScope.$watch('exp3'); var grandChildIsolateScope = childIsolateScope.$new(true); grandChildIsolateScope.$watch('exp4'); expect($rootScope.$countWatchers()).toBe(4); expect(childIsolateScope.$countWatchers()).toBe(3); expect(grandChildScope.$countWatchers()).toBe(1); expect(grandChildIsolateScope.$countWatchers()).toBe(1); childIsolateScope.$destroy(); expect($rootScope.$countWatchers()).toBe(1); })); }); }); describe('$controllerDecorator', function() { it('should support creating controller with bindings', function() { var called = false; var data = [ { name: 'derp1', id: 0 }, { name: 'testname', id: 1 }, { name: 'flurp', id: 2 } ]; module(function($controllerProvider) { $controllerProvider.register('testCtrl', function() { called = true; expect(this.data).toBe(data); }); }); inject(function($controller, $rootScope) { $controller('testCtrl', { scope: $rootScope }, { data: data }); expect(called).toBe(true); }); }); }); describe('$componentController', function() { it('should instantiate a simple controller defined inline in a component', function() { function TestController($scope, a, b) { this.$scope = $scope; this.a = a; this.b = b; } module(function($compileProvider) { $compileProvider.component('test', { controller: TestController }); }); inject(function($componentController, $rootScope) { var $scope = {}; var ctrl = $componentController('test', { $scope: $scope, a: 'A', b: 'B' }, { x: 'X', y: 'Y' }); expect(ctrl).toEqual({ $scope: $scope, a: 'A', b: 'B', x: 'X', y: 'Y' }); expect($scope.$ctrl).toBe(ctrl); }); }); it('should instantiate a controller with $$inject annotation defined inline in a component', function() { function TestController(x, y, z) { this.$scope = x; this.a = y; this.b = z; } TestController.$inject = ['$scope', 'a', 'b']; module(function($compileProvider) { $compileProvider.component('test', { controller: TestController }); }); inject(function($componentController, $rootScope) { var $scope = {}; var ctrl = $componentController('test', { $scope: $scope, a: 'A', b: 'B' }, { x: 'X', y: 'Y' }); expect(ctrl).toEqual({ $scope: $scope, a: 'A', b: 'B', x: 'X', y: 'Y' }); expect($scope.$ctrl).toBe(ctrl); }); }); it('should instantiate a named controller defined in a component', function() { function TestController($scope, a, b) { this.$scope = $scope; this.a = a; this.b = b; } module(function($controllerProvider, $compileProvider) { $controllerProvider.register('TestController', TestController); $compileProvider.component('test', { controller: 'TestController' }); }); inject(function($componentController, $rootScope) { var $scope = {}; var ctrl = $componentController('test', { $scope: $scope, a: 'A', b: 'B' }, { x: 'X', y: 'Y' }); expect(ctrl).toEqual({ $scope: $scope, a: 'A', b: 'B', x: 'X', y: 'Y' }); expect($scope.$ctrl).toBe(ctrl); }); }); it('should instantiate a named controller with `controller as` syntax defined in a component', function() { function TestController($scope, a, b) { this.$scope = $scope; this.a = a; this.b = b; } module(function($controllerProvider, $compileProvider) { $controllerProvider.register('TestController', TestController); $compileProvider.component('test', { controller: 'TestController as testCtrl' }); }); inject(function($componentController, $rootScope) { var $scope = {}; var ctrl = $componentController('test', { $scope: $scope, a: 'A', b: 'B' }, { x: 'X', y: 'Y' }); expect(ctrl).toEqual({ $scope: $scope, a: 'A', b: 'B', x: 'X', y: 'Y' }); expect($scope.testCtrl).toBe(ctrl); }); }); it('should instantiate the controller of the restrict:\'E\' component if there are more directives with the same name but not restricted to \'E\'', function() { function TestController() { this.r = 6779; } module(function($compileProvider) { $compileProvider.directive('test', function() { return { restrict: 'A' }; }); $compileProvider.component('test', { controller: TestController }); }); inject(function($componentController, $rootScope) { var ctrl = $componentController('test', { $scope: {} }); expect(ctrl).toEqual({ r: 6779 }); }); }); it('should instantiate the controller of the restrict:\'E\' component if there are more directives with the same name and restricted to \'E\' but no controller', function() { function TestController() { this.r = 22926; } module(function($compileProvider) { $compileProvider.directive('test', function() { return { restrict: 'E' }; }); $compileProvider.component('test', { controller: TestController }); }); inject(function($componentController, $rootScope) { var ctrl = $componentController('test', { $scope: {} }); expect(ctrl).toEqual({ r: 22926 }); }); }); it('should instantiate the controller of the directive with controller, controllerAs and restrict:\'E\' if there are more directives', function() { function TestController() { this.r = 18842; } module(function($compileProvider) { $compileProvider.directive('test', function() { return { }; }); $compileProvider.directive('test', function() { return { restrict: 'E', controller: TestController, controllerAs: '$ctrl' }; }); }); inject(function($componentController, $rootScope) { var ctrl = $componentController('test', { $scope: {} }); expect(ctrl).toEqual({ r: 18842 }); }); }); it('should fail if there is no directive with restrict:\'E\' and controller', function() { function TestController() { this.r = 31145; } module(function($compileProvider) { $compileProvider.directive('test', function() { return { restrict: 'AC', controller: TestController }; }); $compileProvider.directive('test', function() { return { restrict: 'E', controller: TestController }; }); $compileProvider.directive('test', function() { return { restrict: 'EA', controller: TestController, controllerAs: '$ctrl' }; }); $compileProvider.directive('test', function() { return { restrict: 'E' }; }); }); inject(function($componentController, $rootScope) { expect(function() { $componentController('test', { $scope: {} }); }).toThrow('No component found'); }); }); it('should fail if there more than two components with same name', function() { function TestController($scope, a, b) { this.$scope = $scope; this.a = a; this.b = b; } module(function($compileProvider) { $compileProvider.directive('test', function() { return { restrict: 'E', controller: TestController, controllerAs: '$ctrl' }; }); $compileProvider.component('test', { controller: TestController }); }); inject(function($componentController, $rootScope) { expect(function() { var $scope = {}; $componentController('test', { $scope: $scope, a: 'A', b: 'B' }, { x: 'X', y: 'Y' }); }).toThrow('Too many components found'); }); }); }); }); describe('ngMockE2E', function() { describe('$httpBackend', function() { var hb, realHttpBackend, callback; beforeEach(function() { module(function($provide) { callback = jasmine.createSpy('callback'); realHttpBackend = jasmine.createSpy('real $httpBackend'); $provide.value('$httpBackend', realHttpBackend); $provide.decorator('$httpBackend', angular.mock.e2e.$httpBackendDecorator); }); inject(function($injector) { hb = $injector.get('$httpBackend'); }); }); describe('passThrough()', function() { it('should delegate requests to the real backend when passThrough is invoked', function() { hb.when('GET', /\/passThrough\/.*/).passThrough(); hb('GET', '/passThrough/23', null, callback, {}, null, true); expect(realHttpBackend).toHaveBeenCalledOnceWith( 'GET', '/passThrough/23', null, callback, {}, null, true); }); it('should be able to override a respond definition with passThrough', function() { var definition = hb.when('GET', /\/passThrough\/.*/).respond('override me'); definition.passThrough(); hb('GET', '/passThrough/23', null, callback, {}, null, true); expect(realHttpBackend).toHaveBeenCalledOnceWith( 'GET', '/passThrough/23', null, callback, {}, null, true); }); it('should be able to override a respond definition with passThrough', inject(function($browser) { var definition = hb.when('GET', /\/passThrough\/.*/).passThrough(); definition.respond('passThrough override'); hb('GET', '/passThrough/23', null, callback, {}, null, true); $browser.defer.flush(); expect(realHttpBackend).not.toHaveBeenCalled(); expect(callback).toHaveBeenCalledOnceWith(200, 'passThrough override', '', ''); })); }); describe('autoflush', function() { it('should flush responses via $browser.defer', inject(function($browser) { hb.when('GET', '/foo').respond('bar'); hb('GET', '/foo', null, callback); expect(callback).not.toHaveBeenCalled(); $browser.defer.flush(); expect(callback).toHaveBeenCalledOnce(); })); }); }); describe('ngAnimateMock', function() { beforeEach(module('ngAnimate')); beforeEach(module('ngAnimateMock')); var ss, element, trackedAnimations, animationLog; afterEach(function() { if (element) { element.remove(); } if (ss) { ss.destroy(); } }); beforeEach(module(function($animateProvider) { trackedAnimations = []; animationLog = []; $animateProvider.register('.animate', function() { return { leave: logFn('leave'), addClass: logFn('addClass') }; function logFn(method) { return function(element) { animationLog.push('start ' + method); trackedAnimations.push(getDoneCallback(arguments)); return function closingFn(cancel) { var lab = cancel ? 'cancel' : 'end'; animationLog.push(lab + ' ' + method); }; }; } function getDoneCallback(args) { for (var i = args.length; i > 0; i--) { if (angular.isFunction(args[i])) return args[i]; } } }); return function($animate, $rootElement, $document, $rootScope) { ss = createMockStyleSheet($document); element = angular.element('<div class="animate"></div>'); $rootElement.append(element); angular.element($document[0].body).append($rootElement); $animate.enabled(true); $rootScope.$digest(); }; })); describe('$animate.queue', function() { it('should maintain a queue of the executed animations', inject(function($animate) { element.removeClass('animate'); // we don't care to test any actual animations var options = {}; $animate.addClass(element, 'on', options); var first = $animate.queue[0]; expect(first.element).toBe(element); expect(first.event).toBe('addClass'); expect(first.options).toBe(options); $animate.removeClass(element, 'off', options); var second = $animate.queue[1]; expect(second.element).toBe(element); expect(second.event).toBe('removeClass'); expect(second.options).toBe(options); $animate.leave(element, options); var third = $animate.queue[2]; expect(third.element).toBe(element); expect(third.event).toBe('leave'); expect(third.options).toBe(options); })); }); describe('$animate.flush()', function() { it('should throw an error if there is nothing to animate', inject(function($animate) { expect(function() { $animate.flush(); }).toThrow('No pending animations ready to be closed or flushed'); })); it('should trigger the animation to start', inject(function($animate) { expect(trackedAnimations.length).toBe(0); $animate.leave(element); $animate.flush(); expect(trackedAnimations.length).toBe(1); })); it('should trigger the animation to end once run and called', inject(function($animate) { $animate.leave(element); $animate.flush(); expect(element.parent().length).toBe(1); trackedAnimations[0](); $animate.flush(); expect(element.parent().length).toBe(0); })); it('should trigger the animation promise callback to fire once run and closed', inject(function($animate) { var doneSpy = jasmine.createSpy(); $animate.leave(element).then(doneSpy); $animate.flush(); trackedAnimations[0](); expect(doneSpy).not.toHaveBeenCalled(); $animate.flush(); expect(doneSpy).toHaveBeenCalled(); })); it('should trigger a series of CSS animations to trigger and start once run', inject(function($animate, $rootScope) { if (!browserSupportsCssAnimations()) return; ss.addRule('.leave-me.ng-leave', 'transition:1s linear all;'); var i, elm, elms = []; for (i = 0; i < 5; i++) { elm = angular.element('<div class="leave-me"></div>'); element.append(elm); elms.push(elm); $animate.leave(elm); } $rootScope.$digest(); for (i = 0; i < 5; i++) { elm = elms[i]; expect(elm.hasClass('ng-leave')).toBe(true); expect(elm.hasClass('ng-leave-active')).toBe(false); } $animate.flush(); for (i = 0; i < 5; i++) { elm = elms[i]; expect(elm.hasClass('ng-leave')).toBe(true); expect(elm.hasClass('ng-leave-active')).toBe(true); } })); it('should trigger parent and child animations to run within the same flush', inject(function($animate, $rootScope) { var child = angular.element('<div class="animate child"></div>'); element.append(child); expect(trackedAnimations.length).toBe(0); $animate.addClass(element, 'go'); $animate.addClass(child, 'start'); $animate.flush(); expect(trackedAnimations.length).toBe(2); })); it('should trigger animation callbacks when called', inject(function($animate, $rootScope) { var spy = jasmine.createSpy(); $animate.on('addClass', element, spy); $animate.addClass(element, 'on'); expect(spy).not.toHaveBeenCalled(); $animate.flush(); expect(spy.callCount).toBe(1); trackedAnimations[0](); $animate.flush(); expect(spy.callCount).toBe(2); })); }); describe('$animate.closeAndFlush()', function() { it('should close the currently running $animateCss animations', inject(function($animateCss, $animate) { if (!browserSupportsCssAnimations()) return; var spy = jasmine.createSpy(); var runner = $animateCss(element, { duration: 1, to: { color: 'red' } }).start(); runner.then(spy); expect(spy).not.toHaveBeenCalled(); $animate.closeAndFlush(); expect(spy).toHaveBeenCalled(); })); it('should close the currently running $$animateJs animations', inject(function($$animateJs, $animate) { var spy = jasmine.createSpy(); var runner = $$animateJs(element, 'leave', 'animate', {}).start(); runner.then(spy); expect(spy).not.toHaveBeenCalled(); $animate.closeAndFlush(); expect(spy).toHaveBeenCalled(); })); it('should run the closing javascript animation function upon flush', inject(function($$animateJs, $animate) { $$animateJs(element, 'leave', 'animate', {}).start(); expect(animationLog).toEqual(['start leave']); $animate.closeAndFlush(); expect(animationLog).toEqual(['start leave', 'end leave']); })); it('should not throw when a regular animation has no javascript animation', inject(function($animate, $$animation, $rootElement) { if (!browserSupportsCssAnimations()) return; var element = jqLite('<div></div>'); $rootElement.append(element); // Make sure the animation has valid $animateCss options $$animation(element, null, { from: { background: 'red' }, to: { background: 'blue' }, duration: 1, transitionStyle: 'all 1s' }); expect(function() { $animate.closeAndFlush(); }).not.toThrow(); dealoc(element); })); it('should throw an error if there are no animations to close and flush', inject(function($animate) { expect(function() { $animate.closeAndFlush(); }).toThrow('No pending animations ready to be closed or flushed'); })); }); }); }); describe('make sure that we can create an injector outside of tests', function() { //since some libraries create custom injectors outside of tests, //we want to make sure that this is not breaking the internals of //how we manage annotated function cleanup during tests. See #10967 angular.injector([function($injector) {}]); });
// @flow type X = {foo: number}; type Y = {bar: X, baz: ?X}; declare var x1: ?X; declare var x2: X; declare var y1: ?Y; declare var y2: Y; (x1?.foo: empty); (x2?.foo: empty); (y1?.bar?.foo: empty); (y2?.bar?.foo: empty); (y1?.baz?.foo: empty); (y2?.baz?.foo: empty); (y1?.bar.foo: empty); (y2?.bar.foo: empty); (y1?.baz.foo: empty); (y2?.baz.foo: empty); (y1.bar?.foo: empty); (y2.bar?.foo: empty); (y1.baz?.foo: empty); (y2.baz?.foo: empty); ((y1?.bar).foo: empty); ((y2?.bar).foo: empty); ((y1?.baz).foo: empty); ((y2?.baz).foo: empty); const a: any | null = 1337; const b: string | null = a?.a; const c: ?any = 1337; const d: string | null = c?.c;
require("coffee-script/register"), require("./gulpfile.coffee");
module.exports = function makeProjectPatch(windowsConfig) { const projectInsert = `<ProjectReference Include="..\\${windowsConfig.relativeProjPath}"> <Project>{${windowsConfig.projectGUID}}</Project> <Name>${windowsConfig.projectName}</Name> </ProjectReference> `; /* eslint-disable no-control-regex */ return { pattern: '<ProjectReference Include="..\\..\\node_modules\\react-native-windows\\ReactWindows\\ReactNative\\ReactNative.csproj">', patch: projectInsert, unpatch: new RegExp(`[^\S\r\n]+<ProjectReference.+\\s+.+\\s+.+${windowsConfig.projectName}.+\\s+.+\\s`), }; };
var fs = require("fs"); var path = require("path"); var expect = require("chai").expect; var vm = require("vm"); before(function() { var basedir = path.join(__dirname, "../../.."); var fileName = "js/app.js"; var filePath = path.join(basedir, fileName); var code = fs.readFileSync(filePath); this.sandbox = { module: {}, __dirname: path.dirname(filePath), global: {}, console: { log: function() { /*console.log("console.log(", arguments, ")");*/ } }, process: { on: function() { /*console.log("process.on called with: ", arguments);*/ }, env: {} } }; this.sandbox.require = function(filename) { // This modifies the global slightly, // but supplies vm with essential code return require(filename); }; vm.runInNewContext(code, this.sandbox, fileName); }); after(function() { //console.log(global); }); describe("'global.root_path' set in js/app.js", function() { var expectedSubPaths = [ "modules", "serveronly", "js", "js/app.js", "js/main.js", "js/electron.js", "config" ]; expectedSubPaths.forEach(subpath => { it(`contains a file/folder "${subpath}"`, function() { expect(fs.existsSync(path.join(this.sandbox.global.root_path, subpath))).to.equal(true); }); }); it("should not modify global.root_path for testing", function() { expect(global.root_path).to.equal(undefined); }); it("should not modify global.version for testing", function() { expect(global.version).to.equal(undefined); }); it("should expect the global.version equals package.json file", function() { versionPackage = JSON.parse(fs.readFileSync("package.json", "utf8")).version; expect(this.sandbox.global.version).to.equal(versionPackage); }); });
#!/usr/bin/env node 'use strict'; /** * Remove build/test related directories. */ // dependencies const config = require('./config'); const sh = require('shelljs'); const tools = require('@singpath/tools'); // exit on error sh.set('-e'); tools.clean([config.build.root, config.coverage.root]);
const DrawCard = require('../../drawcard.js'); class NaiveScout extends DrawCard { setupCardAbilities(ability) { this.persistentEffect({ condition: () => this.game.getPlayers().some(player => player.shadows.length > 0), match: this, effect: ability.effects.cannotBeDeclaredAsDefender() }); } } NaiveScout.code = '11045'; module.exports = NaiveScout;
import Node from "./node"; const config = { category: 'datastores', color: '#ffcc00', defaults: { name: {value:""}, subtype: {value:"webcam"}, }, schemakey: "subtype", inputs:0, outputs:1, icon: "fa-video-camera", unicode: '\uf03d', label: function() { return this.name||"webcam"; }, schemafn: (subtype)=>{ return { output:{ type: "object", description: "the container object", properties:{ name: {type:'string', description: "a name assigned to this webcam"}, dataURL: {type: 'string', description: "a string containing a representation of the image in the format specified by the type parameter"}, }, } } }, risk: (subtype="")=>{ return { score: 5, reason: "this datastore provides access to webcam video" } }, descriptionfn:(subtype)=>{ return "a webcam"; } } export default { type: "webcam", def: Object.assign({_: (id)=>{return id}}, config, {nodetype:"webcam"}), node: Node, }
/**! * * Copyright (c) 2015-2017 Cisco Systems, Inc. See LICENSE file. * @private */ import {registerPlugin} from '@ciscospark/spark-core'; import Feature from './feature'; import config from './config'; registerPlugin(`feature`, Feature, { config }); export {default as default} from './feature';
/** * Version: 1.0 Alpha-1 * Build Date: 13-Nov-2007 * Copyright (c) 2006-2007, Coolite Inc. (http://www.coolite.com/). All rights reserved. * License: Licensed under The MIT License. See license.txt and http://www.datejs.com/license/. * Website: http://www.datejs.com/ or http://www.coolite.com/datejs/ */ Date.CultureInfo = { /* Culture Name */ name: "mt-MT", englishName: "Maltese (Malta)", nativeName: "Malti (Malta)", /* Day Name Strings */ dayNames: ["Il-Ħadd", "It-Tnejn", "It-Tlieta", "L-Erbgħa", "Il-Ħamis", "Il-Ġimgħa", "Is-Sibt"], abbreviatedDayNames: ["Ħad", "Tne", "Tli", "Erb", "Ħam", "Ġim", "Sib"], shortestDayNames: ["Ħad", "Tne", "Tli", "Erb", "Ħam", "Ġim", "Sib"], firstLetterDayNames: ["Ħ", "T", "T", "E", "Ħ", "Ġ", "S"], /* Month Name Strings */ monthNames: ["Jannar", "Frar", "Marzu", "April", "Mejju", "Ġunju", "Lulju", "Awissu", "Settembru", "Ottubru", "Novembru", "Diċembru"], abbreviatedMonthNames: ["Jan", "Fra", "Mar", "Apr", "Mej", "Ġun", "Lul", "Awi", "Set", "Ott", "Nov", "Diċ"], /* AM/PM Designators */ amDesignator: "AM", pmDesignator: "PM", firstDayOfWeek: 1, twoDigitYearMax: 2029, /** * The dateElementOrder is based on the order of the * format specifiers in the formatPatterns.DatePattern. * * Example: <pre> shortDatePattern dateElementOrder ------------------ ---------------- "M/d/yyyy" "mdy" "dd/MM/yyyy" "dmy" "yyyy-MM-dd" "ymd" </pre> * The correct dateElementOrder is required by the parser to * determine the expected order of the date elements in the * string being parsed. * * NOTE: It is VERY important this value be correct for each Culture. */ dateElementOrder: "dmy", /* Standard date and time format patterns */ formatPatterns: { shortDate: "dd/MM/yyyy", longDate: "dddd, d' ta\' 'MMMM yyyy", shortTime: "HH:mm:ss", longTime: "HH:mm:ss", fullDateTime: "dddd, d' ta\' 'MMMM yyyy HH:mm:ss", sortableDateTime: "yyyy-MM-ddTHH:mm:ss", universalSortableDateTime: "yyyy-MM-dd HH:mm:ssZ", rfc1123: "ddd, dd MMM yyyy HH:mm:ss GMT", monthDay: "MMMM dd", yearMonth: "MMMM yyyy" }, /** * NOTE: If a string format is not parsing correctly, but * you would expect it parse, the problem likely lies below. * * The following regex patterns control most of the string matching * within the parser. * * The Month name and Day name patterns were automatically generated * and in general should be (mostly) correct. * * Beyond the month and day name patterns are natural language strings. * Example: "next", "today", "months" * * These natural language string may NOT be correct for this culture. * If they are not correct, please translate and edit this file * providing the correct regular expression pattern. * * If you modify this file, please post your revised CultureInfo file * to the Datejs Discussions located at * http://groups.google.com/group/date-js * * Please mark the subject with [CultureInfo]. Example: * Subject: [CultureInfo] Translated "da-DK" Danish(Denmark) * * We will add the modified patterns to the master source files. * * As well, please review the list of "Future Strings" section below. */ regexPatterns: { jan: /^jan(nar)?/i, feb: /^fra(r)?/i, mar: /^mar(zu)?/i, apr: /^apr(il)?/i, may: /^mej(ju)?/i, jun: /^ġun(ju)?/i, jul: /^lul(ju)?/i, aug: /^awi(ssu)?/i, sep: /^set(tembru)?/i, oct: /^ott(ubru)?/i, nov: /^nov(embru)?/i, dec: /^diċ(embru)?/i, sun: /^il-ħadd/i, mon: /^it-tnejn/i, tue: /^it-tlieta/i, wed: /^l-erbgħa/i, thu: /^il-ħamis/i, fri: /^il-ġimgħa/i, sat: /^is-sibt/i, future: /^next/i, past: /^last|past|prev(ious)?/i, add: /^(\+|after|from)/i, subtract: /^(\-|before|ago)/i, yesterday: /^yesterday/i, today: /^t(oday)?/i, tomorrow: /^tomorrow/i, now: /^n(ow)?/i, millisecond: /^ms|milli(second)?s?/i, second: /^sec(ond)?s?/i, minute: /^min(ute)?s?/i, hour: /^h(ou)?rs?/i, week: /^w(ee)?k/i, month: /^m(o(nth)?s?)?/i, day: /^d(ays?)?/i, year: /^y((ea)?rs?)?/i, shortMeridian: /^(a|p)/i, longMeridian: /^(a\.?m?\.?|p\.?m?\.?)/i, timezone: /^((e(s|d)t|c(s|d)t|m(s|d)t|p(s|d)t)|((gmt)?\s*(\+|\-)\s*\d\d\d\d?)|gmt)/i, ordinalSuffix: /^\s*(st|nd|rd|th)/i, timeContext: /^\s*(\:|a|p)/i }, abbreviatedTimeZoneStandard: { GMT: "-000", EST: "-0400", CST: "-0500", MST: "-0600", PST: "-0700" }, abbreviatedTimeZoneDST: { GMT: "-000", EDT: "-0500", CDT: "-0600", MDT: "-0700", PDT: "-0800" } }; /******************** ** Future Strings ** ******************** * * The following list of strings are not currently being used, but * may be incorporated later. We would appreciate any help translating * the strings below. * * If you modify this file, please post your revised CultureInfo file * to the Datejs Discussions located at * http://groups.google.com/group/date-js * * Please mark the subject with [CultureInfo]. Example: * Subject: [CultureInfo] Translated "da-DK" Danish(Denmark) * * English Name Translated * ------------------ ----------------- * date date * time time * calendar calendar * show show * hourly hourly * daily daily * weekly weekly * bi-weekly bi-weekly * monthly monthly * bi-monthly bi-monthly * quarter quarter * quarterly quarterly * yearly yearly * annual annual * annually annually * annum annum * again again * between between * after after * from now from now * repeat repeat * times times * per per */
var extend = require('xtend') var getFormData = require('form-data-set/element') var BaseEvent = require('./base-event.js') var VALID_CHANGE = ['checkbox', 'file', 'select-multiple', 'select-one']; var VALID_INPUT = ['color', 'date', 'datetime', 'datetime-local', 'email', 'month', 'number', 'password', 'range', 'search', 'tel', 'text', 'time', 'url', 'week']; module.exports = BaseEvent(changeLambda); function changeLambda(ev, broadcast) { var target = ev.target var isValid = (ev.type === 'input' && VALID_INPUT.indexOf(target.type) !== -1) || (ev.type === 'change' && VALID_CHANGE.indexOf(target.type) !== -1); if (!isValid) { if (ev.startPropagation) { ev.startPropagation() } return } var value = getFormData(ev.currentTarget) var data = extend(value, this.data) broadcast(data) }
var concat = require('../../src/concat'); var equals = require('../../src/equals'); var map = require('../../src/map'); var toString = require('../../src/toString'); // Id :: a -> Id a module.exports = function Id(value) { return { '@@type': 'ramda/Id', 'fantasy-land/equals': function(other) { return other != null && other['@@type'] === this['@@type'] && equals(other.value, value); }, 'fantasy-land/concat': function(id) { return Id(concat(value, id.value)); }, 'fantasy-land/map': function(f) { return Id(f(value)); }, 'fantasy-land/ap': function(id) { return Id(id.value(value)); }, 'fantasy-land/chain': function(f) { return f(value); }, 'fantasy-land/reduce': function(f, x) { return f(x, value); }, 'fantasy-land/traverse': function(f, of) { return map(Id, f(value)); }, sequence: function(of) { return map(Id, this.value); }, constructor: {'fantasy-land/of': Id}, toString: function() { return 'Id(' + toString(value) + ')'; }, value: value }; };
var http = require("http"), url = require("url"), path = require("path"), fs = require("fs"), port = process.argv[2] || 8888; var offset = "/../www/" http.createServer(function(request, response) { var uri = url.parse(request.url).pathname , filename = path.join(process.cwd() + offset, uri); fs.exists(filename, function(exists) { if(!exists) { response.writeHead(404, {"Content-Type": "text/plain"}); response.write("404 Not Found\n"); response.end(); console.log("couldn't find: " + filename); return; } if (fs.statSync(filename).isDirectory()) filename += '/index.html'; fs.readFile(filename, "binary", function(err, file) { if(err) { response.writeHead(500, {"Content-Type": "text/plain"}); response.write(err + "\n"); response.end(); console.log("error while loading: " + filename); return; } var type = "text/plain"; var extn = path.extname(filename); switch(extn) { case ".json": type = "application/json" break; case ".js": type = "text/javascript" break; case ".html": type = "text/html"; break; case ".css": type = "text/css"; break; default: type = "text/plain"; } response.writeHead(200, {"Content-Type": type}); response.write(file, "binary"); response.end(); }); }); }).listen(parseInt(port, 10)); console.log("Static file server running at\n => http://localhost:" + port + "/\nCTRL + C to shutdown");
import {load, finputDefaultDelimiters} from '../pageObjects/index'; import customCommandsFactory from '../customCommands'; const {typing} = customCommandsFactory(finputDefaultDelimiters); describe('traversals', () => { beforeAll(load); describe('supports HOME and END keys sending caret to start / end of field', () => { typing(`12⇤3`).shouldShow(`312`).shouldHaveFocus(true).shouldHaveCaretAt(1); typing(`123⇤⇤4`).shouldShow(`4,123`).shouldHaveCaretAt(1); typing(`123⇤⇥4`).shouldShow(`1,234`).shouldHaveCaretAt(5); typing(`123⇤⇥4⇤5`).shouldShow(`51,234`).shouldHaveCaretAt(1); }); describe('supports left and right ARROW keys shifting caret left / right one caret', () => { typing(`123456←8`).shouldShow(`1,234,586`); typing(`123456←←8`).shouldShow(`1,234,856`); typing(`123456←←←8`).shouldShow(`1,238,456`); }); describe('supports up and down ARROW keys sending caret to start / end of field', () => { typing(`12↑3`).shouldShow(`312`).shouldHaveFocus(true).shouldHaveCaretAt(1); typing(`123↑↑4`).shouldShow(`4,123`).shouldHaveCaretAt(1); typing(`123↑↓4`).shouldShow(`1,234`).shouldHaveCaretAt(5); typing(`123↑↓4↑5`).shouldShow(`51,234`).shouldHaveCaretAt(1); }); });
/* * JSON Date Extensions - JSON date parsing extensions * Version 1.2.1 * https://github.com/RickStrahl/json.date-extensions * (c) 2013-2015 Rick Strahl, West Wind Technologies * * Released under MIT License * http://en.wikipedia.org/wiki/MIT_License */ (function (undefined) { "use strict"; if (JSON && !JSON.dateParser) { var reISO = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.{0,1}\d*))(?:Z|(\+|-)([\d|:]*))?$/; var reMsAjax = /^\/Date\((d|-|.*)\)[\/|\\]$/; /// <summary> /// set this if you want MS Ajax Dates parsed /// before calling any of the other functions /// </summary> JSON.parseMsAjaxDate = false; JSON.useDateParser = function (reset) { /// <summary> /// Globally enables JSON date parsing for JSON.parse(). /// Replaces the default JSON.parse() method and adds /// the datePaser() extension to the processing chain. /// </summary> /// <param name="reset" type="bool">when set restores the original JSON.parse() function</param> // if any parameter is passed reset if (reset !== undefined) { if (JSON._parseSaved) { JSON.parse = JSON._parseSaved; JSON._parseSaved = null; } } else { if (!JSON._parseSaved) { JSON._parseSaved = JSON.parse; JSON.parse = JSON.parseWithDate; } } }; /// <summary> /// Creates a new filter that processes dates and also delegates to a chain filter optionaly. /// </summary> /// <param name="chainFilter" type="Function">property name that is parsed</param> /// <returns type="Function">returns a new chainning filter for dates</returns> var createDateParser = function (chainFilter) { return function (key, value) { var parsedValue = value; if (typeof value === 'string') { var a = reISO.exec(value); if (a) { parsedValue = new Date(value); } else if (JSON.parseMsAjaxDate) { a = reMsAjax.exec(value); if (a) { var b = a[1].split(/[-+,.]/); parsedValue = new Date(b[0] ? +b[0] : 0 - +b[1]); } } } if (chainFilter !== undefined) return chainFilter(key, parsedValue); else return parsedValue; }; } /// <summary> /// A filter that can be used with JSON.parse to convert dates. /// </summary> /// <param name="key" type="string">property name that is parsed</param> /// <param name="value" type="any">property value</param> /// <returns type="date">returns date or the original value if not a date string</returns> JSON.dateParser = createDateParser(); JSON.parseWithDate = function (json, chainFilter) { /// <summary> /// Wrapper around the JSON.parse() function that adds a date /// filtering extension. Returns all dates as real JavaScript dates. /// </summary> /// <param name="json" type="string">JSON to be parsed</param> /// <returns type="any">parsed value or object</returns> var parse = JSON._parseSaved ? JSON._parseSaved : JSON.parse; try { var res = parse(json, createDateParser(chainFilter)); return res; } catch (e) { // orignal error thrown has no error message so rethrow with message throw new Error("JSON content could not be parsed"); } }; JSON.dateStringToDate = function (dtString, nullDateVal) { alert(dtString) /// <summary> /// Converts a JSON ISO or MSAJAX date or real date a date value. /// Supports both JSON encoded dates or plain date formatted strings /// (without the JSON string quotes). /// If you pass a date the date is returned as is. If you pass null /// null or the nullDateVal is returned. /// </summary> /// <param name="dtString" type="var">Date String in ISO or MSAJAX format</param> /// <param name="nullDateVal" type="var">value to return if date can't be parsed</param> /// <returns type="date">date or the nullDateVal (null by default)</returns> if (!nullDateVal) nullDateVal = null; if (!dtString) return nullDateVal; // empty if (dtString.getTime) return dtString; // already a date if (dtString[0] === '"' || dtString[0] === "'") // strip off JSON quotes dtString = dtString.substr(1, dtString.length - 2); var a = reISO.exec(dtString); if (a) return new Date(dtString); if (!JSON.parseMsAjaxDate) return nullDateVal; a = reMsAjax.exec(dtString); if (a) { var b = a[1].split(/[-,.]/); return new Date(+b[0]); } return nullDateVal; }; } })(); /*-------------------------------------------------------------------------- * linq.js - LINQ for JavaScript * ver 2.2.0.2 (Jan. 21th, 2011) * * created and maintained by neuecc <ils@neue.cc> * licensed under Microsoft Public License(Ms-PL) * http://neue.cc/ * http://linqjs.codeplex.com/ *--------------------------------------------------------------------------*/ Enumerable = (function () { var Enumerable = function (getEnumerator) { this.GetEnumerator = getEnumerator; } // Generator Enumerable.Choice = function () // variable argument { var args = (arguments[0] instanceof Array) ? arguments[0] : arguments; return new Enumerable(function () { return new IEnumerator( Functions.Blank, function () { return this.Yield(args[Math.floor(Math.random() * args.length)]); }, Functions.Blank); }); } Enumerable.Cycle = function () // variable argument { var args = (arguments[0] instanceof Array) ? arguments[0] : arguments; return new Enumerable(function () { var index = 0; return new IEnumerator( Functions.Blank, function () { if (index >= args.length) index = 0; return this.Yield(args[index++]); }, Functions.Blank); }); } Enumerable.Empty = function () { return new Enumerable(function () { return new IEnumerator( Functions.Blank, function () { return false; }, Functions.Blank); }); } Enumerable.From = function (obj) { if (obj == null) { return Enumerable.Empty(); } if (obj instanceof Enumerable) { return obj; } if (typeof obj == Types.Number || typeof obj == Types.Boolean) { return Enumerable.Repeat(obj, 1); } if (typeof obj == Types.String) { return new Enumerable(function () { var index = 0; return new IEnumerator( Functions.Blank, function () { return (index < obj.length) ? this.Yield(obj.charAt(index++)) : false; }, Functions.Blank); }); } if (typeof obj != Types.Function) { // array or array like object if (typeof obj.length == Types.Number) { return new ArrayEnumerable(obj); } // JScript's IEnumerable if (!(obj instanceof Object) && Utils.IsIEnumerable(obj)) { return new Enumerable(function () { var isFirst = true; var enumerator; return new IEnumerator( function () { enumerator = new Enumerator(obj); }, function () { if (isFirst) isFirst = false; else enumerator.moveNext(); return (enumerator.atEnd()) ? false : this.Yield(enumerator.item()); }, Functions.Blank); }); } } // case function/object : Create KeyValuePair[] return new Enumerable(function () { var array = []; var index = 0; return new IEnumerator( function () { for (var key in obj) { if (!(obj[key] instanceof Function)) { array.push({ Key: key, Value: obj[key] }); } } }, function () { return (index < array.length) ? this.Yield(array[index++]) : false; }, Functions.Blank); }); }, Enumerable.Return = function (element) { return Enumerable.Repeat(element, 1); } // Overload:function(input, pattern) // Overload:function(input, pattern, flags) Enumerable.Matches = function (input, pattern, flags) { if (flags == null) flags = ""; if (pattern instanceof RegExp) { flags += (pattern.ignoreCase) ? "i" : ""; flags += (pattern.multiline) ? "m" : ""; pattern = pattern.source; } if (flags.indexOf("g") === -1) flags += "g"; return new Enumerable(function () { var regex; return new IEnumerator( function () { regex = new RegExp(pattern, flags) }, function () { var match = regex.exec(input); return (match) ? this.Yield(match) : false; }, Functions.Blank); }); } // Overload:function(start, count) // Overload:function(start, count, step) Enumerable.Range = function (start, count, step) { if (step == null) step = 1; return Enumerable.ToInfinity(start, step).Take(count); } // Overload:function(start, count) // Overload:function(start, count, step) Enumerable.RangeDown = function (start, count, step) { if (step == null) step = 1; return Enumerable.ToNegativeInfinity(start, step).Take(count); } // Overload:function(start, to) // Overload:function(start, to, step) Enumerable.RangeTo = function (start, to, step) { if (step == null) step = 1; return (start < to) ? Enumerable.ToInfinity(start, step).TakeWhile(function (i) { return i <= to; }) : Enumerable.ToNegativeInfinity(start, step).TakeWhile(function (i) { return i >= to; }) } // Overload:function(obj) // Overload:function(obj, num) Enumerable.Repeat = function (obj, num) { if (num != null) return Enumerable.Repeat(obj).Take(num); return new Enumerable(function () { return new IEnumerator( Functions.Blank, function () { return this.Yield(obj); }, Functions.Blank); }); } Enumerable.RepeatWithFinalize = function (initializer, finalizer) { initializer = Utils.CreateLambda(initializer); finalizer = Utils.CreateLambda(finalizer); return new Enumerable(function () { var element; return new IEnumerator( function () { element = initializer(); }, function () { return this.Yield(element); }, function () { if (element != null) { finalizer(element); element = null; } }); }); } // Overload:function(func) // Overload:function(func, count) Enumerable.Generate = function (func, count) { if (count != null) return Enumerable.Generate(func).Take(count); func = Utils.CreateLambda(func); return new Enumerable(function () { return new IEnumerator( Functions.Blank, function () { return this.Yield(func()); }, Functions.Blank); }); } // Overload:function() // Overload:function(start) // Overload:function(start, step) Enumerable.ToInfinity = function (start, step) { if (start == null) start = 0; if (step == null) step = 1; return new Enumerable(function () { var value; return new IEnumerator( function () { value = start - step }, function () { return this.Yield(value += step); }, Functions.Blank); }); } // Overload:function() // Overload:function(start) // Overload:function(start, step) Enumerable.ToNegativeInfinity = function (start, step) { if (start == null) start = 0; if (step == null) step = 1; return new Enumerable(function () { var value; return new IEnumerator( function () { value = start + step }, function () { return this.Yield(value -= step); }, Functions.Blank); }); } Enumerable.Unfold = function (seed, func) { func = Utils.CreateLambda(func); return new Enumerable(function () { var isFirst = true; var value; return new IEnumerator( Functions.Blank, function () { if (isFirst) { isFirst = false; value = seed; return this.Yield(value); } value = func(value); return this.Yield(value); }, Functions.Blank); }); } // Extension Methods Enumerable.prototype = { /* Projection and Filtering Methods */ // Overload:function(func) // Overload:function(func, resultSelector<element>) // Overload:function(func, resultSelector<element, nestLevel>) CascadeBreadthFirst: function (func, resultSelector) { var source = this; func = Utils.CreateLambda(func); resultSelector = Utils.CreateLambda(resultSelector); return new Enumerable(function () { var enumerator; var nestLevel = 0; var buffer = []; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { while (true) { if (enumerator.MoveNext()) { buffer.push(enumerator.Current()); return this.Yield(resultSelector(enumerator.Current(), nestLevel)); } var next = Enumerable.From(buffer).SelectMany(function (x) { return func(x); }); if (!next.Any()) { return false; } else { nestLevel++; buffer = []; Utils.Dispose(enumerator); enumerator = next.GetEnumerator(); } } }, function () { Utils.Dispose(enumerator); }); }); }, // Overload:function(func) // Overload:function(func, resultSelector<element>) // Overload:function(func, resultSelector<element, nestLevel>) CascadeDepthFirst: function (func, resultSelector) { var source = this; func = Utils.CreateLambda(func); resultSelector = Utils.CreateLambda(resultSelector); return new Enumerable(function () { var enumeratorStack = []; var enumerator; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { while (true) { if (enumerator.MoveNext()) { var value = resultSelector(enumerator.Current(), enumeratorStack.length); enumeratorStack.push(enumerator); enumerator = Enumerable.From(func(enumerator.Current())).GetEnumerator(); return this.Yield(value); } if (enumeratorStack.length <= 0) return false; Utils.Dispose(enumerator); enumerator = enumeratorStack.pop(); } }, function () { try { Utils.Dispose(enumerator); } finally { Enumerable.From(enumeratorStack).ForEach(function (s) { s.Dispose(); }) } }); }); }, Flatten: function () { var source = this; return new Enumerable(function () { var enumerator; var middleEnumerator = null; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { while (true) { if (middleEnumerator != null) { if (middleEnumerator.MoveNext()) { return this.Yield(middleEnumerator.Current()); } else { middleEnumerator = null; } } if (enumerator.MoveNext()) { if (enumerator.Current() instanceof Array) { Utils.Dispose(middleEnumerator); middleEnumerator = Enumerable.From(enumerator.Current()) .SelectMany(Functions.Identity) .Flatten() .GetEnumerator(); continue; } else { return this.Yield(enumerator.Current()); } } return false; } }, function () { try { Utils.Dispose(enumerator); } finally { Utils.Dispose(middleEnumerator); } }); }); }, Pairwise: function (selector) { var source = this; selector = Utils.CreateLambda(selector); return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.GetEnumerator(); enumerator.MoveNext(); }, function () { var prev = enumerator.Current(); return (enumerator.MoveNext()) ? this.Yield(selector(prev, enumerator.Current())) : false; }, function () { Utils.Dispose(enumerator); }); }); }, // Overload:function(func) // Overload:function(seed,func<value,element>) // Overload:function(seed,func<value,element>,resultSelector) Scan: function (seed, func, resultSelector) { if (resultSelector != null) return this.Scan(seed, func).Select(resultSelector); var isUseSeed; if (func == null) { func = Utils.CreateLambda(seed); // arguments[0] isUseSeed = false; } else { func = Utils.CreateLambda(func); isUseSeed = true; } var source = this; return new Enumerable(function () { var enumerator; var value; var isFirst = true; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { if (isFirst) { isFirst = false; if (!isUseSeed) { if (enumerator.MoveNext()) { return this.Yield(value = enumerator.Current()); } } else { return this.Yield(value = seed); } } return (enumerator.MoveNext()) ? this.Yield(value = func(value, enumerator.Current())) : false; }, function () { Utils.Dispose(enumerator); }); }); }, // Overload:function(selector<element>) // Overload:function(selector<element,index>) Select: function (selector) { var source = this; selector = Utils.CreateLambda(selector); return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { return (enumerator.MoveNext()) ? this.Yield(selector(enumerator.Current(), index++)) : false; }, function () { Utils.Dispose(enumerator); }) }); }, // Overload:function(collectionSelector<element>) // Overload:function(collectionSelector<element,index>) // Overload:function(collectionSelector<element>,resultSelector) // Overload:function(collectionSelector<element,index>,resultSelector) SelectMany: function (collectionSelector, resultSelector) { var source = this; collectionSelector = Utils.CreateLambda(collectionSelector); if (resultSelector == null) resultSelector = function (a, b) { return b; } resultSelector = Utils.CreateLambda(resultSelector); return new Enumerable(function () { var enumerator; var middleEnumerator = undefined; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { if (middleEnumerator === undefined) { if (!enumerator.MoveNext()) return false; } do { if (middleEnumerator == null) { var middleSeq = collectionSelector(enumerator.Current(), index++); middleEnumerator = Enumerable.From(middleSeq).GetEnumerator(); } if (middleEnumerator.MoveNext()) { return this.Yield(resultSelector(enumerator.Current(), middleEnumerator.Current())); } Utils.Dispose(middleEnumerator); middleEnumerator = null; } while (enumerator.MoveNext()) return false; }, function () { try { Utils.Dispose(enumerator); } finally { Utils.Dispose(middleEnumerator); } }) }); }, // Overload:function(predicate<element>) // Overload:function(predicate<element,index>) Where: function (predicate) { predicate = Utils.CreateLambda(predicate); var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { while (enumerator.MoveNext()) { if (predicate(enumerator.Current(), index++)) { return this.Yield(enumerator.Current()); } } return false; }, function () { Utils.Dispose(enumerator); }) }); }, OfType: function (type) { var typeName; switch (type) { case Number: typeName = Types.Number; break; case String: typeName = Types.String; break; case Boolean: typeName = Types.Boolean; break; case Function: typeName = Types.Function; break; default: typeName = null; break; } return (typeName === null) ? this.Where(function (x) { return x instanceof type }) : this.Where(function (x) { return typeof x === typeName }); }, // Overload:function(second,selector<outer,inner>) // Overload:function(second,selector<outer,inner,index>) Zip: function (second, selector) { selector = Utils.CreateLambda(selector); var source = this; return new Enumerable(function () { var firstEnumerator; var secondEnumerator; var index = 0; return new IEnumerator( function () { firstEnumerator = source.GetEnumerator(); secondEnumerator = Enumerable.From(second).GetEnumerator(); }, function () { if (firstEnumerator.MoveNext() && secondEnumerator.MoveNext()) { return this.Yield(selector(firstEnumerator.Current(), secondEnumerator.Current(), index++)); } return false; }, function () { try { Utils.Dispose(firstEnumerator); } finally { Utils.Dispose(secondEnumerator); } }) }); }, /* Join Methods */ // Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector) // Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) Join: function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) { outerKeySelector = Utils.CreateLambda(outerKeySelector); innerKeySelector = Utils.CreateLambda(innerKeySelector); resultSelector = Utils.CreateLambda(resultSelector); compareSelector = Utils.CreateLambda(compareSelector); var source = this; return new Enumerable(function () { var outerEnumerator; var lookup; var innerElements = null; var innerCount = 0; return new IEnumerator( function () { outerEnumerator = source.GetEnumerator(); lookup = Enumerable.From(inner).ToLookup(innerKeySelector, Functions.Identity, compareSelector); }, function () { while (true) { if (innerElements != null) { var innerElement = innerElements[innerCount++]; if (innerElement !== undefined) { return this.Yield(resultSelector(outerEnumerator.Current(), innerElement)); } innerElement = null; innerCount = 0; } if (outerEnumerator.MoveNext()) { var key = outerKeySelector(outerEnumerator.Current()); innerElements = lookup.Get(key).ToArray(); } else { return false; } } }, function () { Utils.Dispose(outerEnumerator); }) }); }, // Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector) // Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) GroupJoin: function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) { outerKeySelector = Utils.CreateLambda(outerKeySelector); innerKeySelector = Utils.CreateLambda(innerKeySelector); resultSelector = Utils.CreateLambda(resultSelector); compareSelector = Utils.CreateLambda(compareSelector); var source = this; return new Enumerable(function () { var enumerator = source.GetEnumerator(); var lookup = null; return new IEnumerator( function () { enumerator = source.GetEnumerator(); lookup = Enumerable.From(inner).ToLookup(innerKeySelector, Functions.Identity, compareSelector); }, function () { if (enumerator.MoveNext()) { var innerElement = lookup.Get(outerKeySelector(enumerator.Current())); return this.Yield(resultSelector(enumerator.Current(), innerElement)); } return false; }, function () { Utils.Dispose(enumerator); }) }); }, /* Set Methods */ All: function (predicate) { predicate = Utils.CreateLambda(predicate); var result = true; this.ForEach(function (x) { if (!predicate(x)) { result = false; return false; // break } }); return result; }, // Overload:function() // Overload:function(predicate) Any: function (predicate) { predicate = Utils.CreateLambda(predicate); var enumerator = this.GetEnumerator(); try { if (arguments.length == 0) return enumerator.MoveNext(); // case:function() while (enumerator.MoveNext()) // case:function(predicate) { if (predicate(enumerator.Current())) return true; } return false; } finally { Utils.Dispose(enumerator); } }, Concat: function (second) { var source = this; return new Enumerable(function () { var firstEnumerator; var secondEnumerator; return new IEnumerator( function () { firstEnumerator = source.GetEnumerator(); }, function () { if (secondEnumerator == null) { if (firstEnumerator.MoveNext()) return this.Yield(firstEnumerator.Current()); secondEnumerator = Enumerable.From(second).GetEnumerator(); } if (secondEnumerator.MoveNext()) return this.Yield(secondEnumerator.Current()); return false; }, function () { try { Utils.Dispose(firstEnumerator); } finally { Utils.Dispose(secondEnumerator); } }) }); }, Insert: function (index, second) { var source = this; return new Enumerable(function () { var firstEnumerator; var secondEnumerator; var count = 0; var isEnumerated = false; return new IEnumerator( function () { firstEnumerator = source.GetEnumerator(); secondEnumerator = Enumerable.From(second).GetEnumerator(); }, function () { if (count == index && secondEnumerator.MoveNext()) { isEnumerated = true; return this.Yield(secondEnumerator.Current()); } if (firstEnumerator.MoveNext()) { count++; return this.Yield(firstEnumerator.Current()); } if (!isEnumerated && secondEnumerator.MoveNext()) { return this.Yield(secondEnumerator.Current()); } return false; }, function () { try { Utils.Dispose(firstEnumerator); } finally { Utils.Dispose(secondEnumerator); } }) }); }, Alternate: function (value) { value = Enumerable.Return(value); return this.SelectMany(function (elem) { return Enumerable.Return(elem).Concat(value); }).TakeExceptLast(); }, // Overload:function(value) // Overload:function(value, compareSelector) Contains: function (value, compareSelector) { compareSelector = Utils.CreateLambda(compareSelector); var enumerator = this.GetEnumerator(); try { while (enumerator.MoveNext()) { if (compareSelector(enumerator.Current()) === value) return true; } return false; } finally { Utils.Dispose(enumerator) } }, DefaultIfEmpty: function (defaultValue) { var source = this; return new Enumerable(function () { var enumerator; var isFirst = true; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { if (enumerator.MoveNext()) { isFirst = false; return this.Yield(enumerator.Current()); } else if (isFirst) { isFirst = false; return this.Yield(defaultValue); } return false; }, function () { Utils.Dispose(enumerator); }) }); }, // Overload:function() // Overload:function(compareSelector) Distinct: function (compareSelector) { return this.Except(Enumerable.Empty(), compareSelector); }, // Overload:function(second) // Overload:function(second, compareSelector) Except: function (second, compareSelector) { compareSelector = Utils.CreateLambda(compareSelector); var source = this; return new Enumerable(function () { var enumerator; var keys; return new IEnumerator( function () { enumerator = source.GetEnumerator(); keys = new Dictionary(compareSelector); Enumerable.From(second).ForEach(function (key) { keys.Add(key); }); }, function () { while (enumerator.MoveNext()) { var current = enumerator.Current(); if (!keys.Contains(current)) { keys.Add(current); return this.Yield(current); } } return false; }, function () { Utils.Dispose(enumerator); }) }); }, // Overload:function(second) // Overload:function(second, compareSelector) Intersect: function (second, compareSelector) { compareSelector = Utils.CreateLambda(compareSelector); var source = this; return new Enumerable(function () { var enumerator; var keys; var outs; return new IEnumerator( function () { enumerator = source.GetEnumerator(); keys = new Dictionary(compareSelector); Enumerable.From(second).ForEach(function (key) { keys.Add(key); }); outs = new Dictionary(compareSelector); }, function () { while (enumerator.MoveNext()) { var current = enumerator.Current(); if (!outs.Contains(current) && keys.Contains(current)) { outs.Add(current); return this.Yield(current); } } return false; }, function () { Utils.Dispose(enumerator); }) }); }, // Overload:function(second) // Overload:function(second, compareSelector) SequenceEqual: function (second, compareSelector) { compareSelector = Utils.CreateLambda(compareSelector); var firstEnumerator = this.GetEnumerator(); try { var secondEnumerator = Enumerable.From(second).GetEnumerator(); try { while (firstEnumerator.MoveNext()) { if (!secondEnumerator.MoveNext() || compareSelector(firstEnumerator.Current()) !== compareSelector(secondEnumerator.Current())) { return false; } } if (secondEnumerator.MoveNext()) return false; return true; } finally { Utils.Dispose(secondEnumerator); } } finally { Utils.Dispose(firstEnumerator); } }, Union: function (second, compareSelector) { compareSelector = Utils.CreateLambda(compareSelector); var source = this; return new Enumerable(function () { var firstEnumerator; var secondEnumerator; var keys; return new IEnumerator( function () { firstEnumerator = source.GetEnumerator(); keys = new Dictionary(compareSelector); }, function () { var current; if (secondEnumerator === undefined) { while (firstEnumerator.MoveNext()) { current = firstEnumerator.Current(); if (!keys.Contains(current)) { keys.Add(current); return this.Yield(current); } } secondEnumerator = Enumerable.From(second).GetEnumerator(); } while (secondEnumerator.MoveNext()) { current = secondEnumerator.Current(); if (!keys.Contains(current)) { keys.Add(current); return this.Yield(current); } } return false; }, function () { try { Utils.Dispose(firstEnumerator); } finally { Utils.Dispose(secondEnumerator); } }) }); }, /* Ordering Methods */ OrderBy: function (keySelector) { return new OrderedEnumerable(this, keySelector, false); }, OrderByDescending: function (keySelector) { return new OrderedEnumerable(this, keySelector, true); }, Reverse: function () { var source = this; return new Enumerable(function () { var buffer; var index; return new IEnumerator( function () { buffer = source.ToArray(); index = buffer.length; }, function () { return (index > 0) ? this.Yield(buffer[--index]) : false; }, Functions.Blank) }); }, Shuffle: function () { var source = this; return new Enumerable(function () { var buffer; return new IEnumerator( function () { buffer = source.ToArray(); }, function () { if (buffer.length > 0) { var i = Math.floor(Math.random() * buffer.length); return this.Yield(buffer.splice(i, 1)[0]); } return false; }, Functions.Blank) }); }, /* Grouping Methods */ // Overload:function(keySelector) // Overload:function(keySelector,elementSelector) // Overload:function(keySelector,elementSelector,resultSelector) // Overload:function(keySelector,elementSelector,resultSelector,compareSelector) GroupBy: function (keySelector, elementSelector, resultSelector, compareSelector) { var source = this; keySelector = Utils.CreateLambda(keySelector); elementSelector = Utils.CreateLambda(elementSelector); if (resultSelector != null) resultSelector = Utils.CreateLambda(resultSelector); compareSelector = Utils.CreateLambda(compareSelector); return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.ToLookup(keySelector, elementSelector, compareSelector) .ToEnumerable() .GetEnumerator(); }, function () { while (enumerator.MoveNext()) { return (resultSelector == null) ? this.Yield(enumerator.Current()) : this.Yield(resultSelector(enumerator.Current().Key(), enumerator.Current())); } return false; }, function () { Utils.Dispose(enumerator); }) }); }, // Overload:function(keySelector) // Overload:function(keySelector,elementSelector) // Overload:function(keySelector,elementSelector,resultSelector) // Overload:function(keySelector,elementSelector,resultSelector,compareSelector) PartitionBy: function (keySelector, elementSelector, resultSelector, compareSelector) { var source = this; keySelector = Utils.CreateLambda(keySelector); elementSelector = Utils.CreateLambda(elementSelector); compareSelector = Utils.CreateLambda(compareSelector); var hasResultSelector; if (resultSelector == null) { hasResultSelector = false; resultSelector = function (key, group) { return new Grouping(key, group) } } else { hasResultSelector = true; resultSelector = Utils.CreateLambda(resultSelector); } return new Enumerable(function () { var enumerator; var key; var compareKey; var group = []; return new IEnumerator( function () { enumerator = source.GetEnumerator(); if (enumerator.MoveNext()) { key = keySelector(enumerator.Current()); compareKey = compareSelector(key); group.push(elementSelector(enumerator.Current())); } }, function () { var hasNext; while ((hasNext = enumerator.MoveNext()) == true) { if (compareKey === compareSelector(keySelector(enumerator.Current()))) { group.push(elementSelector(enumerator.Current())); } else break; } if (group.length > 0) { var result = (hasResultSelector) ? resultSelector(key, Enumerable.From(group)) : resultSelector(key, group); if (hasNext) { key = keySelector(enumerator.Current()); compareKey = compareSelector(key); group = [elementSelector(enumerator.Current())]; } else group = []; return this.Yield(result); } return false; }, function () { Utils.Dispose(enumerator); }) }); }, BufferWithCount: function (count) { var source = this; return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { var array = []; var index = 0; while (enumerator.MoveNext()) { array.push(enumerator.Current()); if (++index >= count) return this.Yield(array); } if (array.length > 0) return this.Yield(array); return false; }, function () { Utils.Dispose(enumerator); }) }); }, /* Aggregate Methods */ // Overload:function(func) // Overload:function(seed,func) // Overload:function(seed,func,resultSelector) Aggregate: function (seed, func, resultSelector) { return this.Scan(seed, func, resultSelector).Last(); }, // Overload:function() // Overload:function(selector) Average: function (selector) { selector = Utils.CreateLambda(selector); var sum = 0; var count = 0; this.ForEach(function (x) { sum += selector(x); ++count; }); return sum / count; }, // Overload:function() // Overload:function(predicate) Count: function (predicate) { predicate = (predicate == null) ? Functions.True : Utils.CreateLambda(predicate); var count = 0; this.ForEach(function (x, i) { if (predicate(x, i)) ++count; }); return count; }, // Overload:function() // Overload:function(selector) Max: function (selector) { if (selector == null) selector = Functions.Identity; return this.Select(selector).Aggregate(function (a, b) { return (a > b) ? a : b; }); }, // Overload:function() // Overload:function(selector) Min: function (selector) { if (selector == null) selector = Functions.Identity; return this.Select(selector).Aggregate(function (a, b) { return (a < b) ? a : b; }); }, MaxBy: function (keySelector) { keySelector = Utils.CreateLambda(keySelector); return this.Aggregate(function (a, b) { return (keySelector(a) > keySelector(b)) ? a : b }); }, MinBy: function (keySelector) { keySelector = Utils.CreateLambda(keySelector); return this.Aggregate(function (a, b) { return (keySelector(a) < keySelector(b)) ? a : b }); }, // Overload:function() // Overload:function(selector) Sum: function (selector) { if (selector == null) selector = Functions.Identity; return this.Select(selector).Aggregate(0, function (a, b) { return a + b; }); }, /* Paging Methods */ ElementAt: function (index) { var value; var found = false; this.ForEach(function (x, i) { if (i == index) { value = x; found = true; return false; } }); if (!found) throw new Error("index is less than 0 or greater than or equal to the number of elements in source."); return value; }, ElementAtOrDefault: function (index, defaultValue) { var value; var found = false; this.ForEach(function (x, i) { if (i == index) { value = x; found = true; return false; } }); return (!found) ? defaultValue : value; }, // Overload:function() // Overload:function(predicate) First: function (predicate) { if (predicate != null) return this.Where(predicate).First(); var value; var found = false; this.ForEach(function (x) { value = x; found = true; return false; }); if (!found) throw new Error("First:No element satisfies the condition."); return value; }, // Overload:function(defaultValue) // Overload:function(defaultValue,predicate) FirstOrDefault: function (defaultValue, predicate) { if (predicate != null) return this.Where(predicate).FirstOrDefault(defaultValue); var value; var found = false; this.ForEach(function (x) { value = x; found = true; return false; }); return (!found) ? defaultValue : value; }, // Overload:function() // Overload:function(predicate) Last: function (predicate) { if (predicate != null) return this.Where(predicate).Last(); var value; var found = false; this.ForEach(function (x) { found = true; value = x; }); if (!found) throw new Error("Last:No element satisfies the condition."); return value; }, // Overload:function(defaultValue) // Overload:function(defaultValue,predicate) LastOrDefault: function (defaultValue, predicate) { if (predicate != null) return this.Where(predicate).LastOrDefault(defaultValue); var value; var found = false; this.ForEach(function (x) { found = true; value = x; }); return (!found) ? defaultValue : value; }, // Overload:function() // Overload:function(predicate) Single: function (predicate) { if (predicate != null) return this.Where(predicate).Single(); var value; var found = false; this.ForEach(function (x) { if (!found) { found = true; value = x; } else throw new Error("Single:sequence contains more than one element."); }); if (!found) throw new Error("Single:No element satisfies the condition."); return value; }, // Overload:function(defaultValue) // Overload:function(defaultValue,predicate) SingleOrDefault: function (defaultValue, predicate) { if (predicate != null) return this.Where(predicate).SingleOrDefault(defaultValue); var value; var found = false; this.ForEach(function (x) { if (!found) { found = true; value = x; } else throw new Error("Single:sequence contains more than one element."); }); return (!found) ? defaultValue : value; }, Skip: function (count) { var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); while (index++ < count && enumerator.MoveNext()) { }; }, function () { return (enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; }, function () { Utils.Dispose(enumerator); }) }); }, // Overload:function(predicate<element>) // Overload:function(predicate<element,index>) SkipWhile: function (predicate) { predicate = Utils.CreateLambda(predicate); var source = this; return new Enumerable(function () { var enumerator; var index = 0; var isSkipEnd = false; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { while (!isSkipEnd) { if (enumerator.MoveNext()) { if (!predicate(enumerator.Current(), index++)) { isSkipEnd = true; return this.Yield(enumerator.Current()); } continue; } else return false; } return (enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; }, function () { Utils.Dispose(enumerator); }); }); }, Take: function (count) { var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { return (index++ < count && enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; }, function () { Utils.Dispose(enumerator); } ) }); }, // Overload:function(predicate<element>) // Overload:function(predicate<element,index>) TakeWhile: function (predicate) { predicate = Utils.CreateLambda(predicate); var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { return (enumerator.MoveNext() && predicate(enumerator.Current(), index++)) ? this.Yield(enumerator.Current()) : false; }, function () { Utils.Dispose(enumerator); }); }); }, // Overload:function() // Overload:function(count) TakeExceptLast: function (count) { if (count == null) count = 1; var source = this; return new Enumerable(function () { if (count <= 0) return source.GetEnumerator(); // do nothing var enumerator; var q = []; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { while (enumerator.MoveNext()) { if (q.length == count) { q.push(enumerator.Current()); return this.Yield(q.shift()); } q.push(enumerator.Current()); } return false; }, function () { Utils.Dispose(enumerator); }); }); }, TakeFromLast: function (count) { if (count <= 0 || count == null) return Enumerable.Empty(); var source = this; return new Enumerable(function () { var sourceEnumerator; var enumerator; var q = []; return new IEnumerator( function () { sourceEnumerator = source.GetEnumerator(); }, function () { while (sourceEnumerator.MoveNext()) { if (q.length == count) q.shift() q.push(sourceEnumerator.Current()); } if (enumerator == null) { enumerator = Enumerable.From(q).GetEnumerator(); } return (enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; }, function () { Utils.Dispose(enumerator); }); }); }, IndexOf: function (item) { var found = null; this.ForEach(function (x, i) { if (x === item) { found = i; return true; } }); return (found !== null) ? found : -1; }, LastIndexOf: function (item) { var result = -1; this.ForEach(function (x, i) { if (x === item) result = i; }); return result; }, /* Convert Methods */ ToArray: function () { var array = []; this.ForEach(function (x) { array.push(x) }); return array; }, // Overload:function(keySelector) // Overload:function(keySelector, elementSelector) // Overload:function(keySelector, elementSelector, compareSelector) ToLookup: function (keySelector, elementSelector, compareSelector) { keySelector = Utils.CreateLambda(keySelector); elementSelector = Utils.CreateLambda(elementSelector); compareSelector = Utils.CreateLambda(compareSelector); var dict = new Dictionary(compareSelector); this.ForEach(function (x) { var key = keySelector(x); var element = elementSelector(x); var array = dict.Get(key); if (array !== undefined) array.push(element); else dict.Add(key, [element]); }); return new Lookup(dict); }, ToObject: function (keySelector, elementSelector) { keySelector = Utils.CreateLambda(keySelector); elementSelector = Utils.CreateLambda(elementSelector); var obj = {}; this.ForEach(function (x) { obj[keySelector(x)] = elementSelector(x); }); return obj; }, // Overload:function(keySelector, elementSelector) // Overload:function(keySelector, elementSelector, compareSelector) ToDictionary: function (keySelector, elementSelector, compareSelector) { keySelector = Utils.CreateLambda(keySelector); elementSelector = Utils.CreateLambda(elementSelector); compareSelector = Utils.CreateLambda(compareSelector); var dict = new Dictionary(compareSelector); this.ForEach(function (x) { dict.Add(keySelector(x), elementSelector(x)); }); return dict; }, // Overload:function() // Overload:function(replacer) // Overload:function(replacer, space) ToJSON: function (replacer, space) { return JSON.stringify(this.ToArray(), replacer, space); }, // Overload:function() // Overload:function(separator) // Overload:function(separator,selector) ToString: function (separator, selector) { if (separator == null) separator = ""; if (selector == null) selector = Functions.Identity; return this.Select(selector).ToArray().join(separator); }, /* Action Methods */ // Overload:function(action<element>) // Overload:function(action<element,index>) Do: function (action) { var source = this; action = Utils.CreateLambda(action); return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { if (enumerator.MoveNext()) { action(enumerator.Current(), index++); return this.Yield(enumerator.Current()); } return false; }, function () { Utils.Dispose(enumerator); }); }); }, // Overload:function(action<element>) // Overload:function(action<element,index>) // Overload:function(func<element,bool>) // Overload:function(func<element,index,bool>) ForEach: function (action) { action = Utils.CreateLambda(action); var index = 0; var enumerator = this.GetEnumerator(); try { while (enumerator.MoveNext()) { if (action(enumerator.Current(), index++) === false) break; } } finally { Utils.Dispose(enumerator); } }, // Overload:function() // Overload:function(separator) // Overload:function(separator,selector) Write: function (separator, selector) { if (separator == null) separator = ""; selector = Utils.CreateLambda(selector); var isFirst = true; this.ForEach(function (item) { if (isFirst) isFirst = false; else document.write(separator); document.write(selector(item)); }); }, // Overload:function() // Overload:function(selector) WriteLine: function (selector) { selector = Utils.CreateLambda(selector); this.ForEach(function (item) { document.write(selector(item)); document.write("<br />"); }); }, Force: function () { var enumerator = this.GetEnumerator(); try { while (enumerator.MoveNext()) { } } finally { Utils.Dispose(enumerator); } }, /* Functional Methods */ Let: function (func) { func = Utils.CreateLambda(func); var source = this; return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = Enumerable.From(func(source)).GetEnumerator(); }, function () { return (enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; }, function () { Utils.Dispose(enumerator); }) }); }, Share: function () { var source = this; var sharedEnumerator; return new Enumerable(function () { return new IEnumerator( function () { if (sharedEnumerator == null) { sharedEnumerator = source.GetEnumerator(); } }, function () { return (sharedEnumerator.MoveNext()) ? this.Yield(sharedEnumerator.Current()) : false; }, Functions.Blank ) }); }, MemoizeAll: function () { var source = this; var cache; var enumerator; return new Enumerable(function () { var index = -1; return new IEnumerator( function () { if (enumerator == null) { enumerator = source.GetEnumerator(); cache = []; } }, function () { index++; if (cache.length <= index) { return (enumerator.MoveNext()) ? this.Yield(cache[index] = enumerator.Current()) : false; } return this.Yield(cache[index]); }, Functions.Blank ) }); }, /* Error Handling Methods */ Catch: function (handler) { handler = Utils.CreateLambda(handler); var source = this; return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { try { return (enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; } catch (e) { handler(e); return false; } }, function () { Utils.Dispose(enumerator); }); }); }, Finally: function (finallyAction) { finallyAction = Utils.CreateLambda(finallyAction); var source = this; return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { return (enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; }, function () { try { Utils.Dispose(enumerator); } finally { finallyAction(); } }); }); }, /* For Debug Methods */ // Overload:function() // Overload:function(message) // Overload:function(message,selector) Trace: function (message, selector) { if (message == null) message = "Trace"; selector = Utils.CreateLambda(selector); return this.Do(function (item) { console.log(message, ":", selector(item)); }); } } // private // static functions var Functions = { Identity: function (x) { return x; }, True: function () { return true; }, Blank: function () { } } // static const var Types = { Boolean: typeof true, Number: typeof 0, String: typeof "", Object: typeof {}, Undefined: typeof undefined, Function: typeof function () { } } // static utility methods var Utils = { // Create anonymous function from lambda expression string CreateLambda: function (expression) { if (expression == null) return Functions.Identity; if (typeof expression == Types.String) { if (expression == "") { return Functions.Identity; } else if (expression.indexOf("=>") == -1) { return new Function("$,$$,$$$,$$$$", "return " + expression); } else { var expr = expression.match(/^[(\s]*([^()]*?)[)\s]*=>(.*)/); return new Function(expr[1], "return " + expr[2]); } } return expression; }, IsIEnumerable: function (obj) { if (typeof Enumerator != Types.Undefined) { try { new Enumerator(obj); return true; } catch (e) { } } return false; }, Compare: function (a, b) { return (a === b) ? 0 : (a > b) ? 1 : -1; }, Dispose: function (obj) { if (obj != null) obj.Dispose(); } } // IEnumerator State var State = { Before: 0, Running: 1, After: 2 } // name "Enumerator" is conflict JScript's "Enumerator" var IEnumerator = function (initialize, tryGetNext, dispose) { var yielder = new Yielder(); var state = State.Before; this.Current = yielder.Current; this.MoveNext = function () { try { switch (state) { case State.Before: state = State.Running; initialize(); // fall through case State.Running: if (tryGetNext.apply(yielder)) { return true; } else { this.Dispose(); return false; } case State.After: return false; } } catch (e) { this.Dispose(); throw e; } } this.Dispose = function () { if (state != State.Running) return; try { dispose(); } finally { state = State.After; } } } // for tryGetNext var Yielder = function () { var current = null; this.Current = function () { return current; } this.Yield = function (value) { current = value; return true; } } // for OrderBy/ThenBy var OrderedEnumerable = function (source, keySelector, descending, parent) { this.source = source; this.keySelector = Utils.CreateLambda(keySelector); this.descending = descending; this.parent = parent; } OrderedEnumerable.prototype = new Enumerable(); OrderedEnumerable.prototype.CreateOrderedEnumerable = function (keySelector, descending) { return new OrderedEnumerable(this.source, keySelector, descending, this); } OrderedEnumerable.prototype.ThenBy = function (keySelector) { return this.CreateOrderedEnumerable(keySelector, false); } OrderedEnumerable.prototype.ThenByDescending = function (keySelector) { return this.CreateOrderedEnumerable(keySelector, true); } OrderedEnumerable.prototype.GetEnumerator = function () { var self = this; var buffer; var indexes; var index = 0; return new IEnumerator( function () { buffer = []; indexes = []; self.source.ForEach(function (item, index) { buffer.push(item); indexes.push(index); }); var sortContext = SortContext.Create(self, null); sortContext.GenerateKeys(buffer); indexes.sort(function (a, b) { return sortContext.Compare(a, b); }); }, function () { return (index < indexes.length) ? this.Yield(buffer[indexes[index++]]) : false; }, Functions.Blank ) } var SortContext = function (keySelector, descending, child) { this.keySelector = keySelector; this.descending = descending; this.child = child; this.keys = null; } SortContext.Create = function (orderedEnumerable, currentContext) { var context = new SortContext(orderedEnumerable.keySelector, orderedEnumerable.descending, currentContext); if (orderedEnumerable.parent != null) return SortContext.Create(orderedEnumerable.parent, context); return context; } SortContext.prototype.GenerateKeys = function (source) { var len = source.length; var keySelector = this.keySelector; var keys = new Array(len); for (var i = 0; i < len; i++) keys[i] = keySelector(source[i]); this.keys = keys; if (this.child != null) this.child.GenerateKeys(source); } SortContext.prototype.Compare = function (index1, index2) { var comparison = Utils.Compare(this.keys[index1], this.keys[index2]); if (comparison == 0) { if (this.child != null) return this.child.Compare(index1, index2) comparison = Utils.Compare(index1, index2); } return (this.descending) ? -comparison : comparison; } // optimize array or arraylike object var ArrayEnumerable = function (source) { this.source = source; } ArrayEnumerable.prototype = new Enumerable(); ArrayEnumerable.prototype.Any = function (predicate) { return (predicate == null) ? (this.source.length > 0) : Enumerable.prototype.Any.apply(this, arguments); } ArrayEnumerable.prototype.Count = function (predicate) { return (predicate == null) ? this.source.length : Enumerable.prototype.Count.apply(this, arguments); } ArrayEnumerable.prototype.ElementAt = function (index) { return (0 <= index && index < this.source.length) ? this.source[index] : Enumerable.prototype.ElementAt.apply(this, arguments); } ArrayEnumerable.prototype.ElementAtOrDefault = function (index, defaultValue) { return (0 <= index && index < this.source.length) ? this.source[index] : defaultValue; } ArrayEnumerable.prototype.First = function (predicate) { return (predicate == null && this.source.length > 0) ? this.source[0] : Enumerable.prototype.First.apply(this, arguments); } ArrayEnumerable.prototype.FirstOrDefault = function (defaultValue, predicate) { if (predicate != null) { return Enumerable.prototype.FirstOrDefault.apply(this, arguments); } return this.source.length > 0 ? this.source[0] : defaultValue; } ArrayEnumerable.prototype.Last = function (predicate) { return (predicate == null && this.source.length > 0) ? this.source[this.source.length - 1] : Enumerable.prototype.Last.apply(this, arguments); } ArrayEnumerable.prototype.LastOrDefault = function (defaultValue, predicate) { if (predicate != null) { return Enumerable.prototype.LastOrDefault.apply(this, arguments); } return this.source.length > 0 ? this.source[this.source.length - 1] : defaultValue; } ArrayEnumerable.prototype.Skip = function (count) { var source = this.source; return new Enumerable(function () { var index; return new IEnumerator( function () { index = (count < 0) ? 0 : count }, function () { return (index < source.length) ? this.Yield(source[index++]) : false; }, Functions.Blank); }); }; ArrayEnumerable.prototype.TakeExceptLast = function (count) { if (count == null) count = 1; return this.Take(this.source.length - count); } ArrayEnumerable.prototype.TakeFromLast = function (count) { return this.Skip(this.source.length - count); } ArrayEnumerable.prototype.Reverse = function () { var source = this.source; return new Enumerable(function () { var index; return new IEnumerator( function () { index = source.length; }, function () { return (index > 0) ? this.Yield(source[--index]) : false; }, Functions.Blank) }); } ArrayEnumerable.prototype.SequenceEqual = function (second, compareSelector) { if ((second instanceof ArrayEnumerable || second instanceof Array) && compareSelector == null && Enumerable.From(second).Count() != this.Count()) { return false; } return Enumerable.prototype.SequenceEqual.apply(this, arguments); } ArrayEnumerable.prototype.ToString = function (separator, selector) { if (selector != null || !(this.source instanceof Array)) { return Enumerable.prototype.ToString.apply(this, arguments); } if (separator == null) separator = ""; return this.source.join(separator); } ArrayEnumerable.prototype.GetEnumerator = function () { var source = this.source; var index = 0; return new IEnumerator( Functions.Blank, function () { return (index < source.length) ? this.Yield(source[index++]) : false; }, Functions.Blank); } // Collections var Dictionary = (function () { // static utility methods var HasOwnProperty = function (target, key) { return Object.prototype.hasOwnProperty.call(target, key); } var ComputeHashCode = function (obj) { if (obj === null) return "null"; if (obj === undefined) return "undefined"; return (typeof obj.toString === Types.Function) ? obj.toString() : Object.prototype.toString.call(obj); } // LinkedList for Dictionary var HashEntry = function (key, value) { this.Key = key; this.Value = value; this.Prev = null; this.Next = null; } var EntryList = function () { this.First = null; this.Last = null; } EntryList.prototype = { AddLast: function (entry) { if (this.Last != null) { this.Last.Next = entry; entry.Prev = this.Last; this.Last = entry; } else this.First = this.Last = entry; }, Replace: function (entry, newEntry) { if (entry.Prev != null) { entry.Prev.Next = newEntry; newEntry.Prev = entry.Prev; } else this.First = newEntry; if (entry.Next != null) { entry.Next.Prev = newEntry; newEntry.Next = entry.Next; } else this.Last = newEntry; }, Remove: function (entry) { if (entry.Prev != null) entry.Prev.Next = entry.Next; else this.First = entry.Next; if (entry.Next != null) entry.Next.Prev = entry.Prev; else this.Last = entry.Prev; } } // Overload:function() // Overload:function(compareSelector) var Dictionary = function (compareSelector) { this.count = 0; this.entryList = new EntryList(); this.buckets = {}; // as Dictionary<string,List<object>> this.compareSelector = (compareSelector == null) ? Functions.Identity : compareSelector; } Dictionary.prototype = { Add: function (key, value) { var compareKey = this.compareSelector(key); var hash = ComputeHashCode(compareKey); var entry = new HashEntry(key, value); if (HasOwnProperty(this.buckets, hash)) { var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { if (this.compareSelector(array[i].Key) === compareKey) { this.entryList.Replace(array[i], entry); array[i] = entry; return; } } array.push(entry); } else { this.buckets[hash] = [entry]; } this.count++; this.entryList.AddLast(entry); }, Get: function (key) { var compareKey = this.compareSelector(key); var hash = ComputeHashCode(compareKey); if (!HasOwnProperty(this.buckets, hash)) return undefined; var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { var entry = array[i]; if (this.compareSelector(entry.Key) === compareKey) return entry.Value; } return undefined; }, Set: function (key, value) { var compareKey = this.compareSelector(key); var hash = ComputeHashCode(compareKey); if (HasOwnProperty(this.buckets, hash)) { var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { if (this.compareSelector(array[i].Key) === compareKey) { var newEntry = new HashEntry(key, value); this.entryList.Replace(array[i], newEntry); array[i] = newEntry; return true; } } } return false; }, Contains: function (key) { var compareKey = this.compareSelector(key); var hash = ComputeHashCode(compareKey); if (!HasOwnProperty(this.buckets, hash)) return false; var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { if (this.compareSelector(array[i].Key) === compareKey) return true; } return false; }, Clear: function () { this.count = 0; this.buckets = {}; this.entryList = new EntryList(); }, Remove: function (key) { var compareKey = this.compareSelector(key); var hash = ComputeHashCode(compareKey); if (!HasOwnProperty(this.buckets, hash)) return; var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { if (this.compareSelector(array[i].Key) === compareKey) { this.entryList.Remove(array[i]); array.splice(i, 1); if (array.length == 0) delete this.buckets[hash]; this.count--; return; } } }, Count: function () { return this.count; }, ToEnumerable: function () { var self = this; return new Enumerable(function () { var currentEntry; return new IEnumerator( function () { currentEntry = self.entryList.First }, function () { if (currentEntry != null) { var result = { Key: currentEntry.Key, Value: currentEntry.Value }; currentEntry = currentEntry.Next; return this.Yield(result); } return false; }, Functions.Blank); }); } } return Dictionary; })(); // dictionary = Dictionary<TKey, TValue[]> var Lookup = function (dictionary) { this.Count = function () { return dictionary.Count(); } this.Get = function (key) { return Enumerable.From(dictionary.Get(key)); } this.Contains = function (key) { return dictionary.Contains(key); } this.ToEnumerable = function () { return dictionary.ToEnumerable().Select(function (kvp) { return new Grouping(kvp.Key, kvp.Value); }); } } var Grouping = function (key, elements) { this.Key = function () { return key; } ArrayEnumerable.call(this, elements); } Grouping.prototype = new ArrayEnumerable(); // out to global return Enumerable; })() /*-------------------------------------------------------------------------- * linq.js - LINQ for JavaScript * ver 2.2.0.2 (Jan. 21th, 2011) * * created and maintained by neuecc <ils@neue.cc> * licensed under Microsoft Public License(Ms-PL) * http://neue.cc/ * http://linqjs.codeplex.com/ *--------------------------------------------------------------------------*/ jQuery.extend({ Enumerable: (function (){ var Enumerable = function (getEnumerator) { this.GetEnumerator = getEnumerator; } // Generator Enumerable.Choice = function () // variable argument { var args = (arguments[0] instanceof Array) ? arguments[0] : arguments; return new Enumerable(function () { return new IEnumerator( Functions.Blank, function () { return this.Yield(args[Math.floor(Math.random() * args.length)]); }, Functions.Blank); }); } Enumerable.Cycle = function () // variable argument { var args = (arguments[0] instanceof Array) ? arguments[0] : arguments; return new Enumerable(function () { var index = 0; return new IEnumerator( Functions.Blank, function () { if (index >= args.length) index = 0; return this.Yield(args[index++]); }, Functions.Blank); }); } Enumerable.Empty = function () { return new Enumerable(function () { return new IEnumerator( Functions.Blank, function () { return false; }, Functions.Blank); }); } Enumerable.From = function (obj) { if (obj == null) { return Enumerable.Empty(); } if (obj instanceof Enumerable) { return obj; } if (typeof obj == Types.Number || typeof obj == Types.Boolean) { return Enumerable.Repeat(obj, 1); } if (typeof obj == Types.String) { return new Enumerable(function () { var index = 0; return new IEnumerator( Functions.Blank, function () { return (index < obj.length) ? this.Yield(obj.charAt(index++)) : false; }, Functions.Blank); }); } if (typeof obj != Types.Function) { // array or array like object if (typeof obj.length == Types.Number) { return new ArrayEnumerable(obj); } // JScript's IEnumerable if (!(obj instanceof Object) && Utils.IsIEnumerable(obj)) { return new Enumerable(function () { var isFirst = true; var enumerator; return new IEnumerator( function () { enumerator = new Enumerator(obj); }, function () { if (isFirst) isFirst = false; else enumerator.moveNext(); return (enumerator.atEnd()) ? false : this.Yield(enumerator.item()); }, Functions.Blank); }); } } // case function/object : Create KeyValuePair[] return new Enumerable(function () { var array = []; var index = 0; return new IEnumerator( function () { for (var key in obj) { if (!(obj[key] instanceof Function)) { array.push({ Key: key, Value: obj[key] }); } } }, function () { return (index < array.length) ? this.Yield(array[index++]) : false; }, Functions.Blank); }); }, Enumerable.Return = function (element) { return Enumerable.Repeat(element, 1); } // Overload:function(input, pattern) // Overload:function(input, pattern, flags) Enumerable.Matches = function (input, pattern, flags) { if (flags == null) flags = ""; if (pattern instanceof RegExp) { flags += (pattern.ignoreCase) ? "i" : ""; flags += (pattern.multiline) ? "m" : ""; pattern = pattern.source; } if (flags.indexOf("g") === -1) flags += "g"; return new Enumerable(function () { var regex; return new IEnumerator( function () { regex = new RegExp(pattern, flags) }, function () { var match = regex.exec(input); return (match) ? this.Yield(match) : false; }, Functions.Blank); }); } // Overload:function(start, count) // Overload:function(start, count, step) Enumerable.Range = function (start, count, step) { if (step == null) step = 1; return Enumerable.ToInfinity(start, step).Take(count); } // Overload:function(start, count) // Overload:function(start, count, step) Enumerable.RangeDown = function (start, count, step) { if (step == null) step = 1; return Enumerable.ToNegativeInfinity(start, step).Take(count); } // Overload:function(start, to) // Overload:function(start, to, step) Enumerable.RangeTo = function (start, to, step) { if (step == null) step = 1; return (start < to) ? Enumerable.ToInfinity(start, step).TakeWhile(function (i) { return i <= to; }) : Enumerable.ToNegativeInfinity(start, step).TakeWhile(function (i) { return i >= to; }) } // Overload:function(obj) // Overload:function(obj, num) Enumerable.Repeat = function (obj, num) { if (num != null) return Enumerable.Repeat(obj).Take(num); return new Enumerable(function () { return new IEnumerator( Functions.Blank, function () { return this.Yield(obj); }, Functions.Blank); }); } Enumerable.RepeatWithFinalize = function (initializer, finalizer) { initializer = Utils.CreateLambda(initializer); finalizer = Utils.CreateLambda(finalizer); return new Enumerable(function () { var element; return new IEnumerator( function () { element = initializer(); }, function () { return this.Yield(element); }, function () { if (element != null) { finalizer(element); element = null; } }); }); } // Overload:function(func) // Overload:function(func, count) Enumerable.Generate = function (func, count) { if (count != null) return Enumerable.Generate(func).Take(count); func = Utils.CreateLambda(func); return new Enumerable(function () { return new IEnumerator( Functions.Blank, function () { return this.Yield(func()); }, Functions.Blank); }); } // Overload:function() // Overload:function(start) // Overload:function(start, step) Enumerable.ToInfinity = function (start, step) { if (start == null) start = 0; if (step == null) step = 1; return new Enumerable(function () { var value; return new IEnumerator( function () { value = start - step }, function () { return this.Yield(value += step); }, Functions.Blank); }); } // Overload:function() // Overload:function(start) // Overload:function(start, step) Enumerable.ToNegativeInfinity = function (start, step) { if (start == null) start = 0; if (step == null) step = 1; return new Enumerable(function () { var value; return new IEnumerator( function () { value = start + step }, function () { return this.Yield(value -= step); }, Functions.Blank); }); } Enumerable.Unfold = function (seed, func) { func = Utils.CreateLambda(func); return new Enumerable(function () { var isFirst = true; var value; return new IEnumerator( Functions.Blank, function () { if (isFirst) { isFirst = false; value = seed; return this.Yield(value); } value = func(value); return this.Yield(value); }, Functions.Blank); }); } // Extension Methods Enumerable.prototype = { /* Projection and Filtering Methods */ // Overload:function(func) // Overload:function(func, resultSelector<element>) // Overload:function(func, resultSelector<element, nestLevel>) CascadeBreadthFirst: function (func, resultSelector) { var source = this; func = Utils.CreateLambda(func); resultSelector = Utils.CreateLambda(resultSelector); return new Enumerable(function () { var enumerator; var nestLevel = 0; var buffer = []; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { while (true) { if (enumerator.MoveNext()) { buffer.push(enumerator.Current()); return this.Yield(resultSelector(enumerator.Current(), nestLevel)); } var next = Enumerable.From(buffer).SelectMany(function (x) { return func(x); }); if (!next.Any()) { return false; } else { nestLevel++; buffer = []; Utils.Dispose(enumerator); enumerator = next.GetEnumerator(); } } }, function () { Utils.Dispose(enumerator); }); }); }, // Overload:function(func) // Overload:function(func, resultSelector<element>) // Overload:function(func, resultSelector<element, nestLevel>) CascadeDepthFirst: function (func, resultSelector) { var source = this; func = Utils.CreateLambda(func); resultSelector = Utils.CreateLambda(resultSelector); return new Enumerable(function () { var enumeratorStack = []; var enumerator; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { while (true) { if (enumerator.MoveNext()) { var value = resultSelector(enumerator.Current(), enumeratorStack.length); enumeratorStack.push(enumerator); enumerator = Enumerable.From(func(enumerator.Current())).GetEnumerator(); return this.Yield(value); } if (enumeratorStack.length <= 0) return false; Utils.Dispose(enumerator); enumerator = enumeratorStack.pop(); } }, function () { try { Utils.Dispose(enumerator); } finally { Enumerable.From(enumeratorStack).ForEach(function (s) { s.Dispose(); }) } }); }); }, Flatten: function () { var source = this; return new Enumerable(function () { var enumerator; var middleEnumerator = null; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { while (true) { if (middleEnumerator != null) { if (middleEnumerator.MoveNext()) { return this.Yield(middleEnumerator.Current()); } else { middleEnumerator = null; } } if (enumerator.MoveNext()) { if (enumerator.Current() instanceof Array) { Utils.Dispose(middleEnumerator); middleEnumerator = Enumerable.From(enumerator.Current()) .SelectMany(Functions.Identity) .Flatten() .GetEnumerator(); continue; } else { return this.Yield(enumerator.Current()); } } return false; } }, function () { try { Utils.Dispose(enumerator); } finally { Utils.Dispose(middleEnumerator); } }); }); }, Pairwise: function (selector) { var source = this; selector = Utils.CreateLambda(selector); return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.GetEnumerator(); enumerator.MoveNext(); }, function () { var prev = enumerator.Current(); return (enumerator.MoveNext()) ? this.Yield(selector(prev, enumerator.Current())) : false; }, function () { Utils.Dispose(enumerator); }); }); }, // Overload:function(func) // Overload:function(seed,func<value,element>) // Overload:function(seed,func<value,element>,resultSelector) Scan: function (seed, func, resultSelector) { if (resultSelector != null) return this.Scan(seed, func).Select(resultSelector); var isUseSeed; if (func == null) { func = Utils.CreateLambda(seed); // arguments[0] isUseSeed = false; } else { func = Utils.CreateLambda(func); isUseSeed = true; } var source = this; return new Enumerable(function () { var enumerator; var value; var isFirst = true; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { if (isFirst) { isFirst = false; if (!isUseSeed) { if (enumerator.MoveNext()) { return this.Yield(value = enumerator.Current()); } } else { return this.Yield(value = seed); } } return (enumerator.MoveNext()) ? this.Yield(value = func(value, enumerator.Current())) : false; }, function () { Utils.Dispose(enumerator); }); }); }, // Overload:function(selector<element>) // Overload:function(selector<element,index>) Select: function (selector) { var source = this; selector = Utils.CreateLambda(selector); return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { return (enumerator.MoveNext()) ? this.Yield(selector(enumerator.Current(), index++)) : false; }, function () { Utils.Dispose(enumerator); }) }); }, // Overload:function(collectionSelector<element>) // Overload:function(collectionSelector<element,index>) // Overload:function(collectionSelector<element>,resultSelector) // Overload:function(collectionSelector<element,index>,resultSelector) SelectMany: function (collectionSelector, resultSelector) { var source = this; collectionSelector = Utils.CreateLambda(collectionSelector); if (resultSelector == null) resultSelector = function (a, b) { return b; } resultSelector = Utils.CreateLambda(resultSelector); return new Enumerable(function () { var enumerator; var middleEnumerator = undefined; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { if (middleEnumerator === undefined) { if (!enumerator.MoveNext()) return false; } do { if (middleEnumerator == null) { var middleSeq = collectionSelector(enumerator.Current(), index++); middleEnumerator = Enumerable.From(middleSeq).GetEnumerator(); } if (middleEnumerator.MoveNext()) { return this.Yield(resultSelector(enumerator.Current(), middleEnumerator.Current())); } Utils.Dispose(middleEnumerator); middleEnumerator = null; } while (enumerator.MoveNext()) return false; }, function () { try { Utils.Dispose(enumerator); } finally { Utils.Dispose(middleEnumerator); } }) }); }, // Overload:function(predicate<element>) // Overload:function(predicate<element,index>) Where: function (predicate) { predicate = Utils.CreateLambda(predicate); var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { while (enumerator.MoveNext()) { if (predicate(enumerator.Current(), index++)) { return this.Yield(enumerator.Current()); } } return false; }, function () { Utils.Dispose(enumerator); }) }); }, OfType: function (type) { var typeName; switch (type) { case Number: typeName = Types.Number; break; case String: typeName = Types.String; break; case Boolean: typeName = Types.Boolean; break; case Function: typeName = Types.Function; break; default: typeName = null; break; } return (typeName === null) ? this.Where(function (x) { return x instanceof type }) : this.Where(function (x) { return typeof x === typeName }); }, // Overload:function(second,selector<outer,inner>) // Overload:function(second,selector<outer,inner,index>) Zip: function (second, selector) { selector = Utils.CreateLambda(selector); var source = this; return new Enumerable(function () { var firstEnumerator; var secondEnumerator; var index = 0; return new IEnumerator( function () { firstEnumerator = source.GetEnumerator(); secondEnumerator = Enumerable.From(second).GetEnumerator(); }, function () { if (firstEnumerator.MoveNext() && secondEnumerator.MoveNext()) { return this.Yield(selector(firstEnumerator.Current(), secondEnumerator.Current(), index++)); } return false; }, function () { try { Utils.Dispose(firstEnumerator); } finally { Utils.Dispose(secondEnumerator); } }) }); }, /* Join Methods */ // Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector) // Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) Join: function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) { outerKeySelector = Utils.CreateLambda(outerKeySelector); innerKeySelector = Utils.CreateLambda(innerKeySelector); resultSelector = Utils.CreateLambda(resultSelector); compareSelector = Utils.CreateLambda(compareSelector); var source = this; return new Enumerable(function () { var outerEnumerator; var lookup; var innerElements = null; var innerCount = 0; return new IEnumerator( function () { outerEnumerator = source.GetEnumerator(); lookup = Enumerable.From(inner).ToLookup(innerKeySelector, Functions.Identity, compareSelector); }, function () { while (true) { if (innerElements != null) { var innerElement = innerElements[innerCount++]; if (innerElement !== undefined) { return this.Yield(resultSelector(outerEnumerator.Current(), innerElement)); } innerElement = null; innerCount = 0; } if (outerEnumerator.MoveNext()) { var key = outerKeySelector(outerEnumerator.Current()); innerElements = lookup.Get(key).ToArray(); } else { return false; } } }, function () { Utils.Dispose(outerEnumerator); }) }); }, // Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector) // Overload:function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) GroupJoin: function (inner, outerKeySelector, innerKeySelector, resultSelector, compareSelector) { outerKeySelector = Utils.CreateLambda(outerKeySelector); innerKeySelector = Utils.CreateLambda(innerKeySelector); resultSelector = Utils.CreateLambda(resultSelector); compareSelector = Utils.CreateLambda(compareSelector); var source = this; return new Enumerable(function () { var enumerator = source.GetEnumerator(); var lookup = null; return new IEnumerator( function () { enumerator = source.GetEnumerator(); lookup = Enumerable.From(inner).ToLookup(innerKeySelector, Functions.Identity, compareSelector); }, function () { if (enumerator.MoveNext()) { var innerElement = lookup.Get(outerKeySelector(enumerator.Current())); return this.Yield(resultSelector(enumerator.Current(), innerElement)); } return false; }, function () { Utils.Dispose(enumerator); }) }); }, /* Set Methods */ All: function (predicate) { predicate = Utils.CreateLambda(predicate); var result = true; this.ForEach(function (x) { if (!predicate(x)) { result = false; return false; // break } }); return result; }, // Overload:function() // Overload:function(predicate) Any: function (predicate) { predicate = Utils.CreateLambda(predicate); var enumerator = this.GetEnumerator(); try { if (arguments.length == 0) return enumerator.MoveNext(); // case:function() while (enumerator.MoveNext()) // case:function(predicate) { if (predicate(enumerator.Current())) return true; } return false; } finally { Utils.Dispose(enumerator); } }, Concat: function (second) { var source = this; return new Enumerable(function () { var firstEnumerator; var secondEnumerator; return new IEnumerator( function () { firstEnumerator = source.GetEnumerator(); }, function () { if (secondEnumerator == null) { if (firstEnumerator.MoveNext()) return this.Yield(firstEnumerator.Current()); secondEnumerator = Enumerable.From(second).GetEnumerator(); } if (secondEnumerator.MoveNext()) return this.Yield(secondEnumerator.Current()); return false; }, function () { try { Utils.Dispose(firstEnumerator); } finally { Utils.Dispose(secondEnumerator); } }) }); }, Insert: function (index, second) { var source = this; return new Enumerable(function () { var firstEnumerator; var secondEnumerator; var count = 0; var isEnumerated = false; return new IEnumerator( function () { firstEnumerator = source.GetEnumerator(); secondEnumerator = Enumerable.From(second).GetEnumerator(); }, function () { if (count == index && secondEnumerator.MoveNext()) { isEnumerated = true; return this.Yield(secondEnumerator.Current()); } if (firstEnumerator.MoveNext()) { count++; return this.Yield(firstEnumerator.Current()); } if (!isEnumerated && secondEnumerator.MoveNext()) { return this.Yield(secondEnumerator.Current()); } return false; }, function () { try { Utils.Dispose(firstEnumerator); } finally { Utils.Dispose(secondEnumerator); } }) }); }, Alternate: function (value) { value = Enumerable.Return(value); return this.SelectMany(function (elem) { return Enumerable.Return(elem).Concat(value); }).TakeExceptLast(); }, // Overload:function(value) // Overload:function(value, compareSelector) Contains: function (value, compareSelector) { compareSelector = Utils.CreateLambda(compareSelector); var enumerator = this.GetEnumerator(); try { while (enumerator.MoveNext()) { if (compareSelector(enumerator.Current()) === value) return true; } return false; } finally { Utils.Dispose(enumerator) } }, DefaultIfEmpty: function (defaultValue) { var source = this; return new Enumerable(function () { var enumerator; var isFirst = true; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { if (enumerator.MoveNext()) { isFirst = false; return this.Yield(enumerator.Current()); } else if (isFirst) { isFirst = false; return this.Yield(defaultValue); } return false; }, function () { Utils.Dispose(enumerator); }) }); }, // Overload:function() // Overload:function(compareSelector) Distinct: function (compareSelector) { return this.Except(Enumerable.Empty(), compareSelector); }, // Overload:function(second) // Overload:function(second, compareSelector) Except: function (second, compareSelector) { compareSelector = Utils.CreateLambda(compareSelector); var source = this; return new Enumerable(function () { var enumerator; var keys; return new IEnumerator( function () { enumerator = source.GetEnumerator(); keys = new Dictionary(compareSelector); Enumerable.From(second).ForEach(function (key) { keys.Add(key); }); }, function () { while (enumerator.MoveNext()) { var current = enumerator.Current(); if (!keys.Contains(current)) { keys.Add(current); return this.Yield(current); } } return false; }, function () { Utils.Dispose(enumerator); }) }); }, // Overload:function(second) // Overload:function(second, compareSelector) Intersect: function (second, compareSelector) { compareSelector = Utils.CreateLambda(compareSelector); var source = this; return new Enumerable(function () { var enumerator; var keys; var outs; return new IEnumerator( function () { enumerator = source.GetEnumerator(); keys = new Dictionary(compareSelector); Enumerable.From(second).ForEach(function (key) { keys.Add(key); }); outs = new Dictionary(compareSelector); }, function () { while (enumerator.MoveNext()) { var current = enumerator.Current(); if (!outs.Contains(current) && keys.Contains(current)) { outs.Add(current); return this.Yield(current); } } return false; }, function () { Utils.Dispose(enumerator); }) }); }, // Overload:function(second) // Overload:function(second, compareSelector) SequenceEqual: function (second, compareSelector) { compareSelector = Utils.CreateLambda(compareSelector); var firstEnumerator = this.GetEnumerator(); try { var secondEnumerator = Enumerable.From(second).GetEnumerator(); try { while (firstEnumerator.MoveNext()) { if (!secondEnumerator.MoveNext() || compareSelector(firstEnumerator.Current()) !== compareSelector(secondEnumerator.Current())) { return false; } } if (secondEnumerator.MoveNext()) return false; return true; } finally { Utils.Dispose(secondEnumerator); } } finally { Utils.Dispose(firstEnumerator); } }, Union: function (second, compareSelector) { compareSelector = Utils.CreateLambda(compareSelector); var source = this; return new Enumerable(function () { var firstEnumerator; var secondEnumerator; var keys; return new IEnumerator( function () { firstEnumerator = source.GetEnumerator(); keys = new Dictionary(compareSelector); }, function () { var current; if (secondEnumerator === undefined) { while (firstEnumerator.MoveNext()) { current = firstEnumerator.Current(); if (!keys.Contains(current)) { keys.Add(current); return this.Yield(current); } } secondEnumerator = Enumerable.From(second).GetEnumerator(); } while (secondEnumerator.MoveNext()) { current = secondEnumerator.Current(); if (!keys.Contains(current)) { keys.Add(current); return this.Yield(current); } } return false; }, function () { try { Utils.Dispose(firstEnumerator); } finally { Utils.Dispose(secondEnumerator); } }) }); }, /* Ordering Methods */ OrderBy: function (keySelector) { return new OrderedEnumerable(this, keySelector, false); }, OrderByDescending: function (keySelector) { return new OrderedEnumerable(this, keySelector, true); }, Reverse: function () { var source = this; return new Enumerable(function () { var buffer; var index; return new IEnumerator( function () { buffer = source.ToArray(); index = buffer.length; }, function () { return (index > 0) ? this.Yield(buffer[--index]) : false; }, Functions.Blank) }); }, Shuffle: function () { var source = this; return new Enumerable(function () { var buffer; return new IEnumerator( function () { buffer = source.ToArray(); }, function () { if (buffer.length > 0) { var i = Math.floor(Math.random() * buffer.length); return this.Yield(buffer.splice(i, 1)[0]); } return false; }, Functions.Blank) }); }, /* Grouping Methods */ // Overload:function(keySelector) // Overload:function(keySelector,elementSelector) // Overload:function(keySelector,elementSelector,resultSelector) // Overload:function(keySelector,elementSelector,resultSelector,compareSelector) GroupBy: function (keySelector, elementSelector, resultSelector, compareSelector) { var source = this; keySelector = Utils.CreateLambda(keySelector); elementSelector = Utils.CreateLambda(elementSelector); if (resultSelector != null) resultSelector = Utils.CreateLambda(resultSelector); compareSelector = Utils.CreateLambda(compareSelector); return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.ToLookup(keySelector, elementSelector, compareSelector) .ToEnumerable() .GetEnumerator(); }, function () { while (enumerator.MoveNext()) { return (resultSelector == null) ? this.Yield(enumerator.Current()) : this.Yield(resultSelector(enumerator.Current().Key(), enumerator.Current())); } return false; }, function () { Utils.Dispose(enumerator); }) }); }, // Overload:function(keySelector) // Overload:function(keySelector,elementSelector) // Overload:function(keySelector,elementSelector,resultSelector) // Overload:function(keySelector,elementSelector,resultSelector,compareSelector) PartitionBy: function (keySelector, elementSelector, resultSelector, compareSelector) { var source = this; keySelector = Utils.CreateLambda(keySelector); elementSelector = Utils.CreateLambda(elementSelector); compareSelector = Utils.CreateLambda(compareSelector); var hasResultSelector; if (resultSelector == null) { hasResultSelector = false; resultSelector = function (key, group) { return new Grouping(key, group) } } else { hasResultSelector = true; resultSelector = Utils.CreateLambda(resultSelector); } return new Enumerable(function () { var enumerator; var key; var compareKey; var group = []; return new IEnumerator( function () { enumerator = source.GetEnumerator(); if (enumerator.MoveNext()) { key = keySelector(enumerator.Current()); compareKey = compareSelector(key); group.push(elementSelector(enumerator.Current())); } }, function () { var hasNext; while ((hasNext = enumerator.MoveNext()) == true) { if (compareKey === compareSelector(keySelector(enumerator.Current()))) { group.push(elementSelector(enumerator.Current())); } else break; } if (group.length > 0) { var result = (hasResultSelector) ? resultSelector(key, Enumerable.From(group)) : resultSelector(key, group); if (hasNext) { key = keySelector(enumerator.Current()); compareKey = compareSelector(key); group = [elementSelector(enumerator.Current())]; } else group = []; return this.Yield(result); } return false; }, function () { Utils.Dispose(enumerator); }) }); }, BufferWithCount: function (count) { var source = this; return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { var array = []; var index = 0; while (enumerator.MoveNext()) { array.push(enumerator.Current()); if (++index >= count) return this.Yield(array); } if (array.length > 0) return this.Yield(array); return false; }, function () { Utils.Dispose(enumerator); }) }); }, /* Aggregate Methods */ // Overload:function(func) // Overload:function(seed,func) // Overload:function(seed,func,resultSelector) Aggregate: function (seed, func, resultSelector) { return this.Scan(seed, func, resultSelector).Last(); }, // Overload:function() // Overload:function(selector) Average: function (selector) { selector = Utils.CreateLambda(selector); var sum = 0; var count = 0; this.ForEach(function (x) { sum += selector(x); ++count; }); return sum / count; }, // Overload:function() // Overload:function(predicate) Count: function (predicate) { predicate = (predicate == null) ? Functions.True : Utils.CreateLambda(predicate); var count = 0; this.ForEach(function (x, i) { if (predicate(x, i)) ++count; }); return count; }, // Overload:function() // Overload:function(selector) Max: function (selector) { if (selector == null) selector = Functions.Identity; return this.Select(selector).Aggregate(function (a, b) { return (a > b) ? a : b; }); }, // Overload:function() // Overload:function(selector) Min: function (selector) { if (selector == null) selector = Functions.Identity; return this.Select(selector).Aggregate(function (a, b) { return (a < b) ? a : b; }); }, MaxBy: function (keySelector) { keySelector = Utils.CreateLambda(keySelector); return this.Aggregate(function (a, b) { return (keySelector(a) > keySelector(b)) ? a : b }); }, MinBy: function (keySelector) { keySelector = Utils.CreateLambda(keySelector); return this.Aggregate(function (a, b) { return (keySelector(a) < keySelector(b)) ? a : b }); }, // Overload:function() // Overload:function(selector) Sum: function (selector) { if (selector == null) selector = Functions.Identity; return this.Select(selector).Aggregate(0, function (a, b) { return a + b; }); }, /* Paging Methods */ ElementAt: function (index) { var value; var found = false; this.ForEach(function (x, i) { if (i == index) { value = x; found = true; return false; } }); if (!found) throw new Error("index is less than 0 or greater than or equal to the number of elements in source."); return value; }, ElementAtOrDefault: function (index, defaultValue) { var value; var found = false; this.ForEach(function (x, i) { if (i == index) { value = x; found = true; return false; } }); return (!found) ? defaultValue : value; }, // Overload:function() // Overload:function(predicate) First: function (predicate) { if (predicate != null) return this.Where(predicate).First(); var value; var found = false; this.ForEach(function (x) { value = x; found = true; return false; }); if (!found) throw new Error("First:No element satisfies the condition."); return value; }, // Overload:function(defaultValue) // Overload:function(defaultValue,predicate) FirstOrDefault: function (defaultValue, predicate) { if (predicate != null) return this.Where(predicate).FirstOrDefault(defaultValue); var value; var found = false; this.ForEach(function (x) { value = x; found = true; return false; }); return (!found) ? defaultValue : value; }, // Overload:function() // Overload:function(predicate) Last: function (predicate) { if (predicate != null) return this.Where(predicate).Last(); var value; var found = false; this.ForEach(function (x) { found = true; value = x; }); if (!found) throw new Error("Last:No element satisfies the condition."); return value; }, // Overload:function(defaultValue) // Overload:function(defaultValue,predicate) LastOrDefault: function (defaultValue, predicate) { if (predicate != null) return this.Where(predicate).LastOrDefault(defaultValue); var value; var found = false; this.ForEach(function (x) { found = true; value = x; }); return (!found) ? defaultValue : value; }, // Overload:function() // Overload:function(predicate) Single: function (predicate) { if (predicate != null) return this.Where(predicate).Single(); var value; var found = false; this.ForEach(function (x) { if (!found) { found = true; value = x; } else throw new Error("Single:sequence contains more than one element."); }); if (!found) throw new Error("Single:No element satisfies the condition."); return value; }, // Overload:function(defaultValue) // Overload:function(defaultValue,predicate) SingleOrDefault: function (defaultValue, predicate) { if (predicate != null) return this.Where(predicate).SingleOrDefault(defaultValue); var value; var found = false; this.ForEach(function (x) { if (!found) { found = true; value = x; } else throw new Error("Single:sequence contains more than one element."); }); return (!found) ? defaultValue : value; }, Skip: function (count) { var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); while (index++ < count && enumerator.MoveNext()) { }; }, function () { return (enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; }, function () { Utils.Dispose(enumerator); }) }); }, // Overload:function(predicate<element>) // Overload:function(predicate<element,index>) SkipWhile: function (predicate) { predicate = Utils.CreateLambda(predicate); var source = this; return new Enumerable(function () { var enumerator; var index = 0; var isSkipEnd = false; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { while (!isSkipEnd) { if (enumerator.MoveNext()) { if (!predicate(enumerator.Current(), index++)) { isSkipEnd = true; return this.Yield(enumerator.Current()); } continue; } else return false; } return (enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; }, function () { Utils.Dispose(enumerator); }); }); }, Take: function (count) { var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { return (index++ < count && enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; }, function () { Utils.Dispose(enumerator); } ) }); }, // Overload:function(predicate<element>) // Overload:function(predicate<element,index>) TakeWhile: function (predicate) { predicate = Utils.CreateLambda(predicate); var source = this; return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { return (enumerator.MoveNext() && predicate(enumerator.Current(), index++)) ? this.Yield(enumerator.Current()) : false; }, function () { Utils.Dispose(enumerator); }); }); }, // Overload:function() // Overload:function(count) TakeExceptLast: function (count) { if (count == null) count = 1; var source = this; return new Enumerable(function () { if (count <= 0) return source.GetEnumerator(); // do nothing var enumerator; var q = []; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { while (enumerator.MoveNext()) { if (q.length == count) { q.push(enumerator.Current()); return this.Yield(q.shift()); } q.push(enumerator.Current()); } return false; }, function () { Utils.Dispose(enumerator); }); }); }, TakeFromLast: function (count) { if (count <= 0 || count == null) return Enumerable.Empty(); var source = this; return new Enumerable(function () { var sourceEnumerator; var enumerator; var q = []; return new IEnumerator( function () { sourceEnumerator = source.GetEnumerator(); }, function () { while (sourceEnumerator.MoveNext()) { if (q.length == count) q.shift() q.push(sourceEnumerator.Current()); } if (enumerator == null) { enumerator = Enumerable.From(q).GetEnumerator(); } return (enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; }, function () { Utils.Dispose(enumerator); }); }); }, IndexOf: function (item) { var found = null; this.ForEach(function (x, i) { if (x === item) { found = i; return true; } }); return (found !== null) ? found : -1; }, LastIndexOf: function (item) { var result = -1; this.ForEach(function (x, i) { if (x === item) result = i; }); return result; }, /* Convert Methods */ ToArray: function () { var array = []; this.ForEach(function (x) { array.push(x) }); return array; }, // Overload:function(keySelector) // Overload:function(keySelector, elementSelector) // Overload:function(keySelector, elementSelector, compareSelector) ToLookup: function (keySelector, elementSelector, compareSelector) { keySelector = Utils.CreateLambda(keySelector); elementSelector = Utils.CreateLambda(elementSelector); compareSelector = Utils.CreateLambda(compareSelector); var dict = new Dictionary(compareSelector); this.ForEach(function (x) { var key = keySelector(x); var element = elementSelector(x); var array = dict.Get(key); if (array !== undefined) array.push(element); else dict.Add(key, [element]); }); return new Lookup(dict); }, ToObject: function (keySelector, elementSelector) { keySelector = Utils.CreateLambda(keySelector); elementSelector = Utils.CreateLambda(elementSelector); var obj = {}; this.ForEach(function (x) { obj[keySelector(x)] = elementSelector(x); }); return obj; }, // Overload:function(keySelector, elementSelector) // Overload:function(keySelector, elementSelector, compareSelector) ToDictionary: function (keySelector, elementSelector, compareSelector) { keySelector = Utils.CreateLambda(keySelector); elementSelector = Utils.CreateLambda(elementSelector); compareSelector = Utils.CreateLambda(compareSelector); var dict = new Dictionary(compareSelector); this.ForEach(function (x) { dict.Add(keySelector(x), elementSelector(x)); }); return dict; }, // Overload:function() // Overload:function(replacer) // Overload:function(replacer, space) ToJSON: function (replacer, space) { return JSON.stringify(this.ToArray(), replacer, space); }, // Overload:function() // Overload:function(separator) // Overload:function(separator,selector) ToString: function (separator, selector) { if (separator == null) separator = ""; if (selector == null) selector = Functions.Identity; return this.Select(selector).ToArray().join(separator); }, /* Action Methods */ // Overload:function(action<element>) // Overload:function(action<element,index>) Do: function (action) { var source = this; action = Utils.CreateLambda(action); return new Enumerable(function () { var enumerator; var index = 0; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { if (enumerator.MoveNext()) { action(enumerator.Current(), index++); return this.Yield(enumerator.Current()); } return false; }, function () { Utils.Dispose(enumerator); }); }); }, // Overload:function(action<element>) // Overload:function(action<element,index>) // Overload:function(func<element,bool>) // Overload:function(func<element,index,bool>) ForEach: function (action) { action = Utils.CreateLambda(action); var index = 0; var enumerator = this.GetEnumerator(); try { while (enumerator.MoveNext()) { if (action(enumerator.Current(), index++) === false) break; } } finally { Utils.Dispose(enumerator); } }, // Overload:function() // Overload:function(separator) // Overload:function(separator,selector) Write: function (separator, selector) { if (separator == null) separator = ""; selector = Utils.CreateLambda(selector); var isFirst = true; this.ForEach(function (item) { if (isFirst) isFirst = false; else document.write(separator); document.write(selector(item)); }); }, // Overload:function() // Overload:function(selector) WriteLine: function (selector) { selector = Utils.CreateLambda(selector); this.ForEach(function (item) { document.write(selector(item)); document.write("<br />"); }); }, Force: function () { var enumerator = this.GetEnumerator(); try { while (enumerator.MoveNext()) { } } finally { Utils.Dispose(enumerator); } }, /* Functional Methods */ Let: function (func) { func = Utils.CreateLambda(func); var source = this; return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = Enumerable.From(func(source)).GetEnumerator(); }, function () { return (enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; }, function () { Utils.Dispose(enumerator); }) }); }, Share: function () { var source = this; var sharedEnumerator; return new Enumerable(function () { return new IEnumerator( function () { if (sharedEnumerator == null) { sharedEnumerator = source.GetEnumerator(); } }, function () { return (sharedEnumerator.MoveNext()) ? this.Yield(sharedEnumerator.Current()) : false; }, Functions.Blank ) }); }, MemoizeAll: function () { var source = this; var cache; var enumerator; return new Enumerable(function () { var index = -1; return new IEnumerator( function () { if (enumerator == null) { enumerator = source.GetEnumerator(); cache = []; } }, function () { index++; if (cache.length <= index) { return (enumerator.MoveNext()) ? this.Yield(cache[index] = enumerator.Current()) : false; } return this.Yield(cache[index]); }, Functions.Blank ) }); }, /* Error Handling Methods */ Catch: function (handler) { handler = Utils.CreateLambda(handler); var source = this; return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { try { return (enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; } catch (e) { handler(e); return false; } }, function () { Utils.Dispose(enumerator); }); }); }, Finally: function (finallyAction) { finallyAction = Utils.CreateLambda(finallyAction); var source = this; return new Enumerable(function () { var enumerator; return new IEnumerator( function () { enumerator = source.GetEnumerator(); }, function () { return (enumerator.MoveNext()) ? this.Yield(enumerator.Current()) : false; }, function () { try { Utils.Dispose(enumerator); } finally { finallyAction(); } }); }); }, /* For Debug Methods */ // Overload:function() // Overload:function(message) // Overload:function(message,selector) Trace: function (message, selector) { if (message == null) message = "Trace"; selector = Utils.CreateLambda(selector); return this.Do(function (item) { console.log(message, ":", selector(item)); }); } } // private // static functions var Functions = { Identity: function (x) { return x; }, True: function () { return true; }, Blank: function () { } } // static const var Types = { Boolean: typeof true, Number: typeof 0, String: typeof "", Object: typeof {}, Undefined: typeof undefined, Function: typeof function () { } } // static utility methods var Utils = { // Create anonymous function from lambda expression string CreateLambda: function (expression) { if (expression == null) return Functions.Identity; if (typeof expression == Types.String) { if (expression == "") { return Functions.Identity; } else if (expression.indexOf("=>") == -1) { return new Function("$,$$,$$$,$$$$", "return " + expression); } else { var expr = expression.match(/^[(\s]*([^()]*?)[)\s]*=>(.*)/); return new Function(expr[1], "return " + expr[2]); } } return expression; }, IsIEnumerable: function (obj) { if (typeof Enumerator != Types.Undefined) { try { new Enumerator(obj); return true; } catch (e) { } } return false; }, Compare: function (a, b) { return (a === b) ? 0 : (a > b) ? 1 : -1; }, Dispose: function (obj) { if (obj != null) obj.Dispose(); } } // IEnumerator State var State = { Before: 0, Running: 1, After: 2 } // name "Enumerator" is conflict JScript's "Enumerator" var IEnumerator = function (initialize, tryGetNext, dispose) { var yielder = new Yielder(); var state = State.Before; this.Current = yielder.Current; this.MoveNext = function () { try { switch (state) { case State.Before: state = State.Running; initialize(); // fall through case State.Running: if (tryGetNext.apply(yielder)) { return true; } else { this.Dispose(); return false; } case State.After: return false; } } catch (e) { this.Dispose(); throw e; } } this.Dispose = function () { if (state != State.Running) return; try { dispose(); } finally { state = State.After; } } } // for tryGetNext var Yielder = function () { var current = null; this.Current = function () { return current; } this.Yield = function (value) { current = value; return true; } } // for OrderBy/ThenBy var OrderedEnumerable = function (source, keySelector, descending, parent) { this.source = source; this.keySelector = Utils.CreateLambda(keySelector); this.descending = descending; this.parent = parent; } OrderedEnumerable.prototype = new Enumerable(); OrderedEnumerable.prototype.CreateOrderedEnumerable = function (keySelector, descending) { return new OrderedEnumerable(this.source, keySelector, descending, this); } OrderedEnumerable.prototype.ThenBy = function (keySelector) { return this.CreateOrderedEnumerable(keySelector, false); } OrderedEnumerable.prototype.ThenByDescending = function (keySelector) { return this.CreateOrderedEnumerable(keySelector, true); } OrderedEnumerable.prototype.GetEnumerator = function () { var self = this; var buffer; var indexes; var index = 0; return new IEnumerator( function () { buffer = []; indexes = []; self.source.ForEach(function (item, index) { buffer.push(item); indexes.push(index); }); var sortContext = SortContext.Create(self, null); sortContext.GenerateKeys(buffer); indexes.sort(function (a, b) { return sortContext.Compare(a, b); }); }, function () { return (index < indexes.length) ? this.Yield(buffer[indexes[index++]]) : false; }, Functions.Blank ) } var SortContext = function (keySelector, descending, child) { this.keySelector = keySelector; this.descending = descending; this.child = child; this.keys = null; } SortContext.Create = function (orderedEnumerable, currentContext) { var context = new SortContext(orderedEnumerable.keySelector, orderedEnumerable.descending, currentContext); if (orderedEnumerable.parent != null) return SortContext.Create(orderedEnumerable.parent, context); return context; } SortContext.prototype.GenerateKeys = function (source) { var len = source.length; var keySelector = this.keySelector; var keys = new Array(len); for (var i = 0; i < len; i++) keys[i] = keySelector(source[i]); this.keys = keys; if (this.child != null) this.child.GenerateKeys(source); } SortContext.prototype.Compare = function (index1, index2) { var comparison = Utils.Compare(this.keys[index1], this.keys[index2]); if (comparison == 0) { if (this.child != null) return this.child.Compare(index1, index2) comparison = Utils.Compare(index1, index2); } return (this.descending) ? -comparison : comparison; } // optimize array or arraylike object var ArrayEnumerable = function (source) { this.source = source; } ArrayEnumerable.prototype = new Enumerable(); ArrayEnumerable.prototype.Any = function (predicate) { return (predicate == null) ? (this.source.length > 0) : Enumerable.prototype.Any.apply(this, arguments); } ArrayEnumerable.prototype.Count = function (predicate) { return (predicate == null) ? this.source.length : Enumerable.prototype.Count.apply(this, arguments); } ArrayEnumerable.prototype.ElementAt = function (index) { return (0 <= index && index < this.source.length) ? this.source[index] : Enumerable.prototype.ElementAt.apply(this, arguments); } ArrayEnumerable.prototype.ElementAtOrDefault = function (index, defaultValue) { return (0 <= index && index < this.source.length) ? this.source[index] : defaultValue; } ArrayEnumerable.prototype.First = function (predicate) { return (predicate == null && this.source.length > 0) ? this.source[0] : Enumerable.prototype.First.apply(this, arguments); } ArrayEnumerable.prototype.FirstOrDefault = function (defaultValue, predicate) { if (predicate != null) { return Enumerable.prototype.FirstOrDefault.apply(this, arguments); } return this.source.length > 0 ? this.source[0] : defaultValue; } ArrayEnumerable.prototype.Last = function (predicate) { return (predicate == null && this.source.length > 0) ? this.source[this.source.length - 1] : Enumerable.prototype.Last.apply(this, arguments); } ArrayEnumerable.prototype.LastOrDefault = function (defaultValue, predicate) { if (predicate != null) { return Enumerable.prototype.LastOrDefault.apply(this, arguments); } return this.source.length > 0 ? this.source[this.source.length - 1] : defaultValue; } ArrayEnumerable.prototype.Skip = function (count) { var source = this.source; return new Enumerable(function () { var index; return new IEnumerator( function () { index = (count < 0) ? 0 : count }, function () { return (index < source.length) ? this.Yield(source[index++]) : false; }, Functions.Blank); }); }; ArrayEnumerable.prototype.TakeExceptLast = function (count) { if (count == null) count = 1; return this.Take(this.source.length - count); } ArrayEnumerable.prototype.TakeFromLast = function (count) { return this.Skip(this.source.length - count); } ArrayEnumerable.prototype.Reverse = function () { var source = this.source; return new Enumerable(function () { var index; return new IEnumerator( function () { index = source.length; }, function () { return (index > 0) ? this.Yield(source[--index]) : false; }, Functions.Blank) }); } ArrayEnumerable.prototype.SequenceEqual = function (second, compareSelector) { if ((second instanceof ArrayEnumerable || second instanceof Array) && compareSelector == null && Enumerable.From(second).Count() != this.Count()) { return false; } return Enumerable.prototype.SequenceEqual.apply(this, arguments); } ArrayEnumerable.prototype.ToString = function (separator, selector) { if (selector != null || !(this.source instanceof Array)) { return Enumerable.prototype.ToString.apply(this, arguments); } if (separator == null) separator = ""; return this.source.join(separator); } ArrayEnumerable.prototype.GetEnumerator = function () { var source = this.source; var index = 0; return new IEnumerator( Functions.Blank, function () { return (index < source.length) ? this.Yield(source[index++]) : false; }, Functions.Blank); } // Collections var Dictionary = (function () { // static utility methods var HasOwnProperty = function (target, key) { return Object.prototype.hasOwnProperty.call(target, key); } var ComputeHashCode = function (obj) { if (obj === null) return "null"; if (obj === undefined) return "undefined"; return (typeof obj.toString === Types.Function) ? obj.toString() : Object.prototype.toString.call(obj); } // LinkedList for Dictionary var HashEntry = function (key, value) { this.Key = key; this.Value = value; this.Prev = null; this.Next = null; } var EntryList = function () { this.First = null; this.Last = null; } EntryList.prototype = { AddLast: function (entry) { if (this.Last != null) { this.Last.Next = entry; entry.Prev = this.Last; this.Last = entry; } else this.First = this.Last = entry; }, Replace: function (entry, newEntry) { if (entry.Prev != null) { entry.Prev.Next = newEntry; newEntry.Prev = entry.Prev; } else this.First = newEntry; if (entry.Next != null) { entry.Next.Prev = newEntry; newEntry.Next = entry.Next; } else this.Last = newEntry; }, Remove: function (entry) { if (entry.Prev != null) entry.Prev.Next = entry.Next; else this.First = entry.Next; if (entry.Next != null) entry.Next.Prev = entry.Prev; else this.Last = entry.Prev; } } // Overload:function() // Overload:function(compareSelector) var Dictionary = function (compareSelector) { this.count = 0; this.entryList = new EntryList(); this.buckets = {}; // as Dictionary<string,List<object>> this.compareSelector = (compareSelector == null) ? Functions.Identity : compareSelector; } Dictionary.prototype = { Add: function (key, value) { var compareKey = this.compareSelector(key); var hash = ComputeHashCode(compareKey); var entry = new HashEntry(key, value); if (HasOwnProperty(this.buckets, hash)) { var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { if (this.compareSelector(array[i].Key) === compareKey) { this.entryList.Replace(array[i], entry); array[i] = entry; return; } } array.push(entry); } else { this.buckets[hash] = [entry]; } this.count++; this.entryList.AddLast(entry); }, Get: function (key) { var compareKey = this.compareSelector(key); var hash = ComputeHashCode(compareKey); if (!HasOwnProperty(this.buckets, hash)) return undefined; var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { var entry = array[i]; if (this.compareSelector(entry.Key) === compareKey) return entry.Value; } return undefined; }, Set: function (key, value) { var compareKey = this.compareSelector(key); var hash = ComputeHashCode(compareKey); if (HasOwnProperty(this.buckets, hash)) { var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { if (this.compareSelector(array[i].Key) === compareKey) { var newEntry = new HashEntry(key, value); this.entryList.Replace(array[i], newEntry); array[i] = newEntry; return true; } } } return false; }, Contains: function (key) { var compareKey = this.compareSelector(key); var hash = ComputeHashCode(compareKey); if (!HasOwnProperty(this.buckets, hash)) return false; var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { if (this.compareSelector(array[i].Key) === compareKey) return true; } return false; }, Clear: function () { this.count = 0; this.buckets = {}; this.entryList = new EntryList(); }, Remove: function (key) { var compareKey = this.compareSelector(key); var hash = ComputeHashCode(compareKey); if (!HasOwnProperty(this.buckets, hash)) return; var array = this.buckets[hash]; for (var i = 0; i < array.length; i++) { if (this.compareSelector(array[i].Key) === compareKey) { this.entryList.Remove(array[i]); array.splice(i, 1); if (array.length == 0) delete this.buckets[hash]; this.count--; return; } } }, Count: function () { return this.count; }, ToEnumerable: function () { var self = this; return new Enumerable(function () { var currentEntry; return new IEnumerator( function () { currentEntry = self.entryList.First }, function () { if (currentEntry != null) { var result = { Key: currentEntry.Key, Value: currentEntry.Value }; currentEntry = currentEntry.Next; return this.Yield(result); } return false; }, Functions.Blank); }); } } return Dictionary; })(); // dictionary = Dictionary<TKey, TValue[]> var Lookup = function (dictionary) { this.Count = function () { return dictionary.Count(); } this.Get = function (key) { return Enumerable.From(dictionary.Get(key)); } this.Contains = function (key) { return dictionary.Contains(key); } this.ToEnumerable = function () { return dictionary.ToEnumerable().Select(function (kvp) { return new Grouping(kvp.Key, kvp.Value); }); } } var Grouping = function (key, elements) { this.Key = function () { return key; } ArrayEnumerable.call(this, elements); } Grouping.prototype = new ArrayEnumerable(); // out to global return Enumerable; })()}); // binding for jQuery // toEnumerable / TojQuery (function ($, Enumerable) { $.fn.toEnumerable = function () { /// <summary>each contains elements. to Enumerable&lt;jQuery&gt;.</summary> /// <returns type="Enumerable"></returns> return Enumerable.From(this).Select(function (e) { return $(e) }); } Enumerable.prototype.TojQuery = function () { /// <summary>Enumerable to jQuery.</summary> /// <returns type="jQuery"></returns> return $(this.ToArray()); } })(jQuery, this.Enumerable || this.jQuery.Enumerable) (function () { // **************************** // extensions // **************************** String.prototype.format = function () { var formatted = this; for (var arg in arguments) { formatted = formatted.replace("{" + arg + "}", arguments[arg]); } return formatted; }; // **************************** // helper class // **************************** // **************************** // globals // **************************** window.Helper = window.Helper || {}; // **************************** // public methods // **************************** Helper = Helper.prototype = { ErrorResponse: function (error) { if (error.responseJSON) { if (error.responseJSON.message) { // Type: Action Exception alert(error.responseJSON.message) } else if (error.responseJSON[0]) { // Type: Invalid Model error var strError = ""; for (var iField in error.responseJSON) for (var iErro in error.responseJSON[iField].errors) strError += "- " + error.responseJSON[iField].errors[iErro] + "\r\n"; alert(strError); } } else { // Type: Inexpected Exception alert(error.statusText) } }, OpenUrl: function (url, target) { target = target ? target : '_self'; var win = window.open(url, target); win.focus(); }, DisableWindow: function () { $("body").append('<div style="width: 100%; height: 100%; position: absolute; left: 0; top: 0;" id="disabled-window"> </div>'); }, EnabledWindow: function () { $("#disabled-window").remove(); }, } }());
function printInSampleTemplate(code, result) { return '<table style="width:100%;"><tr><th>Code</th><th>Result</th></tr><tr><td style="width: 50%;vertical-align:top;"><pre class="typescript">' + code + '</pre></td><td style="width: 50%;vertical-align:top;"><pre class="json">' + result + '</pre></td></tr></table>'; } function execAndPrint(code, func, id) { // var code = document.getElementById("forMemberMapFrom").innerHTML = func.toString(); // JS code var result; try { result = JSON.stringify(func(), null, '\t'); } catch (error) { console.error(error); result = 'Function execution failed with the following error message: ' + error.message; } document.getElementById(id).innerHTML = printInSampleTemplate(code, result); }
"use strict"; "use strict"; var assert = require("assert"); var adapter = require("../../js/debug/bluebird.js"); var Promise = adapter; var fulfilled = adapter.fulfilled; var rejected = adapter.rejected; var pending = adapter.pending; describe("Promise filter", function() { function ThrownError() {} var arr = [1,2,3]; function assertArr(arr) { assert(arr.length === 2); assert(arr[0] === 1); assert(arr[1] === 3); } function assertErr(e) { assert(e instanceof ThrownError); } function assertFail() { assert.fail(); } function cd(done) { return function() { done(); }; } describe("should accept eventual booleans", function() { specify("immediately fulfilled", function(done) { Promise.filter(arr, function(v) { return new Promise(function(r){ r(v !== 2); }); }).then(assertArr).then(cd(done)); }); specify("already fulfilled", function(done) { Promise.filter(arr, function(v) { return Promise.resolve(v !== 2); }).then(assertArr).then(cd(done)); }); specify("eventually fulfilled", function(done) { Promise.filter(arr, function(v) { return new Promise(function(r){ setTimeout(function(){ r(v !== 2); }, 13); }); }).then(assertArr).then(cd(done)); }); specify("immediately rejected", function(done) { Promise.filter(arr, function(v) { return new Promise(function(v, r){ r(new ThrownError()); }); }).then(assertFail, assertErr).then(cd(done)); }); specify("already rejected", function(done) { Promise.filter(arr, function(v) { return Promise.reject(new ThrownError()); }).then(assertFail, assertErr).then(cd(done)); }); specify("eventually rejected", function(done) { Promise.filter(arr, function(v) { return new Promise(function(v, r){ setTimeout(function(){ r(new ThrownError()); }, 13); }); }).then(assertFail, assertErr).then(cd(done)); }); specify("immediately fulfilled thenable", function(done) { Promise.filter(arr, function(v) { return { then: function(f, r) { f(v !== 2); } }; }).then(assertArr).then(cd(done)); }); specify("eventually fulfilled thenable", function(done) { Promise.filter(arr, function(v) { return { then: function(f, r) { setTimeout(function(){ f(v !== 2); }, 13); } }; }).then(assertArr).then(cd(done)); }); specify("immediately rejected thenable", function(done) { Promise.filter(arr, function(v) { return { then: function(f, r) { r(new ThrownError()); } }; }).then(assertFail, assertErr).then(cd(done)); }); specify("eventually rejected thenable", function(done) { Promise.filter(arr, function(v) { return { then: function(f, r) { setTimeout(function(){ r(new ThrownError()); }, 13); } }; }).then(assertFail, assertErr).then(cd(done)); }); }); });
define( ({ insertTableTitle: "Wstawianie tabeli", modifyTableTitle: "Modyfikowanie tabeli", rows: "Wiersze:", columns: "Kolumny:", align: "Wyrównanie:", cellPadding: "Dopełnianie komórek:", cellSpacing: "Odstępy między komórkami:", tableWidth: "Szerokość tabeli:", backgroundColor: "Kolor tła:", borderColor: "Kolor krawędzi:", borderThickness: "Grubość krawędzi:", percent: "procent", pixels: "piksle", "default": "domyślna", left: "left", center: "środek", right: "right", buttonSet: "Ustaw", // translated elsewhere? buttonInsert: "Wstaw", buttonCancel: "Anuluj", selectTableLabel: "Wybierz tabelę", insertTableRowBeforeLabel: "Dodaj wiersz przed", insertTableRowAfterLabel: "Dodaj wiersz po", insertTableColumnBeforeLabel: "Dodaj kolumnę przed", insertTableColumnAfterLabel: "Dodaj kolumnę po", deleteTableRowLabel: "Usuń wiersz", deleteTableColumnLabel: "Usuń kolumnę" }) );
/*! * Copyright (c) 2017 ETS Corporation * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE * OR OTHER DEALINGS IN THE SOFTWARE. */ // Closure (function(){ /** * Decimal adjustment of a number. * * @param {String} type The type of adjustment. * @param {Number} value The number. * @param {Integer} exp The exponent (the 10 logarithm of the adjustment base). * @returns {Number} The adjusted value. */ function decimalAdjust(type, value, exp) { // If the exp is undefined or zero... if (typeof exp === 'undefined' || +exp === 0) { return Math[type](value); } value = +value; exp = +exp; // If the value is not a number or the exp is not an integer... if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { return NaN; } // Shift value = value.toString().split('e'); value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); // Shift back value = value.toString().split('e'); return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); } // Decimal round if (!Math.round10) { Math.round10 = function(value, exp) { return decimalAdjust('round', value, exp); }; } // Decimal floor if (!Math.floor10) { Math.floor10 = function(value, exp) { return decimalAdjust('floor', value, exp); }; } // Decimal ceil if (!Math.ceil10) { Math.ceil10 = function(value, exp) { return decimalAdjust('ceil', value, exp); }; } })(); /* jquery.signalR.core.js */ /*global window:false */ /*! * ASP.NET SignalR JavaScript Library v2.2.1 * http://signalr.net/ * * Copyright (c) .NET Foundation. All rights reserved. * Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. * */ /// <reference path="Scripts/jquery-1.6.4.js" /> /// <reference path="jquery.signalR.version.js" /> (function ($, window, undefined) { var resources = { nojQuery: "jQuery was not found. Please ensure jQuery is referenced before the SignalR client JavaScript file.", noTransportOnInit: "No transport could be initialized successfully. Try specifying a different transport or none at all for auto initialization.", errorOnNegotiate: "Error during negotiation request.", stoppedWhileLoading: "The connection was stopped during page load.", stoppedWhileNegotiating: "The connection was stopped during the negotiate request.", errorParsingNegotiateResponse: "Error parsing negotiate response.", errorDuringStartRequest: "Error during start request. Stopping the connection.", stoppedDuringStartRequest: "The connection was stopped during the start request.", errorParsingStartResponse: "Error parsing start response: '{0}'. Stopping the connection.", invalidStartResponse: "Invalid start response: '{0}'. Stopping the connection.", protocolIncompatible: "You are using a version of the client that isn't compatible with the server. Client version {0}, server version {1}.", sendFailed: "Send failed.", parseFailed: "Failed at parsing response: {0}", longPollFailed: "Long polling request failed.", eventSourceFailedToConnect: "EventSource failed to connect.", eventSourceError: "Error raised by EventSource", webSocketClosed: "WebSocket closed.", pingServerFailedInvalidResponse: "Invalid ping response when pinging server: '{0}'.", pingServerFailed: "Failed to ping server.", pingServerFailedStatusCode: "Failed to ping server. Server responded with status code {0}, stopping the connection.", pingServerFailedParse: "Failed to parse ping server response, stopping the connection.", noConnectionTransport: "Connection is in an invalid state, there is no transport active.", webSocketsInvalidState: "The Web Socket transport is in an invalid state, transitioning into reconnecting.", reconnectTimeout: "Couldn't reconnect within the configured timeout of {0} ms, disconnecting.", reconnectWindowTimeout: "The client has been inactive since {0} and it has exceeded the inactivity timeout of {1} ms. Stopping the connection." }; if (typeof ($) !== "function") { // no jQuery! throw new Error(resources.nojQuery); } var signalR, _connection, _pageLoaded = (window.document.readyState === "complete"), _pageWindow = $(window), _negotiateAbortText = "__Negotiate Aborted__", events = { onStart: "onStart", onStarting: "onStarting", onReceived: "onReceived", onError: "onError", onConnectionSlow: "onConnectionSlow", onReconnecting: "onReconnecting", onReconnect: "onReconnect", onStateChanged: "onStateChanged", onDisconnect: "onDisconnect" }, ajaxDefaults = { processData: true, timeout: null, async: true, global: false, cache: false }, log = function (msg, logging) { if (logging === false) { return; } var m; if (typeof (window.console) === "undefined") { return; } m = "[" + new Date().toTimeString() + "] SignalR: " + msg; if (window.console.debug) { window.console.debug(m); } else if (window.console.log) { window.console.log(m); } }, changeState = function (connection, expectedState, newState) { if (expectedState === connection.state) { connection.state = newState; $(connection).triggerHandler(events.onStateChanged, [{ oldState: expectedState, newState: newState }]); return true; } return false; }, isDisconnecting = function (connection) { return connection.state === signalR.connectionState.disconnected; }, supportsKeepAlive = function (connection) { return connection._.keepAliveData.activated && connection.transport.supportsKeepAlive(connection); }, configureStopReconnectingTimeout = function (connection) { var stopReconnectingTimeout, onReconnectTimeout; // Check if this connection has already been configured to stop reconnecting after a specified timeout. // Without this check if a connection is stopped then started events will be bound multiple times. if (!connection._.configuredStopReconnectingTimeout) { onReconnectTimeout = function (connection) { var message = signalR._.format(signalR.resources.reconnectTimeout, connection.disconnectTimeout); connection.log(message); $(connection).triggerHandler(events.onError, [signalR._.error(message, /* source */ "TimeoutException")]); connection.stop(/* async */ false, /* notifyServer */ false); }; connection.reconnecting(function () { var connection = this; // Guard against state changing in a previous user defined even handler if (connection.state === signalR.connectionState.reconnecting) { stopReconnectingTimeout = window.setTimeout(function () { onReconnectTimeout(connection); }, connection.disconnectTimeout); } }); connection.stateChanged(function (data) { if (data.oldState === signalR.connectionState.reconnecting) { // Clear the pending reconnect timeout check window.clearTimeout(stopReconnectingTimeout); } }); connection._.configuredStopReconnectingTimeout = true; } }; signalR = function (url, qs, logging) { /// <summary>Creates a new SignalR connection for the given url</summary> /// <param name="url" type="String">The URL of the long polling endpoint</param> /// <param name="qs" type="Object"> /// [Optional] Custom querystring parameters to add to the connection URL. /// If an object, every non-function member will be added to the querystring. /// If a string, it's added to the QS as specified. /// </param> /// <param name="logging" type="Boolean"> /// [Optional] A flag indicating whether connection logging is enabled to the browser /// console/log. Defaults to false. /// </param> return new signalR.fn.init(url, qs, logging); }; signalR._ = { defaultContentType: "application/x-www-form-urlencoded; charset=UTF-8", ieVersion: (function () { var version, matches; if (window.navigator.appName === 'Microsoft Internet Explorer') { // Check if the user agent has the pattern "MSIE (one or more numbers).(one or more numbers)"; matches = /MSIE ([0-9]+\.[0-9]+)/.exec(window.navigator.userAgent); if (matches) { version = window.parseFloat(matches[1]); } } // undefined value means not IE return version; })(), error: function (message, source, context) { var e = new Error(message); e.source = source; if (typeof context !== "undefined") { e.context = context; } return e; }, transportError: function (message, transport, source, context) { var e = this.error(message, source, context); e.transport = transport ? transport.name : undefined; return e; }, format: function () { /// <summary>Usage: format("Hi {0}, you are {1}!", "Foo", 100) </summary> var s = arguments[0]; for (var i = 0; i < arguments.length - 1; i++) { s = s.replace("{" + i + "}", arguments[i + 1]); } return s; }, firefoxMajorVersion: function (userAgent) { // Firefox user agents: http://useragentstring.com/pages/Firefox/ var matches = userAgent.match(/Firefox\/(\d+)/); if (!matches || !matches.length || matches.length < 2) { return 0; } return parseInt(matches[1], 10 /* radix */); }, configurePingInterval: function (connection) { var config = connection._.config, onFail = function (error) { $(connection).triggerHandler(events.onError, [error]); }; if (config && !connection._.pingIntervalId && config.pingInterval) { connection._.pingIntervalId = window.setInterval(function () { signalR.transports._logic.pingServer(connection).fail(onFail); }, config.pingInterval); } } }; signalR.events = events; signalR.resources = resources; signalR.ajaxDefaults = ajaxDefaults; signalR.changeState = changeState; signalR.isDisconnecting = isDisconnecting; signalR.connectionState = { connecting: 0, connected: 1, reconnecting: 2, disconnected: 4 }; signalR.hub = { start: function () { // This will get replaced with the real hub connection start method when hubs is referenced correctly throw new Error("SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. <script src='/signalr/js'></script>."); } }; // .on() was added in version 1.7.0, .load() was removed in version 3.0.0 so we fallback to .load() if .on() does // not exist to not break existing applications if (typeof _pageWindow.on == "function") { _pageWindow.on("load", function () { _pageLoaded = true; }); } else { _pageWindow.load(function () { _pageLoaded = true; }); } function validateTransport(requestedTransport, connection) { /// <summary>Validates the requested transport by cross checking it with the pre-defined signalR.transports</summary> /// <param name="requestedTransport" type="Object">The designated transports that the user has specified.</param> /// <param name="connection" type="signalR">The connection that will be using the requested transports. Used for logging purposes.</param> /// <returns type="Object" /> if ($.isArray(requestedTransport)) { // Go through transport array and remove an "invalid" tranports for (var i = requestedTransport.length - 1; i >= 0; i--) { var transport = requestedTransport[i]; if ($.type(transport) !== "string" || !signalR.transports[transport]) { connection.log("Invalid transport: " + transport + ", removing it from the transports list."); requestedTransport.splice(i, 1); } } // Verify we still have transports left, if we dont then we have invalid transports if (requestedTransport.length === 0) { connection.log("No transports remain within the specified transport array."); requestedTransport = null; } } else if (!signalR.transports[requestedTransport] && requestedTransport !== "auto") { connection.log("Invalid transport: " + requestedTransport.toString() + "."); requestedTransport = null; } else if (requestedTransport === "auto" && signalR._.ieVersion <= 8) { // If we're doing an auto transport and we're IE8 then force longPolling, #1764 return ["longPolling"]; } return requestedTransport; } function getDefaultPort(protocol) { if (protocol === "http:") { return 80; } else if (protocol === "https:") { return 443; } } function addDefaultPort(protocol, url) { // Remove ports from url. We have to check if there's a / or end of line // following the port in order to avoid removing ports such as 8080. if (url.match(/:\d+$/)) { return url; } else { return url + ":" + getDefaultPort(protocol); } } function ConnectingMessageBuffer(connection, drainCallback) { var that = this, buffer = []; that.tryBuffer = function (message) { if (connection.state === $.signalR.connectionState.connecting) { buffer.push(message); return true; } return false; }; that.drain = function () { // Ensure that the connection is connected when we drain (do not want to drain while a connection is not active) if (connection.state === $.signalR.connectionState.connected) { while (buffer.length > 0) { drainCallback(buffer.shift()); } } }; that.clear = function () { buffer = []; }; } signalR.fn = signalR.prototype = { init: function (url, qs, logging) { var $connection = $(this); this.url = url; this.qs = qs; this.lastError = null; this._ = { keepAliveData: {}, connectingMessageBuffer: new ConnectingMessageBuffer(this, function (message) { $connection.triggerHandler(events.onReceived, [message]); }), lastMessageAt: new Date().getTime(), lastActiveAt: new Date().getTime(), beatInterval: 5000, // Default value, will only be overridden if keep alive is enabled, beatHandle: null, totalTransportConnectTimeout: 0 // This will be the sum of the TransportConnectTimeout sent in response to negotiate and connection.transportConnectTimeout }; if (typeof (logging) === "boolean") { this.logging = logging; } }, _parseResponse: function (response) { var that = this; if (!response) { return response; } else if (typeof response === "string") { return that.json.parse(response); } else { return response; } }, _originalJson: window.JSON, json: window.JSON, isCrossDomain: function (url, against) { /// <summary>Checks if url is cross domain</summary> /// <param name="url" type="String">The base URL</param> /// <param name="against" type="Object"> /// An optional argument to compare the URL against, if not specified it will be set to window.location. /// If specified it must contain a protocol and a host property. /// </param> var link; url = $.trim(url); against = against || window.location; if (url.indexOf("http") !== 0) { return false; } // Create an anchor tag. link = window.document.createElement("a"); link.href = url; // When checking for cross domain we have to special case port 80 because the window.location will remove the return link.protocol + addDefaultPort(link.protocol, link.host) !== against.protocol + addDefaultPort(against.protocol, against.host); }, ajaxDataType: "text", contentType: "application/json; charset=UTF-8", logging: false, state: signalR.connectionState.disconnected, clientProtocol: "1.5", reconnectDelay: 2000, transportConnectTimeout: 0, disconnectTimeout: 30000, // This should be set by the server in response to the negotiate request (30s default) reconnectWindow: 30000, // This should be set by the server in response to the negotiate request keepAliveWarnAt: 2 / 3, // Warn user of slow connection if we breach the X% mark of the keep alive timeout start: function (options, callback) { /// <summary>Starts the connection</summary> /// <param name="options" type="Object">Options map</param> /// <param name="callback" type="Function">A callback function to execute when the connection has started</param> var connection = this, config = { pingInterval: 300000, waitForPageLoad: true, transport: "auto", jsonp: false }, initialize, deferred = connection._deferral || $.Deferred(), // Check to see if there is a pre-existing deferral that's being built on, if so we want to keep using it parser = window.document.createElement("a"); connection.lastError = null; // Persist the deferral so that if start is called multiple times the same deferral is used. connection._deferral = deferred; if (!connection.json) { // no JSON! throw new Error("SignalR: No JSON parser found. Please ensure json2.js is referenced before the SignalR.js file if you need to support clients without native JSON parsing support, e.g. IE<8."); } if ($.type(options) === "function") { // Support calling with single callback parameter callback = options; } else if ($.type(options) === "object") { $.extend(config, options); if ($.type(config.callback) === "function") { callback = config.callback; } } config.transport = validateTransport(config.transport, connection); // If the transport is invalid throw an error and abort start if (!config.transport) { throw new Error("SignalR: Invalid transport(s) specified, aborting start."); } connection._.config = config; // Check to see if start is being called prior to page load // If waitForPageLoad is true we then want to re-direct function call to the window load event if (!_pageLoaded && config.waitForPageLoad === true) { connection._.deferredStartHandler = function () { connection.start(options, callback); }; _pageWindow.bind("load", connection._.deferredStartHandler); return deferred.promise(); } // If we're already connecting just return the same deferral as the original connection start if (connection.state === signalR.connectionState.connecting) { return deferred.promise(); } else if (changeState(connection, signalR.connectionState.disconnected, signalR.connectionState.connecting) === false) { // We're not connecting so try and transition into connecting. // If we fail to transition then we're either in connected or reconnecting. deferred.resolve(connection); return deferred.promise(); } configureStopReconnectingTimeout(connection); // Resolve the full url parser.href = connection.url; if (!parser.protocol || parser.protocol === ":") { connection.protocol = window.document.location.protocol; connection.host = parser.host || window.document.location.host; } else { connection.protocol = parser.protocol; connection.host = parser.host; } connection.baseUrl = connection.protocol + "//" + connection.host; // Set the websocket protocol connection.wsProtocol = connection.protocol === "https:" ? "wss://" : "ws://"; // If jsonp with no/auto transport is specified, then set the transport to long polling // since that is the only transport for which jsonp really makes sense. // Some developers might actually choose to specify jsonp for same origin requests // as demonstrated by Issue #623. if (config.transport === "auto" && config.jsonp === true) { config.transport = "longPolling"; } // If the url is protocol relative, prepend the current windows protocol to the url. if (connection.url.indexOf("//") === 0) { connection.url = window.location.protocol + connection.url; connection.log("Protocol relative URL detected, normalizing it to '" + connection.url + "'."); } if (this.isCrossDomain(connection.url)) { connection.log("Auto detected cross domain url."); if (config.transport === "auto") { // TODO: Support XDM with foreverFrame config.transport = ["webSockets", "serverSentEvents", "longPolling"]; } if (typeof (config.withCredentials) === "undefined") { config.withCredentials = true; } // Determine if jsonp is the only choice for negotiation, ajaxSend and ajaxAbort. // i.e. if the browser doesn't supports CORS // If it is, ignore any preference to the contrary, and switch to jsonp. if (!config.jsonp) { config.jsonp = !$.support.cors; if (config.jsonp) { connection.log("Using jsonp because this browser doesn't support CORS."); } } connection.contentType = signalR._.defaultContentType; } connection.withCredentials = config.withCredentials; connection.ajaxDataType = config.jsonp ? "jsonp" : "text"; $(connection).bind(events.onStart, function (e, data) { if ($.type(callback) === "function") { callback.call(connection); } deferred.resolve(connection); }); connection._.initHandler = signalR.transports._logic.initHandler(connection); initialize = function (transports, index) { var noTransportError = signalR._.error(resources.noTransportOnInit); index = index || 0; if (index >= transports.length) { if (index === 0) { connection.log("No transports supported by the server were selected."); } else if (index === 1) { connection.log("No fallback transports were selected."); } else { connection.log("Fallback transports exhausted."); } // No transport initialized successfully $(connection).triggerHandler(events.onError, [noTransportError]); deferred.reject(noTransportError); // Stop the connection if it has connected and move it into the disconnected state connection.stop(); return; } // The connection was aborted if (connection.state === signalR.connectionState.disconnected) { return; } var transportName = transports[index], transport = signalR.transports[transportName], onFallback = function () { initialize(transports, index + 1); }; connection.transport = transport; try { connection._.initHandler.start(transport, function () { // success // Firefox 11+ doesn't allow sync XHR withCredentials: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#withCredentials var isFirefox11OrGreater = signalR._.firefoxMajorVersion(window.navigator.userAgent) >= 11, asyncAbort = !!connection.withCredentials && isFirefox11OrGreater; connection.log("The start request succeeded. Transitioning to the connected state."); if (supportsKeepAlive(connection)) { signalR.transports._logic.monitorKeepAlive(connection); } signalR.transports._logic.startHeartbeat(connection); // Used to ensure low activity clients maintain their authentication. // Must be configured once a transport has been decided to perform valid ping requests. signalR._.configurePingInterval(connection); if (!changeState(connection, signalR.connectionState.connecting, signalR.connectionState.connected)) { connection.log("WARNING! The connection was not in the connecting state."); } // Drain any incoming buffered messages (messages that came in prior to connect) connection._.connectingMessageBuffer.drain(); $(connection).triggerHandler(events.onStart); // wire the stop handler for when the user leaves the page _pageWindow.bind("unload", function () { connection.log("Window unloading, stopping the connection."); connection.stop(asyncAbort); }); if (isFirefox11OrGreater) { // Firefox does not fire cross-domain XHRs in the normal unload handler on tab close. // #2400 _pageWindow.bind("beforeunload", function () { // If connection.stop() runs runs in beforeunload and fails, it will also fail // in unload unless connection.stop() runs after a timeout. window.setTimeout(function () { connection.stop(asyncAbort); }, 0); }); } }, onFallback); } catch (error) { connection.log(transport.name + " transport threw '" + error.message + "' when attempting to start."); onFallback(); } }; var url = connection.url + "/negotiate", onFailed = function (error, connection) { var err = signalR._.error(resources.errorOnNegotiate, error, connection._.negotiateRequest); $(connection).triggerHandler(events.onError, err); deferred.reject(err); // Stop the connection if negotiate failed connection.stop(); }; $(connection).triggerHandler(events.onStarting); url = signalR.transports._logic.prepareQueryString(connection, url); connection.log("Negotiating with '" + url + "'."); // Save the ajax negotiate request object so we can abort it if stop is called while the request is in flight. connection._.negotiateRequest = signalR.transports._logic.ajax(connection, { url: url, error: function (error, statusText) { // We don't want to cause any errors if we're aborting our own negotiate request. if (statusText !== _negotiateAbortText) { onFailed(error, connection); } else { // This rejection will noop if the deferred has already been resolved or rejected. deferred.reject(signalR._.error(resources.stoppedWhileNegotiating, null /* error */, connection._.negotiateRequest)); } }, success: function (result) { var res, keepAliveData, protocolError, transports = [], supportedTransports = []; try { res = connection._parseResponse(result); } catch (error) { onFailed(signalR._.error(resources.errorParsingNegotiateResponse, error), connection); return; } keepAliveData = connection._.keepAliveData; connection.appRelativeUrl = res.Url; connection.id = res.ConnectionId; connection.token = res.ConnectionToken; connection.webSocketServerUrl = res.WebSocketServerUrl; // The long poll timeout is the ConnectionTimeout plus 10 seconds connection._.pollTimeout = res.ConnectionTimeout * 1000 + 10000; // in ms // Once the server has labeled the PersistentConnection as Disconnected, we should stop attempting to reconnect // after res.DisconnectTimeout seconds. connection.disconnectTimeout = res.DisconnectTimeout * 1000; // in ms // Add the TransportConnectTimeout from the response to the transportConnectTimeout from the client to calculate the total timeout connection._.totalTransportConnectTimeout = connection.transportConnectTimeout + res.TransportConnectTimeout * 1000; // If we have a keep alive if (res.KeepAliveTimeout) { // Register the keep alive data as activated keepAliveData.activated = true; // Timeout to designate when to force the connection into reconnecting converted to milliseconds keepAliveData.timeout = res.KeepAliveTimeout * 1000; // Timeout to designate when to warn the developer that the connection may be dead or is not responding. keepAliveData.timeoutWarning = keepAliveData.timeout * connection.keepAliveWarnAt; // Instantiate the frequency in which we check the keep alive. It must be short in order to not miss/pick up any changes connection._.beatInterval = (keepAliveData.timeout - keepAliveData.timeoutWarning) / 3; } else { keepAliveData.activated = false; } connection.reconnectWindow = connection.disconnectTimeout + (keepAliveData.timeout || 0); if (!res.ProtocolVersion || res.ProtocolVersion !== connection.clientProtocol) { protocolError = signalR._.error(signalR._.format(resources.protocolIncompatible, connection.clientProtocol, res.ProtocolVersion)); $(connection).triggerHandler(events.onError, [protocolError]); deferred.reject(protocolError); return; } $.each(signalR.transports, function (key) { if ((key.indexOf("_") === 0) || (key === "webSockets" && !res.TryWebSockets)) { return true; } supportedTransports.push(key); }); if ($.isArray(config.transport)) { $.each(config.transport, function (_, transport) { if ($.inArray(transport, supportedTransports) >= 0) { transports.push(transport); } }); } else if (config.transport === "auto") { transports = supportedTransports; } else if ($.inArray(config.transport, supportedTransports) >= 0) { transports.push(config.transport); } initialize(transports); } }); return deferred.promise(); }, starting: function (callback) { /// <summary>Adds a callback that will be invoked before anything is sent over the connection</summary> /// <param name="callback" type="Function">A callback function to execute before the connection is fully instantiated.</param> /// <returns type="signalR" /> var connection = this; $(connection).bind(events.onStarting, function (e, data) { callback.call(connection); }); return connection; }, send: function (data) { /// <summary>Sends data over the connection</summary> /// <param name="data" type="String">The data to send over the connection</param> /// <returns type="signalR" /> var connection = this; if (connection.state === signalR.connectionState.disconnected) { // Connection hasn't been started yet throw new Error("SignalR: Connection must be started before data can be sent. Call .start() before .send()"); } if (connection.state === signalR.connectionState.connecting) { // Connection hasn't been started yet throw new Error("SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started."); } connection.transport.send(connection, data); // REVIEW: Should we return deferred here? return connection; }, received: function (callback) { /// <summary>Adds a callback that will be invoked after anything is received over the connection</summary> /// <param name="callback" type="Function">A callback function to execute when any data is received on the connection</param> /// <returns type="signalR" /> var connection = this; $(connection).bind(events.onReceived, function (e, data) { callback.call(connection, data); }); return connection; }, stateChanged: function (callback) { /// <summary>Adds a callback that will be invoked when the connection state changes</summary> /// <param name="callback" type="Function">A callback function to execute when the connection state changes</param> /// <returns type="signalR" /> var connection = this; $(connection).bind(events.onStateChanged, function (e, data) { callback.call(connection, data); }); return connection; }, error: function (callback) { /// <summary>Adds a callback that will be invoked after an error occurs with the connection</summary> /// <param name="callback" type="Function">A callback function to execute when an error occurs on the connection</param> /// <returns type="signalR" /> var connection = this; $(connection).bind(events.onError, function (e, errorData, sendData) { connection.lastError = errorData; // In practice 'errorData' is the SignalR built error object. // In practice 'sendData' is undefined for all error events except those triggered by // 'ajaxSend' and 'webSockets.send'.'sendData' is the original send payload. callback.call(connection, errorData, sendData); }); return connection; }, disconnected: function (callback) { /// <summary>Adds a callback that will be invoked when the client disconnects</summary> /// <param name="callback" type="Function">A callback function to execute when the connection is broken</param> /// <returns type="signalR" /> var connection = this; $(connection).bind(events.onDisconnect, function (e, data) { callback.call(connection); }); return connection; }, connectionSlow: function (callback) { /// <summary>Adds a callback that will be invoked when the client detects a slow connection</summary> /// <param name="callback" type="Function">A callback function to execute when the connection is slow</param> /// <returns type="signalR" /> var connection = this; $(connection).bind(events.onConnectionSlow, function (e, data) { callback.call(connection); }); return connection; }, reconnecting: function (callback) { /// <summary>Adds a callback that will be invoked when the underlying transport begins reconnecting</summary> /// <param name="callback" type="Function">A callback function to execute when the connection enters a reconnecting state</param> /// <returns type="signalR" /> var connection = this; $(connection).bind(events.onReconnecting, function (e, data) { callback.call(connection); }); return connection; }, reconnected: function (callback) { /// <summary>Adds a callback that will be invoked when the underlying transport reconnects</summary> /// <param name="callback" type="Function">A callback function to execute when the connection is restored</param> /// <returns type="signalR" /> var connection = this; $(connection).bind(events.onReconnect, function (e, data) { callback.call(connection); }); return connection; }, stop: function (async, notifyServer) { /// <summary>Stops listening</summary> /// <param name="async" type="Boolean">Whether or not to asynchronously abort the connection</param> /// <param name="notifyServer" type="Boolean">Whether we want to notify the server that we are aborting the connection</param> /// <returns type="signalR" /> var connection = this, // Save deferral because this is always cleaned up deferral = connection._deferral; // Verify that we've bound a load event. if (connection._.deferredStartHandler) { // Unbind the event. _pageWindow.unbind("load", connection._.deferredStartHandler); } // Always clean up private non-timeout based state. delete connection._.config; delete connection._.deferredStartHandler; // This needs to be checked despite the connection state because a connection start can be deferred until page load. // If we've deferred the start due to a page load we need to unbind the "onLoad" -> start event. if (!_pageLoaded && (!connection._.config || connection._.config.waitForPageLoad === true)) { connection.log("Stopping connection prior to negotiate."); // If we have a deferral we should reject it if (deferral) { deferral.reject(signalR._.error(resources.stoppedWhileLoading)); } // Short-circuit because the start has not been fully started. return; } if (connection.state === signalR.connectionState.disconnected) { return; } connection.log("Stopping connection."); // Clear this no matter what window.clearTimeout(connection._.beatHandle); window.clearInterval(connection._.pingIntervalId); if (connection.transport) { connection.transport.stop(connection); if (notifyServer !== false) { connection.transport.abort(connection, async); } if (supportsKeepAlive(connection)) { signalR.transports._logic.stopMonitoringKeepAlive(connection); } connection.transport = null; } if (connection._.negotiateRequest) { // If the negotiation request has already completed this will noop. connection._.negotiateRequest.abort(_negotiateAbortText); delete connection._.negotiateRequest; } // Ensure that initHandler.stop() is called before connection._deferral is deleted if (connection._.initHandler) { connection._.initHandler.stop(); } delete connection._deferral; delete connection.messageId; delete connection.groupsToken; delete connection.id; delete connection._.pingIntervalId; delete connection._.lastMessageAt; delete connection._.lastActiveAt; // Clear out our message buffer connection._.connectingMessageBuffer.clear(); // Trigger the disconnect event changeState(connection, connection.state, signalR.connectionState.disconnected); $(connection).triggerHandler(events.onDisconnect); return connection; }, log: function (msg) { log(msg, this.logging); } }; signalR.fn.init.prototype = signalR.fn; signalR.noConflict = function () { /// <summary>Reinstates the original value of $.connection and returns the signalR object for manual assignment</summary> /// <returns type="signalR" /> if ($.connection === signalR) { $.connection = _connection; } return signalR; }; if ($.connection) { _connection = $.connection; } $.connection = $.signalR = signalR; }(window.jQuery, window)); /* jquery.signalR.transports.common.js */ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. /*global window:false */ /// <reference path="jquery.signalR.core.js" /> (function ($, window, undefined) { var signalR = $.signalR, events = $.signalR.events, changeState = $.signalR.changeState, startAbortText = "__Start Aborted__", transportLogic; signalR.transports = {}; function beat(connection) { if (connection._.keepAliveData.monitoring) { checkIfAlive(connection); } // Ensure that we successfully marked active before continuing the heartbeat. if (transportLogic.markActive(connection)) { connection._.beatHandle = window.setTimeout(function () { beat(connection); }, connection._.beatInterval); } } function checkIfAlive(connection) { var keepAliveData = connection._.keepAliveData, timeElapsed; // Only check if we're connected if (connection.state === signalR.connectionState.connected) { timeElapsed = new Date().getTime() - connection._.lastMessageAt; // Check if the keep alive has completely timed out if (timeElapsed >= keepAliveData.timeout) { connection.log("Keep alive timed out. Notifying transport that connection has been lost."); // Notify transport that the connection has been lost connection.transport.lostConnection(connection); } else if (timeElapsed >= keepAliveData.timeoutWarning) { // This is to assure that the user only gets a single warning if (!keepAliveData.userNotified) { connection.log("Keep alive has been missed, connection may be dead/slow."); $(connection).triggerHandler(events.onConnectionSlow); keepAliveData.userNotified = true; } } else { keepAliveData.userNotified = false; } } } function getAjaxUrl(connection, path) { var url = connection.url + path; if (connection.transport) { url += "?transport=" + connection.transport.name; } return transportLogic.prepareQueryString(connection, url); } function InitHandler(connection) { this.connection = connection; this.startRequested = false; this.startCompleted = false; this.connectionStopped = false; } InitHandler.prototype = { start: function (transport, onSuccess, onFallback) { var that = this, connection = that.connection, failCalled = false; if (that.startRequested || that.connectionStopped) { connection.log("WARNING! " + transport.name + " transport cannot be started. Initialization ongoing or completed."); return; } connection.log(transport.name + " transport starting."); transport.start(connection, function () { if (!failCalled) { that.initReceived(transport, onSuccess); } }, function (error) { // Don't allow the same transport to cause onFallback to be called twice if (!failCalled) { failCalled = true; that.transportFailed(transport, error, onFallback); } // Returns true if the transport should stop; // false if it should attempt to reconnect return !that.startCompleted || that.connectionStopped; }); that.transportTimeoutHandle = window.setTimeout(function () { if (!failCalled) { failCalled = true; connection.log(transport.name + " transport timed out when trying to connect."); that.transportFailed(transport, undefined, onFallback); } }, connection._.totalTransportConnectTimeout); }, stop: function () { this.connectionStopped = true; window.clearTimeout(this.transportTimeoutHandle); signalR.transports._logic.tryAbortStartRequest(this.connection); }, initReceived: function (transport, onSuccess) { var that = this, connection = that.connection; if (that.startRequested) { connection.log("WARNING! The client received multiple init messages."); return; } if (that.connectionStopped) { return; } that.startRequested = true; window.clearTimeout(that.transportTimeoutHandle); connection.log(transport.name + " transport connected. Initiating start request."); signalR.transports._logic.ajaxStart(connection, function () { that.startCompleted = true; onSuccess(); }); }, transportFailed: function (transport, error, onFallback) { var connection = this.connection, deferred = connection._deferral, wrappedError; if (this.connectionStopped) { return; } window.clearTimeout(this.transportTimeoutHandle); if (!this.startRequested) { transport.stop(connection); connection.log(transport.name + " transport failed to connect. Attempting to fall back."); onFallback(); } else if (!this.startCompleted) { // Do not attempt to fall back if a start request is ongoing during a transport failure. // Instead, trigger an error and stop the connection. wrappedError = signalR._.error(signalR.resources.errorDuringStartRequest, error); connection.log(transport.name + " transport failed during the start request. Stopping the connection."); $(connection).triggerHandler(events.onError, [wrappedError]); if (deferred) { deferred.reject(wrappedError); } connection.stop(); } else { // The start request has completed, but the connection has not stopped. // No need to do anything here. The transport should attempt its normal reconnect logic. } } }; transportLogic = signalR.transports._logic = { ajax: function (connection, options) { return $.ajax( $.extend(/*deep copy*/ true, {}, $.signalR.ajaxDefaults, { type: "GET", data: {}, xhrFields: { withCredentials: connection.withCredentials }, contentType: connection.contentType, dataType: connection.ajaxDataType }, options)); }, pingServer: function (connection) { /// <summary>Pings the server</summary> /// <param name="connection" type="signalr">Connection associated with the server ping</param> /// <returns type="signalR" /> var url, xhr, deferral = $.Deferred(); if (connection.transport) { url = connection.url + "/ping"; url = transportLogic.addQs(url, connection.qs); xhr = transportLogic.ajax(connection, { url: url, success: function (result) { var data; try { data = connection._parseResponse(result); } catch (error) { deferral.reject( signalR._.transportError( signalR.resources.pingServerFailedParse, connection.transport, error, xhr ) ); connection.stop(); return; } if (data.Response === "pong") { deferral.resolve(); } else { deferral.reject( signalR._.transportError( signalR._.format(signalR.resources.pingServerFailedInvalidResponse, result), connection.transport, null /* error */, xhr ) ); } }, error: function (error) { if (error.status === 401 || error.status === 403) { deferral.reject( signalR._.transportError( signalR._.format(signalR.resources.pingServerFailedStatusCode, error.status), connection.transport, error, xhr ) ); connection.stop(); } else { deferral.reject( signalR._.transportError( signalR.resources.pingServerFailed, connection.transport, error, xhr ) ); } } }); } else { deferral.reject( signalR._.transportError( signalR.resources.noConnectionTransport, connection.transport ) ); } return deferral.promise(); }, prepareQueryString: function (connection, url) { var preparedUrl; // Use addQs to start since it handles the ?/& prefix for us preparedUrl = transportLogic.addQs(url, "clientProtocol=" + connection.clientProtocol); // Add the user-specified query string params if any preparedUrl = transportLogic.addQs(preparedUrl, connection.qs); if (connection.token) { preparedUrl += "&connectionToken=" + window.encodeURIComponent(connection.token); } if (connection.data) { preparedUrl += "&connectionData=" + window.encodeURIComponent(connection.data); } return preparedUrl; }, addQs: function (url, qs) { var appender = url.indexOf("?") !== -1 ? "&" : "?", firstChar; if (!qs) { return url; } if (typeof (qs) === "object") { return url + appender + $.param(qs); } if (typeof (qs) === "string") { firstChar = qs.charAt(0); if (firstChar === "?" || firstChar === "&") { appender = ""; } return url + appender + qs; } throw new Error("Query string property must be either a string or object."); }, // BUG #2953: The url needs to be same otherwise it will cause a memory leak getUrl: function (connection, transport, reconnecting, poll, ajaxPost) { /// <summary>Gets the url for making a GET based connect request</summary> var baseUrl = transport === "webSockets" ? "" : connection.baseUrl, url = baseUrl + connection.appRelativeUrl, qs = "transport=" + transport; if (!ajaxPost && connection.groupsToken) { qs += "&groupsToken=" + window.encodeURIComponent(connection.groupsToken); } if (!reconnecting) { url += "/connect"; } else { if (poll) { // longPolling transport specific url += "/poll"; } else { url += "/reconnect"; } if (!ajaxPost && connection.messageId) { qs += "&messageId=" + window.encodeURIComponent(connection.messageId); } } url += "?" + qs; url = transportLogic.prepareQueryString(connection, url); if (!ajaxPost) { url += "&tid=" + Math.floor(Math.random() * 11); } return url; }, maximizePersistentResponse: function (minPersistentResponse) { return { MessageId: minPersistentResponse.C, Messages: minPersistentResponse.M, Initialized: typeof (minPersistentResponse.S) !== "undefined" ? true : false, ShouldReconnect: typeof (minPersistentResponse.T) !== "undefined" ? true : false, LongPollDelay: minPersistentResponse.L, GroupsToken: minPersistentResponse.G }; }, updateGroups: function (connection, groupsToken) { if (groupsToken) { connection.groupsToken = groupsToken; } }, stringifySend: function (connection, message) { if (typeof (message) === "string" || typeof (message) === "undefined" || message === null) { return message; } return connection.json.stringify(message); }, ajaxSend: function (connection, data) { var payload = transportLogic.stringifySend(connection, data), url = getAjaxUrl(connection, "/send"), xhr, onFail = function (error, connection) { $(connection).triggerHandler(events.onError, [signalR._.transportError(signalR.resources.sendFailed, connection.transport, error, xhr), data]); }; xhr = transportLogic.ajax(connection, { url: url, type: connection.ajaxDataType === "jsonp" ? "GET" : "POST", contentType: signalR._.defaultContentType, data: { data: payload }, success: function (result) { var res; if (result) { try { res = connection._parseResponse(result); } catch (error) { onFail(error, connection); connection.stop(); return; } transportLogic.triggerReceived(connection, res); } }, error: function (error, textStatus) { if (textStatus === "abort" || textStatus === "parsererror") { // The parsererror happens for sends that don't return any data, and hence // don't write the jsonp callback to the response. This is harder to fix on the server // so just hack around it on the client for now. return; } onFail(error, connection); } }); return xhr; }, ajaxAbort: function (connection, async) { if (typeof (connection.transport) === "undefined") { return; } // Async by default unless explicitly overidden async = typeof async === "undefined" ? true : async; var url = getAjaxUrl(connection, "/abort"); transportLogic.ajax(connection, { url: url, async: async, timeout: 1000, type: "POST" }); connection.log("Fired ajax abort async = " + async + "."); }, ajaxStart: function (connection, onSuccess) { var rejectDeferred = function (error) { var deferred = connection._deferral; if (deferred) { deferred.reject(error); } }, triggerStartError = function (error) { connection.log("The start request failed. Stopping the connection."); $(connection).triggerHandler(events.onError, [error]); rejectDeferred(error); connection.stop(); }; connection._.startRequest = transportLogic.ajax(connection, { url: getAjaxUrl(connection, "/start"), success: function (result, statusText, xhr) { var data; try { data = connection._parseResponse(result); } catch (error) { triggerStartError(signalR._.error( signalR._.format(signalR.resources.errorParsingStartResponse, result), error, xhr)); return; } if (data.Response === "started") { onSuccess(); } else { triggerStartError(signalR._.error( signalR._.format(signalR.resources.invalidStartResponse, result), null /* error */, xhr)); } }, error: function (xhr, statusText, error) { if (statusText !== startAbortText) { triggerStartError(signalR._.error( signalR.resources.errorDuringStartRequest, error, xhr)); } else { // Stop has been called, no need to trigger the error handler // or stop the connection again with onStartError connection.log("The start request aborted because connection.stop() was called."); rejectDeferred(signalR._.error( signalR.resources.stoppedDuringStartRequest, null /* error */, xhr)); } } }); }, tryAbortStartRequest: function (connection) { if (connection._.startRequest) { // If the start request has already completed this will noop. connection._.startRequest.abort(startAbortText); delete connection._.startRequest; } }, tryInitialize: function (connection, persistentResponse, onInitialized) { if (persistentResponse.Initialized && onInitialized) { onInitialized(); } else if (persistentResponse.Initialized) { connection.log("WARNING! The client received an init message after reconnecting."); } }, triggerReceived: function (connection, data) { if (!connection._.connectingMessageBuffer.tryBuffer(data)) { $(connection).triggerHandler(events.onReceived, [data]); } }, processMessages: function (connection, minData, onInitialized) { var data; // Update the last message time stamp transportLogic.markLastMessage(connection); if (minData) { data = transportLogic.maximizePersistentResponse(minData); transportLogic.updateGroups(connection, data.GroupsToken); if (data.MessageId) { connection.messageId = data.MessageId; } if (data.Messages) { $.each(data.Messages, function (index, message) { transportLogic.triggerReceived(connection, message); }); transportLogic.tryInitialize(connection, data, onInitialized); } } }, monitorKeepAlive: function (connection) { var keepAliveData = connection._.keepAliveData; // If we haven't initiated the keep alive timeouts then we need to if (!keepAliveData.monitoring) { keepAliveData.monitoring = true; transportLogic.markLastMessage(connection); // Save the function so we can unbind it on stop connection._.keepAliveData.reconnectKeepAliveUpdate = function () { // Mark a new message so that keep alive doesn't time out connections transportLogic.markLastMessage(connection); }; // Update Keep alive on reconnect $(connection).bind(events.onReconnect, connection._.keepAliveData.reconnectKeepAliveUpdate); connection.log("Now monitoring keep alive with a warning timeout of " + keepAliveData.timeoutWarning + ", keep alive timeout of " + keepAliveData.timeout + " and disconnecting timeout of " + connection.disconnectTimeout); } else { connection.log("Tried to monitor keep alive but it's already being monitored."); } }, stopMonitoringKeepAlive: function (connection) { var keepAliveData = connection._.keepAliveData; // Only attempt to stop the keep alive monitoring if its being monitored if (keepAliveData.monitoring) { // Stop monitoring keepAliveData.monitoring = false; // Remove the updateKeepAlive function from the reconnect event $(connection).unbind(events.onReconnect, connection._.keepAliveData.reconnectKeepAliveUpdate); // Clear all the keep alive data connection._.keepAliveData = {}; connection.log("Stopping the monitoring of the keep alive."); } }, startHeartbeat: function (connection) { connection._.lastActiveAt = new Date().getTime(); beat(connection); }, markLastMessage: function (connection) { connection._.lastMessageAt = new Date().getTime(); }, markActive: function (connection) { if (transportLogic.verifyLastActive(connection)) { connection._.lastActiveAt = new Date().getTime(); return true; } return false; }, isConnectedOrReconnecting: function (connection) { return connection.state === signalR.connectionState.connected || connection.state === signalR.connectionState.reconnecting; }, ensureReconnectingState: function (connection) { if (changeState(connection, signalR.connectionState.connected, signalR.connectionState.reconnecting) === true) { $(connection).triggerHandler(events.onReconnecting); } return connection.state === signalR.connectionState.reconnecting; }, clearReconnectTimeout: function (connection) { if (connection && connection._.reconnectTimeout) { window.clearTimeout(connection._.reconnectTimeout); delete connection._.reconnectTimeout; } }, verifyLastActive: function (connection) { if (new Date().getTime() - connection._.lastActiveAt >= connection.reconnectWindow) { var message = signalR._.format(signalR.resources.reconnectWindowTimeout, new Date(connection._.lastActiveAt), connection.reconnectWindow); connection.log(message); $(connection).triggerHandler(events.onError, [signalR._.error(message, /* source */ "TimeoutException")]); connection.stop(/* async */ false, /* notifyServer */ false); return false; } return true; }, reconnect: function (connection, transportName) { var transport = signalR.transports[transportName]; // We should only set a reconnectTimeout if we are currently connected // and a reconnectTimeout isn't already set. if (transportLogic.isConnectedOrReconnecting(connection) && !connection._.reconnectTimeout) { // Need to verify before the setTimeout occurs because an application sleep could occur during the setTimeout duration. if (!transportLogic.verifyLastActive(connection)) { return; } connection._.reconnectTimeout = window.setTimeout(function () { if (!transportLogic.verifyLastActive(connection)) { return; } transport.stop(connection); if (transportLogic.ensureReconnectingState(connection)) { connection.log(transportName + " reconnecting."); transport.start(connection); } }, connection.reconnectDelay); } }, handleParseFailure: function (connection, result, error, onFailed, context) { var wrappedError = signalR._.transportError( signalR._.format(signalR.resources.parseFailed, result), connection.transport, error, context); // If we're in the initialization phase trigger onFailed, otherwise stop the connection. if (onFailed && onFailed(wrappedError)) { connection.log("Failed to parse server response while attempting to connect."); } else { $(connection).triggerHandler(events.onError, [wrappedError]); connection.stop(); } }, initHandler: function (connection) { return new InitHandler(connection); }, foreverFrame: { count: 0, connections: {} } }; }(window.jQuery, window)); /* jquery.signalR.transports.webSockets.js */ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. /*global window:false */ /// <reference path="jquery.signalR.transports.common.js" /> (function ($, window, undefined) { var signalR = $.signalR, events = $.signalR.events, changeState = $.signalR.changeState, transportLogic = signalR.transports._logic; signalR.transports.webSockets = { name: "webSockets", supportsKeepAlive: function () { return true; }, send: function (connection, data) { var payload = transportLogic.stringifySend(connection, data); try { connection.socket.send(payload); } catch (ex) { $(connection).triggerHandler(events.onError, [signalR._.transportError( signalR.resources.webSocketsInvalidState, connection.transport, ex, connection.socket ), data]); } }, start: function (connection, onSuccess, onFailed) { var url, opened = false, that = this, reconnecting = !onSuccess, $connection = $(connection); if (!window.WebSocket) { onFailed(); return; } if (!connection.socket) { if (connection.webSocketServerUrl) { url = connection.webSocketServerUrl; } else { url = connection.wsProtocol + connection.host; } url += transportLogic.getUrl(connection, this.name, reconnecting); connection.log("Connecting to websocket endpoint '" + url + "'."); connection.socket = new window.WebSocket(url); connection.socket.onopen = function () { opened = true; connection.log("Websocket opened."); transportLogic.clearReconnectTimeout(connection); if (changeState(connection, signalR.connectionState.reconnecting, signalR.connectionState.connected) === true) { $connection.triggerHandler(events.onReconnect); } }; connection.socket.onclose = function (event) { var error; // Only handle a socket close if the close is from the current socket. // Sometimes on disconnect the server will push down an onclose event // to an expired socket. if (this === connection.socket) { if (opened && typeof event.wasClean !== "undefined" && event.wasClean === false) { // Ideally this would use the websocket.onerror handler (rather than checking wasClean in onclose) but // I found in some circumstances Chrome won't call onerror. This implementation seems to work on all browsers. error = signalR._.transportError( signalR.resources.webSocketClosed, connection.transport, event); connection.log("Unclean disconnect from websocket: " + (event.reason || "[no reason given].")); } else { connection.log("Websocket closed."); } if (!onFailed || !onFailed(error)) { if (error) { $(connection).triggerHandler(events.onError, [error]); } that.reconnect(connection); } } }; connection.socket.onmessage = function (event) { var data; try { data = connection._parseResponse(event.data); } catch (error) { transportLogic.handleParseFailure(connection, event.data, error, onFailed, event); return; } if (data) { // data.M is PersistentResponse.Messages if ($.isEmptyObject(data) || data.M) { transportLogic.processMessages(connection, data, onSuccess); } else { // For websockets we need to trigger onReceived // for callbacks to outgoing hub calls. transportLogic.triggerReceived(connection, data); } } }; } }, reconnect: function (connection) { transportLogic.reconnect(connection, this.name); }, lostConnection: function (connection) { this.reconnect(connection); }, stop: function (connection) { // Don't trigger a reconnect after stopping transportLogic.clearReconnectTimeout(connection); if (connection.socket) { connection.log("Closing the Websocket."); connection.socket.close(); connection.socket = null; } }, abort: function (connection, async) { transportLogic.ajaxAbort(connection, async); } }; }(window.jQuery, window)); /* jquery.signalR.transports.serverSentEvents.js */ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. /*global window:false */ /// <reference path="jquery.signalR.transports.common.js" /> (function ($, window, undefined) { var signalR = $.signalR, events = $.signalR.events, changeState = $.signalR.changeState, transportLogic = signalR.transports._logic, clearReconnectAttemptTimeout = function (connection) { window.clearTimeout(connection._.reconnectAttemptTimeoutHandle); delete connection._.reconnectAttemptTimeoutHandle; }; signalR.transports.serverSentEvents = { name: "serverSentEvents", supportsKeepAlive: function () { return true; }, timeOut: 3000, start: function (connection, onSuccess, onFailed) { var that = this, opened = false, $connection = $(connection), reconnecting = !onSuccess, url; if (connection.eventSource) { connection.log("The connection already has an event source. Stopping it."); connection.stop(); } if (!window.EventSource) { if (onFailed) { connection.log("This browser doesn't support SSE."); onFailed(); } return; } url = transportLogic.getUrl(connection, this.name, reconnecting); try { connection.log("Attempting to connect to SSE endpoint '" + url + "'."); connection.eventSource = new window.EventSource(url, { withCredentials: connection.withCredentials }); } catch (e) { connection.log("EventSource failed trying to connect with error " + e.Message + "."); if (onFailed) { // The connection failed, call the failed callback onFailed(); } else { $connection.triggerHandler(events.onError, [signalR._.transportError(signalR.resources.eventSourceFailedToConnect, connection.transport, e)]); if (reconnecting) { // If we were reconnecting, rather than doing initial connect, then try reconnect again that.reconnect(connection); } } return; } if (reconnecting) { connection._.reconnectAttemptTimeoutHandle = window.setTimeout(function () { if (opened === false) { // If we're reconnecting and the event source is attempting to connect, // don't keep retrying. This causes duplicate connections to spawn. if (connection.eventSource.readyState !== window.EventSource.OPEN) { // If we were reconnecting, rather than doing initial connect, then try reconnect again that.reconnect(connection); } } }, that.timeOut); } connection.eventSource.addEventListener("open", function (e) { connection.log("EventSource connected."); clearReconnectAttemptTimeout(connection); transportLogic.clearReconnectTimeout(connection); if (opened === false) { opened = true; if (changeState(connection, signalR.connectionState.reconnecting, signalR.connectionState.connected) === true) { $connection.triggerHandler(events.onReconnect); } } }, false); connection.eventSource.addEventListener("message", function (e) { var res; // process messages if (e.data === "initialized") { return; } try { res = connection._parseResponse(e.data); } catch (error) { transportLogic.handleParseFailure(connection, e.data, error, onFailed, e); return; } transportLogic.processMessages(connection, res, onSuccess); }, false); connection.eventSource.addEventListener("error", function (e) { var error = signalR._.transportError( signalR.resources.eventSourceError, connection.transport, e); // Only handle an error if the error is from the current Event Source. // Sometimes on disconnect the server will push down an error event // to an expired Event Source. if (this !== connection.eventSource) { return; } if (onFailed && onFailed(error)) { return; } connection.log("EventSource readyState: " + connection.eventSource.readyState + "."); if (e.eventPhase === window.EventSource.CLOSED) { // We don't use the EventSource's native reconnect function as it // doesn't allow us to change the URL when reconnecting. We need // to change the URL to not include the /connect suffix, and pass // the last message id we received. connection.log("EventSource reconnecting due to the server connection ending."); that.reconnect(connection); } else { // connection error connection.log("EventSource error."); $connection.triggerHandler(events.onError, [error]); } }, false); }, reconnect: function (connection) { transportLogic.reconnect(connection, this.name); }, lostConnection: function (connection) { this.reconnect(connection); }, send: function (connection, data) { transportLogic.ajaxSend(connection, data); }, stop: function (connection) { // Don't trigger a reconnect after stopping clearReconnectAttemptTimeout(connection); transportLogic.clearReconnectTimeout(connection); if (connection && connection.eventSource) { connection.log("EventSource calling close()."); connection.eventSource.close(); connection.eventSource = null; delete connection.eventSource; } }, abort: function (connection, async) { transportLogic.ajaxAbort(connection, async); } }; }(window.jQuery, window)); /* jquery.signalR.transports.foreverFrame.js */ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. /*global window:false */ /// <reference path="jquery.signalR.transports.common.js" /> (function ($, window, undefined) { var signalR = $.signalR, events = $.signalR.events, changeState = $.signalR.changeState, transportLogic = signalR.transports._logic, createFrame = function () { var frame = window.document.createElement("iframe"); frame.setAttribute("style", "position:absolute;top:0;left:0;width:0;height:0;visibility:hidden;"); return frame; }, // Used to prevent infinite loading icon spins in older versions of ie // We build this object inside a closure so we don't pollute the rest of // the foreverFrame transport with unnecessary functions/utilities. loadPreventer = (function () { var loadingFixIntervalId = null, loadingFixInterval = 1000, attachedTo = 0; return { prevent: function () { // Prevent additional iframe removal procedures from newer browsers if (signalR._.ieVersion <= 8) { // We only ever want to set the interval one time, so on the first attachedTo if (attachedTo === 0) { // Create and destroy iframe every 3 seconds to prevent loading icon, super hacky loadingFixIntervalId = window.setInterval(function () { var tempFrame = createFrame(); window.document.body.appendChild(tempFrame); window.document.body.removeChild(tempFrame); tempFrame = null; }, loadingFixInterval); } attachedTo++; } }, cancel: function () { // Only clear the interval if there's only one more object that the loadPreventer is attachedTo if (attachedTo === 1) { window.clearInterval(loadingFixIntervalId); } if (attachedTo > 0) { attachedTo--; } } }; })(); signalR.transports.foreverFrame = { name: "foreverFrame", supportsKeepAlive: function () { return true; }, // Added as a value here so we can create tests to verify functionality iframeClearThreshold: 50, start: function (connection, onSuccess, onFailed) { var that = this, frameId = (transportLogic.foreverFrame.count += 1), url, frame = createFrame(), frameLoadHandler = function () { connection.log("Forever frame iframe finished loading and is no longer receiving messages."); if (!onFailed || !onFailed()) { that.reconnect(connection); } }; if (window.EventSource) { // If the browser supports SSE, don't use Forever Frame if (onFailed) { connection.log("Forever Frame is not supported by SignalR on browsers with SSE support."); onFailed(); } return; } frame.setAttribute("data-signalr-connection-id", connection.id); // Start preventing loading icon // This will only perform work if the loadPreventer is not attached to another connection. loadPreventer.prevent(); // Build the url url = transportLogic.getUrl(connection, this.name); url += "&frameId=" + frameId; // add frame to the document prior to setting URL to avoid caching issues. window.document.documentElement.appendChild(frame); connection.log("Binding to iframe's load event."); if (frame.addEventListener) { frame.addEventListener("load", frameLoadHandler, false); } else if (frame.attachEvent) { frame.attachEvent("onload", frameLoadHandler); } frame.src = url; transportLogic.foreverFrame.connections[frameId] = connection; connection.frame = frame; connection.frameId = frameId; if (onSuccess) { connection.onSuccess = function () { connection.log("Iframe transport started."); onSuccess(); }; } }, reconnect: function (connection) { var that = this; // Need to verify connection state and verify before the setTimeout occurs because an application sleep could occur during the setTimeout duration. if (transportLogic.isConnectedOrReconnecting(connection) && transportLogic.verifyLastActive(connection)) { window.setTimeout(function () { // Verify that we're ok to reconnect. if (!transportLogic.verifyLastActive(connection)) { return; } if (connection.frame && transportLogic.ensureReconnectingState(connection)) { var frame = connection.frame, src = transportLogic.getUrl(connection, that.name, true) + "&frameId=" + connection.frameId; connection.log("Updating iframe src to '" + src + "'."); frame.src = src; } }, connection.reconnectDelay); } }, lostConnection: function (connection) { this.reconnect(connection); }, send: function (connection, data) { transportLogic.ajaxSend(connection, data); }, receive: function (connection, data) { var cw, body, response; if (connection.json !== connection._originalJson) { // If there's a custom JSON parser configured then serialize the object // using the original (browser) JSON parser and then deserialize it using // the custom parser (connection._parseResponse does that). This is so we // can easily send the response from the server as "raw" JSON but still // support custom JSON deserialization in the browser. data = connection._originalJson.stringify(data); } response = connection._parseResponse(data); transportLogic.processMessages(connection, response, connection.onSuccess); // Protect against connection stopping from a callback trigger within the processMessages above. if (connection.state === $.signalR.connectionState.connected) { // Delete the script & div elements connection.frameMessageCount = (connection.frameMessageCount || 0) + 1; if (connection.frameMessageCount > signalR.transports.foreverFrame.iframeClearThreshold) { connection.frameMessageCount = 0; cw = connection.frame.contentWindow || connection.frame.contentDocument; if (cw && cw.document && cw.document.body) { body = cw.document.body; // Remove all the child elements from the iframe's body to conserver memory while (body.firstChild) { body.removeChild(body.firstChild); } } } } }, stop: function (connection) { var cw = null; // Stop attempting to prevent loading icon loadPreventer.cancel(); if (connection.frame) { if (connection.frame.stop) { connection.frame.stop(); } else { try { cw = connection.frame.contentWindow || connection.frame.contentDocument; if (cw.document && cw.document.execCommand) { cw.document.execCommand("Stop"); } } catch (e) { connection.log("Error occurred when stopping foreverFrame transport. Message = " + e.message + "."); } } // Ensure the iframe is where we left it if (connection.frame.parentNode === window.document.body) { window.document.body.removeChild(connection.frame); } delete transportLogic.foreverFrame.connections[connection.frameId]; connection.frame = null; connection.frameId = null; delete connection.frame; delete connection.frameId; delete connection.onSuccess; delete connection.frameMessageCount; connection.log("Stopping forever frame."); } }, abort: function (connection, async) { transportLogic.ajaxAbort(connection, async); }, getConnection: function (id) { return transportLogic.foreverFrame.connections[id]; }, started: function (connection) { if (changeState(connection, signalR.connectionState.reconnecting, signalR.connectionState.connected) === true) { $(connection).triggerHandler(events.onReconnect); } } }; }(window.jQuery, window)); /* jquery.signalR.transports.longPolling.js */ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. /*global window:false */ /// <reference path="jquery.signalR.transports.common.js" /> (function ($, window, undefined) { var signalR = $.signalR, events = $.signalR.events, changeState = $.signalR.changeState, isDisconnecting = $.signalR.isDisconnecting, transportLogic = signalR.transports._logic; signalR.transports.longPolling = { name: "longPolling", supportsKeepAlive: function () { return false; }, reconnectDelay: 3000, start: function (connection, onSuccess, onFailed) { /// <summary>Starts the long polling connection</summary> /// <param name="connection" type="signalR">The SignalR connection to start</param> var that = this, fireConnect = function () { fireConnect = $.noop; connection.log("LongPolling connected."); if (onSuccess) { onSuccess(); } else { connection.log("WARNING! The client received an init message after reconnecting."); } }, tryFailConnect = function (error) { if (onFailed(error)) { connection.log("LongPolling failed to connect."); return true; } return false; }, privateData = connection._, reconnectErrors = 0, fireReconnected = function (instance) { window.clearTimeout(privateData.reconnectTimeoutId); privateData.reconnectTimeoutId = null; if (changeState(instance, signalR.connectionState.reconnecting, signalR.connectionState.connected) === true) { // Successfully reconnected! instance.log("Raising the reconnect event"); $(instance).triggerHandler(events.onReconnect); } }, // 1 hour maxFireReconnectedTimeout = 3600000; if (connection.pollXhr) { connection.log("Polling xhr requests already exists, aborting."); connection.stop(); } connection.messageId = null; privateData.reconnectTimeoutId = null; privateData.pollTimeoutId = window.setTimeout(function () { (function poll(instance, raiseReconnect) { var messageId = instance.messageId, connect = (messageId === null), reconnecting = !connect, polling = !raiseReconnect, url = transportLogic.getUrl(instance, that.name, reconnecting, polling, true /* use Post for longPolling */), postData = {}; if (instance.messageId) { postData.messageId = instance.messageId; } if (instance.groupsToken) { postData.groupsToken = instance.groupsToken; } // If we've disconnected during the time we've tried to re-instantiate the poll then stop. if (isDisconnecting(instance) === true) { return; } connection.log("Opening long polling request to '" + url + "'."); instance.pollXhr = transportLogic.ajax(connection, { xhrFields: { onprogress: function () { transportLogic.markLastMessage(connection); } }, url: url, type: "POST", contentType: signalR._.defaultContentType, data: postData, timeout: connection._.pollTimeout, success: function (result) { var minData, delay = 0, data, shouldReconnect; connection.log("Long poll complete."); // Reset our reconnect errors so if we transition into a reconnecting state again we trigger // reconnected quickly reconnectErrors = 0; try { // Remove any keep-alives from the beginning of the result minData = connection._parseResponse(result); } catch (error) { transportLogic.handleParseFailure(instance, result, error, tryFailConnect, instance.pollXhr); return; } // If there's currently a timeout to trigger reconnect, fire it now before processing messages if (privateData.reconnectTimeoutId !== null) { fireReconnected(instance); } if (minData) { data = transportLogic.maximizePersistentResponse(minData); } transportLogic.processMessages(instance, minData, fireConnect); if (data && $.type(data.LongPollDelay) === "number") { delay = data.LongPollDelay; } if (isDisconnecting(instance) === true) { return; } shouldReconnect = data && data.ShouldReconnect; if (shouldReconnect) { // Transition into the reconnecting state // If this fails then that means that the user transitioned the connection into a invalid state in processMessages. if (!transportLogic.ensureReconnectingState(instance)) { return; } } // We never want to pass a raiseReconnect flag after a successful poll. This is handled via the error function if (delay > 0) { privateData.pollTimeoutId = window.setTimeout(function () { poll(instance, shouldReconnect); }, delay); } else { poll(instance, shouldReconnect); } }, error: function (data, textStatus) { var error = signalR._.transportError(signalR.resources.longPollFailed, connection.transport, data, instance.pollXhr); // Stop trying to trigger reconnect, connection is in an error state // If we're not in the reconnect state this will noop window.clearTimeout(privateData.reconnectTimeoutId); privateData.reconnectTimeoutId = null; if (textStatus === "abort") { connection.log("Aborted xhr request."); return; } if (!tryFailConnect(error)) { // Increment our reconnect errors, we assume all errors to be reconnect errors // In the case that it's our first error this will cause Reconnect to be fired // after 1 second due to reconnectErrors being = 1. reconnectErrors++; if (connection.state !== signalR.connectionState.reconnecting) { connection.log("An error occurred using longPolling. Status = " + textStatus + ". Response = " + data.responseText + "."); $(instance).triggerHandler(events.onError, [error]); } // We check the state here to verify that we're not in an invalid state prior to verifying Reconnect. // If we're not in connected or reconnecting then the next ensureReconnectingState check will fail and will return. // Therefore we don't want to change that failure code path. if ((connection.state === signalR.connectionState.connected || connection.state === signalR.connectionState.reconnecting) && !transportLogic.verifyLastActive(connection)) { return; } // Transition into the reconnecting state // If this fails then that means that the user transitioned the connection into the disconnected or connecting state within the above error handler trigger. if (!transportLogic.ensureReconnectingState(instance)) { return; } // Call poll with the raiseReconnect flag as true after the reconnect delay privateData.pollTimeoutId = window.setTimeout(function () { poll(instance, true); }, that.reconnectDelay); } } }); // This will only ever pass after an error has occurred via the poll ajax procedure. if (reconnecting && raiseReconnect === true) { // We wait to reconnect depending on how many times we've failed to reconnect. // This is essentially a heuristic that will exponentially increase in wait time before // triggering reconnected. This depends on the "error" handler of Poll to cancel this // timeout if it triggers before the Reconnected event fires. // The Math.min at the end is to ensure that the reconnect timeout does not overflow. privateData.reconnectTimeoutId = window.setTimeout(function () { fireReconnected(instance); }, Math.min(1000 * (Math.pow(2, reconnectErrors) - 1), maxFireReconnectedTimeout)); } }(connection)); }, 250); // Have to delay initial poll so Chrome doesn't show loader spinner in tab }, lostConnection: function (connection) { if (connection.pollXhr) { connection.pollXhr.abort("lostConnection"); } }, send: function (connection, data) { transportLogic.ajaxSend(connection, data); }, stop: function (connection) { /// <summary>Stops the long polling connection</summary> /// <param name="connection" type="signalR">The SignalR connection to stop</param> window.clearTimeout(connection._.pollTimeoutId); window.clearTimeout(connection._.reconnectTimeoutId); delete connection._.pollTimeoutId; delete connection._.reconnectTimeoutId; if (connection.pollXhr) { connection.pollXhr.abort(); connection.pollXhr = null; delete connection.pollXhr; } }, abort: function (connection, async) { transportLogic.ajaxAbort(connection, async); } }; }(window.jQuery, window)); /* jquery.signalR.hubs.js */ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. /*global window:false */ /// <reference path="jquery.signalR.core.js" /> (function ($, window, undefined) { var eventNamespace = ".hubProxy", signalR = $.signalR; function makeEventName(event) { return event + eventNamespace; } // Equivalent to Array.prototype.map function map(arr, fun, thisp) { var i, length = arr.length, result = []; for (i = 0; i < length; i += 1) { if (arr.hasOwnProperty(i)) { result[i] = fun.call(thisp, arr[i], i, arr); } } return result; } function getArgValue(a) { return $.isFunction(a) ? null : ($.type(a) === "undefined" ? null : a); } function hasMembers(obj) { for (var key in obj) { // If we have any properties in our callback map then we have callbacks and can exit the loop via return if (obj.hasOwnProperty(key)) { return true; } } return false; } function clearInvocationCallbacks(connection, error) { /// <param name="connection" type="hubConnection" /> var callbacks = connection._.invocationCallbacks, callback; if (hasMembers(callbacks)) { connection.log("Clearing hub invocation callbacks with error: " + error + "."); } // Reset the callback cache now as we have a local var referencing it connection._.invocationCallbackId = 0; delete connection._.invocationCallbacks; connection._.invocationCallbacks = {}; // Loop over the callbacks and invoke them. // We do this using a local var reference and *after* we've cleared the cache // so that if a fail callback itself tries to invoke another method we don't // end up with its callback in the list we're looping over. for (var callbackId in callbacks) { callback = callbacks[callbackId]; callback.method.call(callback.scope, { E: error }); } } // hubProxy function hubProxy(hubConnection, hubName) { /// <summary> /// Creates a new proxy object for the given hub connection that can be used to invoke /// methods on server hubs and handle client method invocation requests from the server. /// </summary> return new hubProxy.fn.init(hubConnection, hubName); } hubProxy.fn = hubProxy.prototype = { init: function (connection, hubName) { this.state = {}; this.connection = connection; this.hubName = hubName; this._ = { callbackMap: {} }; }, constructor: hubProxy, hasSubscriptions: function () { return hasMembers(this._.callbackMap); }, on: function (eventName, callback) { /// <summary>Wires up a callback to be invoked when a invocation request is received from the server hub.</summary> /// <param name="eventName" type="String">The name of the hub event to register the callback for.</param> /// <param name="callback" type="Function">The callback to be invoked.</param> var that = this, callbackMap = that._.callbackMap; // Normalize the event name to lowercase eventName = eventName.toLowerCase(); // If there is not an event registered for this callback yet we want to create its event space in the callback map. if (!callbackMap[eventName]) { callbackMap[eventName] = {}; } // Map the callback to our encompassed function callbackMap[eventName][callback] = function (e, data) { callback.apply(that, data); }; $(that).bind(makeEventName(eventName), callbackMap[eventName][callback]); return that; }, off: function (eventName, callback) { /// <summary>Removes the callback invocation request from the server hub for the given event name.</summary> /// <param name="eventName" type="String">The name of the hub event to unregister the callback for.</param> /// <param name="callback" type="Function">The callback to be invoked.</param> var that = this, callbackMap = that._.callbackMap, callbackSpace; // Normalize the event name to lowercase eventName = eventName.toLowerCase(); callbackSpace = callbackMap[eventName]; // Verify that there is an event space to unbind if (callbackSpace) { // Only unbind if there's an event bound with eventName and a callback with the specified callback if (callbackSpace[callback]) { $(that).unbind(makeEventName(eventName), callbackSpace[callback]); // Remove the callback from the callback map delete callbackSpace[callback]; // Check if there are any members left on the event, if not we need to destroy it. if (!hasMembers(callbackSpace)) { delete callbackMap[eventName]; } } else if (!callback) { // Check if we're removing the whole event and we didn't error because of an invalid callback $(that).unbind(makeEventName(eventName)); delete callbackMap[eventName]; } } return that; }, invoke: function (methodName) { /// <summary>Invokes a server hub method with the given arguments.</summary> /// <param name="methodName" type="String">The name of the server hub method.</param> var that = this, connection = that.connection, args = $.makeArray(arguments).slice(1), argValues = map(args, getArgValue), data = { H: that.hubName, M: methodName, A: argValues, I: connection._.invocationCallbackId }, d = $.Deferred(), callback = function (minResult) { var result = that._maximizeHubResponse(minResult), source, error; // Update the hub state $.extend(that.state, result.State); if (result.Progress) { if (d.notifyWith) { // Progress is only supported in jQuery 1.7+ d.notifyWith(that, [result.Progress.Data]); } else if(!connection._.progressjQueryVersionLogged) { connection.log("A hub method invocation progress update was received but the version of jQuery in use (" + $.prototype.jquery + ") does not support progress updates. Upgrade to jQuery 1.7+ to receive progress notifications."); connection._.progressjQueryVersionLogged = true; } } else if (result.Error) { // Server hub method threw an exception, log it & reject the deferred if (result.StackTrace) { connection.log(result.Error + "\n" + result.StackTrace + "."); } // result.ErrorData is only set if a HubException was thrown source = result.IsHubException ? "HubException" : "Exception"; error = signalR._.error(result.Error, source); error.data = result.ErrorData; connection.log(that.hubName + "." + methodName + " failed to execute. Error: " + error.message); d.rejectWith(that, [error]); } else { // Server invocation succeeded, resolve the deferred connection.log("Invoked " + that.hubName + "." + methodName); d.resolveWith(that, [result.Result]); } }; connection._.invocationCallbacks[connection._.invocationCallbackId.toString()] = { scope: that, method: callback }; connection._.invocationCallbackId += 1; if (!$.isEmptyObject(that.state)) { data.S = that.state; } connection.log("Invoking " + that.hubName + "." + methodName); connection.send(data); return d.promise(); }, _maximizeHubResponse: function (minHubResponse) { return { State: minHubResponse.S, Result: minHubResponse.R, Progress: minHubResponse.P ? { Id: minHubResponse.P.I, Data: minHubResponse.P.D } : null, Id: minHubResponse.I, IsHubException: minHubResponse.H, Error: minHubResponse.E, StackTrace: minHubResponse.T, ErrorData: minHubResponse.D }; } }; hubProxy.fn.init.prototype = hubProxy.fn; // hubConnection function hubConnection(url, options) { /// <summary>Creates a new hub connection.</summary> /// <param name="url" type="String">[Optional] The hub route url, defaults to "/signalr".</param> /// <param name="options" type="Object">[Optional] Settings to use when creating the hubConnection.</param> var settings = { qs: null, logging: false, useDefaultPath: true }; $.extend(settings, options); if (!url || settings.useDefaultPath) { url = (url || "") + "/signalr"; } return new hubConnection.fn.init(url, settings); } hubConnection.fn = hubConnection.prototype = $.connection(); hubConnection.fn.init = function (url, options) { var settings = { qs: null, logging: false, useDefaultPath: true }, connection = this; $.extend(settings, options); // Call the base constructor $.signalR.fn.init.call(connection, url, settings.qs, settings.logging); // Object to store hub proxies for this connection connection.proxies = {}; connection._.invocationCallbackId = 0; connection._.invocationCallbacks = {}; // Wire up the received handler connection.received(function (minData) { var data, proxy, dataCallbackId, callback, hubName, eventName; if (!minData) { return; } // We have to handle progress updates first in order to ensure old clients that receive // progress updates enter the return value branch and then no-op when they can't find // the callback in the map (because the minData.I value will not be a valid callback ID) if (typeof (minData.P) !== "undefined") { // Process progress notification dataCallbackId = minData.P.I.toString(); callback = connection._.invocationCallbacks[dataCallbackId]; if (callback) { callback.method.call(callback.scope, minData); } } else if (typeof (minData.I) !== "undefined") { // We received the return value from a server method invocation, look up callback by id and call it dataCallbackId = minData.I.toString(); callback = connection._.invocationCallbacks[dataCallbackId]; if (callback) { // Delete the callback from the proxy connection._.invocationCallbacks[dataCallbackId] = null; delete connection._.invocationCallbacks[dataCallbackId]; // Invoke the callback callback.method.call(callback.scope, minData); } } else { data = this._maximizeClientHubInvocation(minData); // We received a client invocation request, i.e. broadcast from server hub connection.log("Triggering client hub event '" + data.Method + "' on hub '" + data.Hub + "'."); // Normalize the names to lowercase hubName = data.Hub.toLowerCase(); eventName = data.Method.toLowerCase(); // Trigger the local invocation event proxy = this.proxies[hubName]; // Update the hub state $.extend(proxy.state, data.State); $(proxy).triggerHandler(makeEventName(eventName), [data.Args]); } }); connection.error(function (errData, origData) { var callbackId, callback; if (!origData) { // No original data passed so this is not a send error return; } callbackId = origData.I; callback = connection._.invocationCallbacks[callbackId]; // Verify that there is a callback bound (could have been cleared) if (callback) { // Delete the callback connection._.invocationCallbacks[callbackId] = null; delete connection._.invocationCallbacks[callbackId]; // Invoke the callback with an error to reject the promise callback.method.call(callback.scope, { E: errData }); } }); connection.reconnecting(function () { if (connection.transport && connection.transport.name === "webSockets") { clearInvocationCallbacks(connection, "Connection started reconnecting before invocation result was received."); } }); connection.disconnected(function () { clearInvocationCallbacks(connection, "Connection was disconnected before invocation result was received."); }); }; hubConnection.fn._maximizeClientHubInvocation = function (minClientHubInvocation) { return { Hub: minClientHubInvocation.H, Method: minClientHubInvocation.M, Args: minClientHubInvocation.A, State: minClientHubInvocation.S }; }; hubConnection.fn._registerSubscribedHubs = function () { /// <summary> /// Sets the starting event to loop through the known hubs and register any new hubs /// that have been added to the proxy. /// </summary> var connection = this; if (!connection._subscribedToHubs) { connection._subscribedToHubs = true; connection.starting(function () { // Set the connection's data object with all the hub proxies with active subscriptions. // These proxies will receive notifications from the server. var subscribedHubs = []; $.each(connection.proxies, function (key) { if (this.hasSubscriptions()) { subscribedHubs.push({ name: key }); connection.log("Client subscribed to hub '" + key + "'."); } }); if (subscribedHubs.length === 0) { connection.log("No hubs have been subscribed to. The client will not receive data from hubs. To fix, declare at least one client side function prior to connection start for each hub you wish to subscribe to."); } connection.data = connection.json.stringify(subscribedHubs); }); } }; hubConnection.fn.createHubProxy = function (hubName) { /// <summary> /// Creates a new proxy object for the given hub connection that can be used to invoke /// methods on server hubs and handle client method invocation requests from the server. /// </summary> /// <param name="hubName" type="String"> /// The name of the hub on the server to create the proxy for. /// </param> // Normalize the name to lowercase hubName = hubName.toLowerCase(); var proxy = this.proxies[hubName]; if (!proxy) { proxy = hubProxy(this, hubName); this.proxies[hubName] = proxy; } this._registerSubscribedHubs(); return proxy; }; hubConnection.fn.init.prototype = hubConnection.fn; $.hubConnection = hubConnection; }(window.jQuery, window)); /* jquery.signalR.version.js */ // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. /*global window:false */ /// <reference path="jquery.signalR.core.js" /> (function ($, undefined) { $.signalR.version = "2.2.1"; }(window.jQuery)); /*! * ASP.NET SignalR JavaScript Library v2.2.0 * http://signalr.net/ * * Copyright Microsoft Open Technologies, Inc. All rights reserved. * Licensed under the Apache 2.0 * https://github.com/SignalR/SignalR/blob/master/LICENSE.md * */ /// <reference path="..\..\SignalR.Client.JS\Scripts\jquery-1.6.4.js" /> /// <reference path="jquery.signalR.js" /> (function ($, window, undefined) { /// <param name="$" type="jQuery" /> "use strict"; if (typeof ($.signalR) !== "function") { throw new Error("SignalR: SignalR is not loaded. Please ensure jquery.signalR-x.js is referenced before ~/signalr/js."); } var signalR = $.signalR; function makeProxyCallback(hub, callback) { return function () { // Call the client hub method callback.apply(hub, $.makeArray(arguments)); }; } function registerHubProxies(instance, shouldSubscribe) { var key, hub, memberKey, memberValue, subscriptionMethod; for (key in instance) { if (instance.hasOwnProperty(key)) { hub = instance[key]; if (!(hub.hubName)) { // Not a client hub continue; } if (shouldSubscribe) { // We want to subscribe to the hub events subscriptionMethod = hub.on; } else { // We want to unsubscribe from the hub events subscriptionMethod = hub.off; } // Loop through all members on the hub and find client hub functions to subscribe/unsubscribe for (memberKey in hub.client) { if (hub.client.hasOwnProperty(memberKey)) { memberValue = hub.client[memberKey]; if (!$.isFunction(memberValue)) { // Not a client hub function continue; } subscriptionMethod.call(hub, memberKey, makeProxyCallback(hub, memberValue)); } } } } } $.hubConnection.prototype.createHubProxies = function () { var proxies = {}; this.starting(function () { // Register the hub proxies as subscribed // (instance, shouldSubscribe) registerHubProxies(proxies, true); this._registerSubscribedHubs(); }).disconnected(function () { // Unsubscribe all hub proxies when we "disconnect". This is to ensure that we do not re-add functional call backs. // (instance, shouldSubscribe) registerHubProxies(proxies, false); }); proxies['transvaultHub'] = this.createHubProxy('transvaultHub'); proxies['transvaultHub'].client = { }; proxies['transvaultHub'].server = { cancelTransaction: function (apiKey, correlationId) { return proxies['transvaultHub'].invoke.apply(proxies['transvaultHub'], $.merge(["CancelTransaction"], $.makeArray(arguments))); }, registerClientWithApiKey: function (apiKey) { return proxies['transvaultHub'].invoke.apply(proxies['transvaultHub'], $.merge(["RegisterClientWithApiKey"], $.makeArray(arguments))); } }; return proxies; }; signalR.hub = $.hubConnection("/hp/v3/adapters/transvault", { useDefaultPath: false }); $.extend(signalR, signalR.hub.createHubProxies()); }(window.jQuery, window)); (function() { "use strict"; /* * setup patterns */ var patterns = {}; patterns.isNumber = "[0-9]+"; patterns.isNotEmpty = "\S+"; patterns.isEmail = ".+\@.+\..+"; /* * setup urls */ var shouldMatch = function(value, regex, message) { if (typeof value === "undefined") { throw new TypeError("Property cannot be undefined."); } value = value + ""; var pattern = new RegExp(regex); if (!pattern.test(value)) { throw new Error(message); } }; /* * findElement */ var findCount = 0; var findDeferred = jQuery.Deferred(); var findElement = function(id) { if (id.nodeType) { findDeferred.resolve(id); return findDeferred; } if (!!document.getElementById(id)) { findDeferred.resolve(document.getElementById(id)); return findDeferred; } setTimeout(function() { if (findCount < 25) { findCount++; findElement(id); } else { findDeferred.reject(); } }, 25); return findDeferred; }; /* * Query help */ var toQueryString = function(obj) { var parts = [], url = ""; for (var i in obj) { if (obj.hasOwnProperty(i)) { parts.push(encodeURIComponent(i) + "=" + encodeURIComponent(obj[i])); } } url = "&" + parts.join("&"); return url; }; /* * Export "hp" */ window.hp = {}; /* * hp Types */ hp.types = {}; hp.types.Event = "Event"; hp.types.Product = "Product"; hp.types.Adapter = "Adapter"; /* * hp Models */ hp.models = {}; hp.models.Item = function(label, price) { this.label = label; this.price = parseFloat(price, 2); }; /* * Options * @param: merchantClientId * @param: merchantPrimaryEmail * @param: merchantSecondaryEmail * @param: showMemoField * @param: merchantGoogleAnalytics * @param: customOrderId * @param: customFormName */ hp.models.Options = function(merchantClientId, merchantPrimaryEmail, merchantSecondaryEmail, showMemoField, merchantGoogleAnalytics, customOrderId, customFormName, customSubjectLine) { this.name = customFormName || "Checkout"; this.CID = merchantClientId; this.email = merchantPrimaryEmail; shouldMatch(this.CID, patterns.isNumber, "Client ID should be digits only."); shouldMatch(this.email, patterns.isEmail, "Primary email should be a valid email address."); if (typeof merchantGoogleAnalytics !== "undefined") { this.ga = merchantGoogleAnalytics; } if (typeof customSubjectLine !== "undefined") { this.subject = customSubjectLine; } if (typeof merchantSecondaryEmail !== "undefined") { this.repoEmail = merchantSecondaryEmail; shouldMatch(this.repoEmail, patterns.isEmail, "Secondary email should be a valid email address."); } if (typeof showMemoField !== "undefined") { this.showMemoField = showMemoField.toString().toLowerCase() === "true" ? "True" : "False"; } if (typeof customOrderId !== "undefined") { this.orderId = customOrderId; shouldMatch(this.orderId, patterns.isNumber, "Customer order Id must be a valid number."); } }; /* * Setup * @param: type * @param: model */ hp.Setup = function(type, options) { if (!(type in hp.types)) { throw new Error("Please specify type. 'hp.Types.Event' or 'hp.Types.Product'"); } this.type = type; this.options = options; this.hasItems = false; this.items = { priceLabels: "", price: "" }; }; /* * addItem (prototype) * @param: item */ hp.Setup.prototype.addItem = function(item) { this.items.priceLabels += (this.items.price === "" ? "" : ",") + item.label; this.items.price += (this.items.price === "" ? "" : ",") + item.price; this.hasItems = true; return this; }; /* * createForm (prototype) * @param: containerElementId */ hp.Setup.prototype.createForm = function(containerElementId, baseUrl) { var deferred = jQuery.Deferred(); var iframe = document.createElement("iframe"); var href = document.createElement("a"); href.href = baseUrl; iframe.setAttribute("seamless", "seamless"); iframe.setAttribute("marginheight", "0"); iframe.setAttribute("marginwidth", "0"); iframe.setAttribute("frameborder", "0"); iframe.setAttribute("horizontalscrolling", "no"); iframe.setAttribute("verticalscrolling", "no"); iframe.style.overflowY = "hidden"; iframe.style.border = "none"; iframe.width = "640"; iframe.className = "inactive"; iframe.style.opacity = "0"; iframe.style.transition = "all 450ms 25ms cubic-bezier(0.175, 0.885, 0.320, 1)"; iframe.style.webkitTransition = "all 450ms 25ms cubic-bezier(0.175, 0.885, 0.320, 1)"; iframe.style.mozTransition = "all 450ms 25ms cubic-bezier(0.175, 0.885, 0.320, 1)"; iframe.style.msTransition = "all 450ms 25ms cubic-bezier(0.175, 0.885, 0.320, 1)"; iframe.style.oTransition = "all 450ms 25ms cubic-bezier(0.175, 0.885, 0.320, 1)"; var url = href.protocol + "//" + href.host; if (this.type == hp.types.Event) { url = url + "/hp/v1/event"; iframe.height = "1311"; } if (this.type == hp.types.Product) { url = url + "/hp/v1/item"; iframe.height = "1220"; } url = url + "?" + toQueryString(this.options); if (!this.hasItems) { url = url + "&price=0"; } else { url = url + toQueryString(this.items); } iframe.src = url .replace("item?&", "item?") .replace("event?&", "event?") .toString(); iframe.onload = function() { deferred.resolve(iframe); iframe.className = "active"; iframe.style.opacity = "1"; }; findElement(containerElementId).then(function(element) { element.appendChild(iframe); }); return deferred; }; $(function(){ $("[data-inventory], [data-event]").hp(); }); })(); (function($, window, document, undefined) { "use strict"; if (!Array.prototype.map) { Array.prototype.map = function(callback, thisArg) { var T, A, k; if (this === null) { throw new TypeError(' this is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== 'function') { throw new TypeError(callback + ' is not a function'); } if (arguments.length > 1) { T = thisArg; } A = new Array(len); k = 0; while (k < len) { var kValue, mappedValue; if (k in O) { kValue = O[k]; mappedValue = callback.call(T, kValue, k, O); A[k] = mappedValue; } k++; } return A; }; } if (!Function.prototype.clone) { Function.prototype.clone = function() { var cloneObj = this; if (this.__isClone) { cloneObj = this.__clonedFrom; } var temp = function() { return cloneObj.apply(this, arguments); }; for (var key in this) { temp[key] = this[key]; } temp.__isClone = true; temp.__clonedFrom = cloneObj; return temp; }; } if (!String.prototype.startsWith) { String.prototype.startsWith = function(searchString, position) { position = position || 0; return this.indexOf(searchString, position) === position; }; } if (!String.prototype.includes) { String.prototype.includes = function() { return String.prototype.indexOf.apply(this, arguments) !== -1; }; } if (!Date.prototype.toISOString) { var pad = function(number) { var r = String(number); if (r.length === 1) { r = '0' + r; } return r; }; Date.prototype.toISOString = function() { return this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1) + '-' + pad(this.getUTCDate()) + 'T' + pad(this.getUTCHours()) + ':' + pad(this.getUTCMinutes()) + ':' + pad(this.getUTCSeconds()) + '.' + String((this.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5) + 'Z'; }; } if (!window.Base64) { var Base64 = { // private property _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", // public method for encoding encode: function(input) { var output = ""; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; var i = 0; input = Base64._utf8_encode(input); while (i < input.length) { chr1 = input.charCodeAt(i++); chr2 = input.charCodeAt(i++); chr3 = input.charCodeAt(i++); enc1 = chr1 >> 2; enc2 = ((chr1 & 3) << 4) | (chr2 >> 4); enc3 = ((chr2 & 15) << 2) | (chr3 >> 6); enc4 = chr3 & 63; if (isNaN(chr2)) { enc3 = enc4 = 64; } else if (isNaN(chr3)) { enc4 = 64; } output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4); } return output; }, // public method for decoding decode: function(input) { var output = ""; var chr1, chr2, chr3; var enc1, enc2, enc3, enc4; var i = 0; input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); while (i < input.length) { enc1 = this._keyStr.indexOf(input.charAt(i++)); enc2 = this._keyStr.indexOf(input.charAt(i++)); enc3 = this._keyStr.indexOf(input.charAt(i++)); enc4 = this._keyStr.indexOf(input.charAt(i++)); chr1 = (enc1 << 2) | (enc2 >> 4); chr2 = ((enc2 & 15) << 4) | (enc3 >> 2); chr3 = ((enc3 & 3) << 6) | enc4; output = output + String.fromCharCode(chr1); if (enc3 != 64) { output = output + String.fromCharCode(chr2); } if (enc4 != 64) { output = output + String.fromCharCode(chr3); } } output = Base64._utf8_decode(output); return output; }, // private method for UTF-8 encoding _utf8_encode: function(string) { string = string.replace(/\r\n/g, "\n"); var utftext = ""; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if ((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; }, // private method for UTF-8 decoding _utf8_decode: function(utftext) { var string = ""; var i = 0; var c = c1; var c1 = c2; var c2 = 0; while (i < utftext.length) { c = utftext.charCodeAt(i); if (c < 128) { string += String.fromCharCode(c); i++; } else if ((c > 191) && (c < 224)) { c2 = utftext.charCodeAt(i + 1); string += String.fromCharCode(((c & 31) << 6) | (c2 & 63)); i += 2; } else { c2 = utftext.charCodeAt(i + 1); c3 = utftext.charCodeAt(i + 2); string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63)); i += 3; } } return string; } }; } if (!window.sessionStorage) { window.sessionStorage = { length: 0, setItem: function(key, value) { document.cookie = key + '=' + value + '; path=/'; this.length++; }, getItem: function(key) { var keyEQ = key + '='; var ca = document.cookie.split(';'); for (var i = 0, len = ca.length; i < len; i++) { var c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); if (c.indexOf(keyEQ) === 0) return c.substring(keyEQ.length, c.length); } return null; }, removeItem: function(key) { this.setItem(key, '', -1); this.length--; }, clear: function() { // Caution: will clear all persistent cookies as well var ca = document.cookie.split(';'); for (var i = 0, len = ca.length; i < len; i++) { var c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); var key = c.substring(0, c.indexOf('=')); this.removeItem(key); } this.length = 0; }, key: function(n) { var ca = document.cookie.split(';'); if (n >= ca.length || isNaN(parseFloat(n)) || !isFinite(n)) return null; var c = ca[n]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); return c.substring(0, c.indexOf('=')); } }; } /* * Export "hp" */ window.hp = hp || {}; window.hp.Utils = hp.Utils || {}; // exposes defaults hp.Utils.defaults = {}; // exposes plugins hp.Utils.plugins = {}; // payment service type hp.PaymentService = {}; hp.PaymentService.EFT = "EFT"; hp.PaymentService.EMONEY = "EMONEY"; hp.PaymentService.TEST = "TEST"; // entry type hp.EntryType = {}; hp.EntryType.DEVICE_CAPTURED = "DEVICE_CAPTURED"; hp.EntryType.KEYED_CARD_PRESENT = "KEYED_CARD_PRESENT"; hp.EntryType.KEYED_CARD_NOT_PRESENT = "KEYED_CARD_NOT_PRESENT"; // entry type hp.PaymentType = {}; hp.PaymentType.CHARGE = "CHARGE"; hp.PaymentType.REFUND = "REFUND"; hp.PaymentType.CREATE_INSTRUMENT = "CREATE_INSTRUMENT"; hp.PaymentType.CANCEL = "CANCEL"; hp.PaymentType.ISSUE = "ISSUE"; hp.PaymentType.ADD_FUNDS = "ADD_FUNDS"; // exposes payments (for split payment methods) hp.Utils.payments = []; // expose inital boolean for embeded instrument hp.Utils.hasPaymentInstrument = false; // A variety of CSS based identifiers var handleLegacyCssClassApplication = function(classPrefix, $form) { var activeClass = "hp-content-active", currentClass = "hp-form-" + classPrefix, $hp = $form.find(".hp"); var $parent = $hp .removeClass("hp-form-emoney hp-form-transvault hp-form-bank hp-form-code hp-form-cc hp-form-gc hp-form-success hp-form-error") .addClass("hp hp-form") .addClass(currentClass); $parent.find(".hp-content").removeClass(activeClass); var $content = $parent.find(".hp-content-" + classPrefix).addClass(activeClass); setTimeout(function() { $form .find(".hp") .addClass("hp-active"); }, 0); return { parent: $parent, content: $content }; }; var setPaymentService = function(serivceType) { var result = hp.PaymentService.EFT; serivceType = serivceType.toString().toLowerCase().replace(/_/gi, ""); switch (serivceType) { case "emoney": result = hp.PaymentService.EMONEY; break; case "eft": result = hp.PaymentService.EFT; break; case "test": result = hp.PaymentService.TEST; break; default: result = hp.PaymentService.EFT; } hp.Utils.defaults.paymentService = result; log("Payment service: " + result); return result; }; var setEntryType = function(entryType) { var result = hp.EntryType.KEYED_CARD_NOT_PRESENT; entryType = entryType.toString().toLowerCase().replace(/_/gi, ""); switch (entryType) { case "devicecaptured": result = hp.EntryType.DEVICE_CAPTURED; break; case "keyedcardpresent": result = hp.EntryType.KEYED_CARD_PRESENT; break; case "keyedcardnotpresent": result = hp.EntryType.KEYED_CARD_NOT_PRESENT; break; default: result = hp.EntryType.KEYED_CARD_NOT_PRESENT; } hp.Utils.defaults.entryType = result; log("Entry type: " + result); return result; }; var setPaymentType = function(paymentType) { var result = hp.PaymentType.CHARGE; paymentType = paymentType.toString().toLowerCase().replace(/_/gi, ""); switch (paymentType) { case "charge": result = hp.PaymentType.CHARGE; break; case "refund": result = hp.PaymentType.REFUND; break; case "createinstrument": result = hp.PaymentType.CREATE_INSTRUMENT; break; default: result = hp.PaymentType.CHARGE; } hp.Utils.defaults.paymentType = result; log("Payment type: " + result); return result; }; var log = function() { var console = window.console; if (console && console.log && console.log.apply) { var args = Array.prototype.slice.call(arguments); var prep = "Hosted Payments v3 (debug): "; for (var i = 0; i < args.length; i++) { var val = args[i]; if (typeof val === "string") { if (i > 0) { prep = ""; } args[i] = prep + val; } } console.log.apply(console, args); return; } }; var getVersion = function() { return hp.Utils.defaults.version; }; var setVersion = function(version) { hp.Utils.defaults.version = version; }; var setPaymentInstrument = function() { if (typeof hp.Utils.defaults.instrumentId !== "undefined" && hp.Utils.defaults.instrumentId !== "") { hp.Utils.hasPaymentInstrument = true; return; } hp.Utils.hasPaymentInstrument = false; }; var generateGuild = function() { var d = null; if (window.performance && window.performance.now) { d = window.performance.now(); } else if (Date.now) { d = Date.now(); } else { d = new Date().getTime(); } var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16); }); return uuid; }; var updateAvsInfo = function(avsStreet, avsZip) { if (typeof avsZip === "undefined") { avsZip = ""; } if (typeof avsStreet === "undefined") { avsStreet = ""; } hp.Utils.defaults.billingAddress.addressLine1 = avsStreet; hp.Utils.defaults.billingAddress.postalCode = avsZip; }; var showLoader = function() { if ($(".hp-error-container").is(":visible")) { hideError(); } $(".hp-loading-container").addClass("hp-loading-container-active"); }; var hideLoader = function() { $(".hp-loading-container").removeClass("hp-loading-container-active"); }; var showError = function(message) { if ($(".hp-loading-container").is(":visible")) { hideLoader(); } $(".hp-error-container").addClass("hp-error-container-active"); var $message = $(".hp-error-container .hp-error-message"), isArray = typeof message !== "undefined" && typeof message.push !== "undefined", list = "<p>Please review the following errors: </p><ul class=\"hp-error-message-list\">{{errors}}</ul>"; if (isArray) { var errors = ""; for (var i = 0; i < message.length; i++) { errors += "<li>" + message[i] + "</li>"; } list = list.replace("{{errors}}", errors); $message.html(list); } else { $message.text(message); } $(".hp-error-container .hp-error-disclaimer a").on("click", hideError); hp.Utils.log("Sign In: Session cleared."); sessionStorage.clear(); }; var hideError = function() { $(".hp-error-container").removeClass("hp-error-container-active"); $(".hp-error-container .hp-error-disclaimer a").off("click"); hp.Utils.defaults.onErrorDismissCallback(); hp.Utils.reset(); }; // sets up iframe DOM var createInstance = function($element, callback) { // Create wrapping HTML var $wrapper = [ '<div class="hp hp-form">', '<div class="hp-loading-container">', '<span class="hp-loading-text">Loading</span>', '<div class="hp-loading"><span></span><span></span><span></span><span></span></div>', '</div>', '<div class="hp-error-container">', '<span class="hp-error-text">{{error}} </span>', '<div class="hp-error-message"></div>', '<hr />', '<div class="hp-error-disclaimer">If you feel that the above error was made by a mistake please contact our support at {{phone}}. <br /><br /><a href="javascript:;">&times; Dismiss error</a></div>', '</div>', '<div class="hp-row">', '<div class="hp-col hp-col-left">', '<ul class="hp-nav">', '{{nav}}', '</ul>', '<div class="hp-secure">', '<div class="hp-support">', '<strong>Help &amp; support</strong>', '<p>Having issues with your payments? Call us at <a href="tel:{{phone}}">{{phone}}</a>.</p>', '<br />', '</div>', '<div class="hp-cards">', '<img class="hp-cards-icons" src="https://cdn.rawgit.com/etsms/payment-icons/master/svg/flat/amex.svg" alt="AMEX" />', '<img class="hp-cards-icons" src="https://cdn.rawgit.com/etsms/payment-icons/master/svg/flat/diners.svg" alt="Diners" />', '<img class="hp-cards-icons" src="https://cdn.rawgit.com/etsms/payment-icons/master/svg/flat/discover.svg" alt="Discover" />', '<img class="hp-cards-icons" src="https://cdn.rawgit.com/etsms/payment-icons/master/svg/flat/jcb.svg" alt="JCB" />', '<img class="hp-cards-icons" src="https://cdn.rawgit.com/etsms/payment-icons/master/svg/flat/mastercard.svg" alt="Master Card" />', '<img class="hp-cards-icons" src="https://cdn.rawgit.com/etsms/payment-icons/master/svg/flat/visa.svg" alt="VISA" />', '<img class="hp-cards-icons" src="https://cdn.rawgit.com/etsms/c2568c3f7343be79032ac7a717fa80de/raw/7923fdf2aacffbc6baf62454cc4213b46b943596/emoney-card-icon.svg" alt="EMoney" />', '<img class="hp-cards-icons" src="https://cdn.rawgit.com/etsms/cd2abb29142a84bb16fbeb3d07a7aefa/raw/a17760bdd23cf1d90c22c8a2235f8d6e6753663e/gift-card-icon.svg" alt="Gift Cards" />', '</div>', '<a class="hp-secure-icon" href="https://www.etsms.com/" target="_blank" title="ETS - Electronic Transaction Systems">', '<img src="https://cdn.rawgit.com/etsms/a5b6be8ebd898748ec829538bd4b603e/raw/9691ef92d11b5a1608a73f5f46c427c4c494d0b9/secure-icon.svg" alt="Secured by ETS" />', '<span>Secured by <br />ETS Corporation</span>', '</a>', '<div class="hp-secure-bottom">', '<div class="hp-secure-bottom-left">', '<span class="' + (hp.Utils.getAmount() === 0 || hp.Utils.defaults.ignoreSubmission === true ? "hide " : "") + (hp.Utils.defaults.paymentType === hp.PaymentType.REFUND ? "hp-version-refund" : "hp-version-charge") + '">' + (hp.Utils.defaults.paymentType === hp.PaymentType.REFUND ? "Refund" : "Charge") + ': <span class="hp-version-amount">' + hp.Utils.formatCurrency(hp.Utils.getAmount()) + '</span></span><br />', '</div>', '<div class="hp-secure-bottom-right">', hp.Utils.getVersion(), '</div>', '</div>', '</div>', '</div>', '<div class="hp-col hp-col-right">', '{{order}}', '<div class="hp-content hp-content-success">{{success}}</div>', '</div>', '</div>', '</div>' ].join(""); hp.Utils.plugins.CreditCard = new hp.CreditCard($element); hp.Utils.plugins.BankAccount = new hp.BankAccount($element); hp.Utils.plugins.Code = new hp.Code($element); hp.Utils.plugins.Success = new hp.Success($element); hp.Utils.plugins.Transvault = new hp.Transvault($element); hp.Utils.plugins.GiftCard = new hp.GiftCard($element); $element.html( $wrapper .replace("{{success}}", hp.Utils.plugins.Success .createTemplate() .replace("{{redirectLabel}}", hp.Utils.defaults.defaultRedirectLabel) .replace("{{successLabel}}", hp.Utils.defaults.defaultSuccessLabel) ) .replace(/{{phone}}/gi, hp.Utils.defaults.defaultPhone) .replace("{{error}}", hp.Utils.defaults.defaultErrorLabel) .replace("{{order}}", hp.Utils.createOrder()) .replace("{{nav}}", hp.Utils.createNav()) ); var $parent = $element.find(".hp"), $types = $parent.find(".hp-type"), activeClass = "hp-active"; if (!$parent.length) { throw new Error("hosted-payments.js : Could not locate template."); } if (!$types.length) { throw new Error("hosted-payments.js : Could not locate template."); } $types.off("click").on("click", function(e) { e.preventDefault(); var $this = $(this), currentIndex = $this.index(); $types .removeClass(activeClass) .eq(currentIndex) .addClass(activeClass); // Wait for DOM to finish loading before querying $(function() { if (!!$this.attr("class").match(/hp-cc/gi)) { callback(hp.Utils.plugins.CreditCard); } if (!!$this.attr("class").match(/hp-bank/gi)) { callback(hp.Utils.plugins.BankAccount); } if (!!$this.attr("class").match(/hp-emoney/gi)) { callback(hp.Utils.plugins.EMoney); } if (!!$this.attr("class").match(/hp-code/gi)) { // Takes focus off link so that a swipe may occur on the HP element $this.find("a").blur(); callback(hp.Utils.plugins.Code); } if (!!$this.attr("class").match(/hp-transvault/gi)) { callback(hp.Utils.plugins.Transvault); } if (!!$this.attr("class").match(/hp-gc/gi)) { callback(hp.Utils.plugins.GiftCard); } }); }).eq(0).trigger("click"); }; // success page var showSuccessPage = function(delay) { var deferred = jQuery.Deferred(), timeout = typeof delay === "undefined" ? 0 : delay; setTimeout(function() { hp.Utils.plugins.Success.init(); $(".hp-col-left .hp-type") .off("click") .removeClass("hp-active"); deferred.resolve(); }, timeout); return deferred; }; var setAmount = function(amount) { hp.Utils.defaults.amount = Math.abs(Math.round10(parseFloat(amount), -2)); $(".hp.hp-form .hp-version-amount").text(formatCurrency(hp.Utils.defaults.amount)); return hp.Utils.defaults.amount; }; var getAmount = function() { return hp.Utils.defaults.amount; }; var createNav = function() { var defaultAreas = hp.Utils.defaults.paymentTypeOrder, html = '', creditCard = '', bankAccount = '', code = '', transvault = '', giftcard = ''; if (defaultAreas.indexOf(0) >= 0) { creditCard = '<li class="hp-type hp-cc"><a href="javascript:void(0);"><img src="https://cdn.rawgit.com/etsms/9e2e4c55564ca8eba12f9fa3e7064299/raw/93965040e6e421e1851bfe7a15af92bdc722fa43/credt-card-icon.svg" alt="Credit Card" /> <span>Credit Card</span></a></li>'; } if (defaultAreas.indexOf(1) >= 0) { bankAccount = '<li class="hp-type hp-bank"><a href="javascript:void(0);"><img src="https://cdn.rawgit.com/etsms/af49afe3c1c1cb41cb3204a45492bd47/raw/78e935c7e5290923dba15e8b595aef7c95b2292e/ach-icon.svg" alt="ACH and Bank Account" /> <span>Bank (ACH)</span></a></li>'; } if (defaultAreas.indexOf(2) >= 0) { code = '<li class="hp-type hp-code"><a href="javascript:void(0);"><img src="https://cdn.rawgit.com/etsms/c70317acba59d3d5b60e5999d5feeab8/raw/764478d2660f97d002eb3bd3177b725a410f694d/swipe-icon.svg" alt="Swipe or Scan" /> <span>Swipe\\Scan</span></a></li>'; } if (defaultAreas.indexOf(3) >= 0) { transvault = '<li class="hp-type hp-transvault"><a href="javascript:void(0);"><img src="https://cdn.rawgit.com/etsms/5363122967f20bd31d6630529cb17c3f/raw/0a0ae6a30247ced8ed5c0c85f2b42072b59b8fba/transvault-icon.svg" alt="Hosted Transvault" /> <span>Transvault</span></a></li>'; } if (defaultAreas.indexOf(4) >= 0) { giftcard = '<li class="hp-type hp-gc"><a href="javascript:void(0);"><img src="https://cdn.rawgit.com/etsms/2e9f0f3bb754a7910ffbdbd16ea9926a/raw/27ce16494e375ff8d04deb918ffd76d743397488/gift-icon.svg" alt="Gift Card" /> <span>Gift Card</span></a></li>'; } for (var i = 0; i < defaultAreas.length; i++) { if (defaultAreas[i] === 0) { html += creditCard; } if (defaultAreas[i] === 1) { html += bankAccount; } if (defaultAreas[i] === 2) { html += code; } if (defaultAreas[i] === 3) { html += transvault; } if (defaultAreas[i] === 4) { html += giftcard; } } return html; }; var createOrder = function() { var defaultAreas = hp.Utils.defaults.paymentTypeOrder, html = '', creditCard = '', bankAccount = '', code = '', transvault = '', giftcard = ''; if (defaultAreas.indexOf(0) >= 0) { creditCard = '<div class="hp-content hp-content-cc">{{creditCard}}</div>'.replace("{{creditCard}}", hp.Utils.plugins.CreditCard.createTemplate(hp.Utils.defaults.defaultCardCharacters, hp.Utils.defaults.defaultNameOnCardName, hp.Utils.defaults.defaultDateCharacters)); } if (defaultAreas.indexOf(1) >= 0) { bankAccount = '<div class="hp-content hp-content-bank">{{bankAccount}}</div>'.replace("{{bankAccount}}", hp.Utils.plugins.BankAccount.createTemplate(hp.Utils.defaults.defaultName, hp.Utils.defaults.defaultAccountNumberCharacters, hp.Utils.defaults.defaultRoutingNumberCharacters)); } if (defaultAreas.indexOf(2) >= 0) { code = '<div class="hp-content hp-content-code">{{code}}</div>'.replace("{{code}}", hp.Utils.plugins.Code.createTemplate(hp.Utils.defaults.defaultCardCharacters, hp.Utils.defaults.defaultNameOnCardNameSwipe, hp.Utils.defaults.defaultDateCharacters)); } if (defaultAreas.indexOf(3) >= 0) { transvault = '<div class="hp-content hp-content-transvault">{{transvault}}</div>'.replace("{{transvault}}", hp.Utils.plugins.Transvault.createTemplate()); } if (defaultAreas.indexOf(4) >= 0) { giftcard = '<div class="hp-content hp-content-gc">{{giftcard}}</div>'.replace("{{giftcard}}", hp.Utils.plugins.GiftCard.createTemplate(hp.Utils.defaults.defaultCardCharacters, hp.Utils.defaults.defaultNameOnCardName, (+(new Date().getFullYear().toString().substring(2, 4)) + 3))); } for (var i = 0; i < defaultAreas.length; i++) { if (defaultAreas[i] === 0) { html += creditCard; } if (defaultAreas[i] === 1) { html += bankAccount; } if (defaultAreas[i] === 2) { html += code; } if (defaultAreas[i] === 3) { html += transvault; } if (defaultAreas[i] === 4) { html += giftcard; } } return html; }; var setIpAddress = function(ipAddress) { if (typeof ipAddress !== "undefined" && ipAddress !== null && ipAddress !== "") { hp.Utils.defaults.ipAddress = ipAddress; } }; var getIpAddress = function() { return hp.Utils.defaults.ipAddress + ""; }; var setSession = function(session, isApiKey) { var currentSession = getSession(); if (session.length <= 36 && !isApiKey) { currentSession.sessionToken = session; } if (isApiKey) { currentSession.apiKey = session; } hp.Utils.defaults.session = currentSession; }; var getSession = function() { var currentSession = {}; currentSession.sessionToken = ""; currentSession.apiKey = ""; currentSession.sessionToken = hp.Utils.defaults.session ? (hp.Utils.defaults.session.sessionToken ? hp.Utils.defaults.session.sessionToken : "") : ""; currentSession.apiKey = hp.Utils.defaults.session ? (hp.Utils.defaults.session.apiKey ? hp.Utils.defaults.session.apiKey : "") : ""; return currentSession; }; var buildSuccessResultObject = function() { return { "status": "Success", "amount": getAmount(), "message": "Transaction processed", "token": getSession().sessionToken, "transaction_id": "", "transaction_approval_code": "", "transaction_avs_street_passed": false, "transaction_avs_postal_code_passed": false, "transaction_currency": "USD$", "transaction_status_indicator": "", "transaction_type": hp.Utils.defaults.paymentType, "transaction_tax": 0, "transaction_surcharge": 0, "transaction_gratuity": 0, "transaction_cashback": 0, "transaction_total": getAmount(), "correlation_id": getCorrelationId(), "instrument_id": "", "instrument_type": "", "instrument_method": "Other", "instrument_last_four": "", "instrument_routing_last_four": "", "instrument_expiration_date": "", "instrument_verification_method": "", "instrument_entry_type": hp.Utils.defaults.entryType, "instrument_entry_type_description": "KEY_ENTRY", "instrument_verification_results": "", "created_on": (new Date()).toISOString(), "customer_name": "", "customer_signature": "https://images.pmoney.com/00000000", "anti_forgery_token": hp.Utils.defaults.antiForgeryToken, "application_identifier": "Hosted Payments", "application_response_code": "", "application_issuer_data": "" }; }; var buildResultObjectByType = function(response) { var deferred = jQuery.Deferred(); var isBankAccount = function(req) { var isBank = false; if (typeof req.properties !== "undefined" && typeof req.properties.accountNumber !== "undefined") { isBank = true; } return isBank; }; var isEMoney = function(req) { if (isBankAccount(req)) { return false; } if (typeof req.type !== "undefined" && ((req.type.toLowerCase() === "emoney") || (req.type.toLowerCase() === "creditcard") || (req.type.toLowerCase() === "ach"))) { return true; } return false; }; var isCreditCard = function(req) { if (isBankAccount(req)) { return false; } if (isEMoney(req)) { return false; } if (typeof req.properties !== "undefined" && typeof req.properties.cardNumber !== "undefined") { return true; } return false; }; var isTrackAccount = function(req) { if (isBankAccount(req)) { return false; } if (isEMoney(req)) { return false; } if (isCreditCard(req)) { return false; } if (typeof req.properties !== "undefined" && (typeof req.properties.trackOne !== "undefined" || typeof req.properties.trackTwo !== "undefined" || typeof req.properties.trackThree !== "undefined")) { return true; } return false; }; if (typeof response.splice === "function") { var responses = [], isCreateOnly = hp.Utils.getAmount() === 0; for (var i = 0; i < response.length; i++) { var res = response[i], createdOn = (new Date()).toISOString(), payment = res.request, message = "Transaction processed.", session = getSession(), lastFour = "", routingLastFour = "", name = "", type = "", expirationDate = "", isError = res.isException ? true : false, status = "Success", payload = payment.__request, swipe = payload ? payload.__swipe : undefined, isAch = isBankAccount(payload), isEm = isEMoney(payload), isCC = isCreditCard(payload), isTrack = isTrackAccount(payload), isScan = (typeof swipe !== "undefined"); // For BANK ACCOUNT objects if (isAch) { message = "Transaction pending."; lastFour = payload.properties.accountNumber.substr(payload.properties.accountNumber.length - 4) + ""; routingLastFour = payload.properties.routingNumber.substr(payload.properties.routingNumber.length - 4) + ""; name = payload.name; type = "ACH"; } // For WALLET objects if (isEm) { var reqType = payload.type.toLowerCase(); if (reqType === "ach") { name = payload.bankName; lastFour = payload.accountNumber.replace(/\*/gi, ""); } else if (reqType === "creditcard") { name = payload.nameOnCard; lastFour = payload.cardNumber.substr(payload.cardNumber.length - 4) + ""; expirationDate = payload.properties.expirationDate; } else { name = payload.email; lastFour = payload.cardNumber.substr(payload.cardNumber.length - 4) + ""; } type = "EMONEY"; } // For Credit Card requests if (isCC) { lastFour = payload.properties.cardNumber.substr(payload.properties.cardNumber.length - 4) + ""; name = payload.properties.nameOnCard; type = $.payment.cardType(payload.properties.cardNumber).toUpperCase(); expirationDate = payload.properties.expirationDate; } if (isError) { status = "Error"; } if (isScan) { lastFour = swipe.cardNumber.substr(swipe.cardNumber.length - 4); name = swipe.nameOnCard; type = $.payment.cardType(swipe.cardNumber).toUpperCase(); expirationDate = swipe.expMonth + "/" + swipe.expYear; } if (isCreateOnly) { message = "Payment instrumented created."; } else if (hp.Utils.defaults.PaymentType === hp.PaymentType.REFUND) { message = "Transaction refunded."; } var successResponse = buildSuccessResultObject(); successResponse.status = status; successResponse.amount = payment.amount; successResponse.message = (isError ? res.description : message); successResponse.transaction_id = res.transactionId; successResponse.transaction_total = payment.amount; successResponse.instrument_id = payment.instrumentId; successResponse.instrument_type = type; successResponse.instrument_last_four = lastFour; successResponse.instrument_routing_last_four = routingLastFour; successResponse.instrument_expiration_date = expirationDate; successResponse.instrument_entry_type_description = isTrack ? "MAGNETIC_SWIPE" : "KEY_ENTRY"; successResponse.customer_name = name; responses.push(successResponse); } if (isCreateOnly) { deferred.resolve(responses); } else { var responseCount = responses.length || 0, currentCount = 0; $.each(responses, function(index) { var statusRequest = { "status": { "statusRequest": { "token": hp.Utils.getSession().sessionToken, "transactionId": responses[index].transaction_id } } }; hp.Utils.makeRequest(statusRequest).then(function(statusResponse) { if (statusResponse.type === "Transaction" && typeof statusResponse.properties !== "undefined") { var isACH = statusResponse.properties.accountType === "BankAccount"; responses[currentCount].transaction_approval_code = isACH ? "" : statusResponse.properties.approvalCode; responses[currentCount].transaction_avs_postal_code_passed = isACH ? true : statusResponse.properties.postalCodeCheck; responses[currentCount].transaction_avs_street_passed = isACH ? true : statusResponse.properties.addressLine1Check; responses[currentCount].customer_signature = (statusResponse.properties.signatureRef === null || statusResponse.properties.signatureRef === undefined || statusResponse.properties.signatureRef === "") ? "https://images.pmoney.com/00000000" : statusResponse.properties.signatureRef; responses[currentCount].message = (responses[currentCount].message + " " + (statusResponse.properties.message + ".")).toLowerCase().replace(" .", ""); responses[currentCount].instrument_verification_results = isACH ? false : true; responses[currentCount].instrument_verification_method = isACH ? "" : "SIGNATURE"; responses[currentCount].instrument_method = (typeof statusResponse.properties.accountType !== "undefined") ? statusResponse.properties.accountType : "CreditCard"; } currentCount = currentCount + 1; if (currentCount === responseCount) { deferred.resolve(responses); } }); }); } } else { var newResponse = []; newResponse.push(response); return buildResultObjectByType(newResponse); } return deferred; }; var retrieveTransactionStatus = function(transactionId) { var deferred = jQuery.Deferred(); var successResponse = buildSuccessResultObject(); var statusRequest = { "status": { "statusRequest": { "token": getSession().sessionToken, "transactionId": transactionId } } }; hp.Utils.makeRequest(statusRequest).then(function(statusResponse) { if (statusResponse.type === "Transaction" && typeof statusResponse.properties !== "undefined") { var isACH = statusResponse.properties.accountType === "BankAccount"; successResponse.transaction_approval_code = isACH ? "" : statusResponse.properties.approvalCode; successResponse.transaction_avs_postal_code_passed = isACH ? true : statusResponse.properties.postalCodeCheck; successResponse.transaction_avs_street_passed = isACH ? true : statusResponse.properties.addressLine1Check; successResponse.customer_signature = (statusResponse.properties.signatureRef === null || statusResponse.properties.signatureRef === undefined || statusResponse.properties.signatureRef === "") ? "https://images.pmoney.com/00000000" : statusResponse.properties.signatureRef; successResponse.message = (successResponse.message + " " + (statusResponse.properties.message + ".")).toLowerCase().replace(" .", ""); successResponse.instrument_verification_results = isACH ? false : true; successResponse.instrument_verification_method = isACH ? "" : "SIGNATURE"; successResponse.instrument_method = (typeof statusResponse.properties.accountType !== "undefined") ? statusResponse.properties.accountType : "CreditCard"; successResponse.customer_name = statusResponse.properties.nameOnAccount; successResponse.instrument_id = statusResponse.properties.instrumentId; successResponse.instrument_last_four = statusResponse.properties.accountNumber; successResponse.instrument_type = statusResponse.properties.cardType; successResponse.transaction_id = transactionId; successResponse.transaction_avs_postal_code_passed = statusResponse.properties.postalCodeCheck; successResponse.transaction_avs_street_passed = statusResponse.properties.addressLine1Check; } deferred.resolve(successResponse); }, deferred.reject); return deferred; }; var requestTypes = {}; requestTypes.SIGN_IN = "signIn"; requestTypes.SIGN_IN_REQUEST = "signInRequest"; requestTypes.SIGN_IN_RESPONSE = "signInResponse"; requestTypes.CHARGE = "charge"; requestTypes.CHARGE_REQUEST = "chargeRequest"; requestTypes.CHARGE_RESPONSE = "chargeResponse"; requestTypes.REFUND = "refund"; requestTypes.REFUND_REQUEST = "refundRequest"; requestTypes.REFUND_RESPONSE = "refundResponse"; requestTypes.TRANSVAULT = "transvault"; requestTypes.TRANSVAULT_REQUEST = "transvaultRequest"; requestTypes.TRANSVAULT_RESPONSE = "transvaultResponse"; requestTypes.CREATE_PAYMENT_INSTRUMENT = "createPaymentInstrument"; requestTypes.CREATE_PAYMENT_INSTRUMENT_REQUEST = "createPaymentInstrumentRequest"; requestTypes.CREATE_PAYMENT_INSTRUMENT_RESPONSE = "createPaymentInstrumentResponse"; requestTypes.WALLET = "wallet"; requestTypes.WALLET_REQUEST = "walletRequest"; requestTypes.WALLET_RESPONSE = "walletResponse"; requestTypes.STATUS = "status"; requestTypes.STATUS_REQUEST = "statusRequest"; requestTypes.STATUS_RESPONSE = "statusResponse"; var getObjectResponseFromData = function(data) { var memberName = ""; var requestMemberName = ""; var responseMemberName = ""; var result = {}; var isResponse = false; if (requestTypes.SIGN_IN in data) { memberName = requestTypes.SIGN_IN; requestMemberName = requestTypes.SIGN_IN_REQUEST; responseMemberName = requestTypes.SIGN_IN_RESPONSE; } if (requestTypes.CHARGE in data) { memberName = requestTypes.CHARGE; requestMemberName = requestTypes.CHARGE_REQUEST; responseMemberName = requestTypes.CHARGE_RESPONSE; } if (requestTypes.REFUND in data) { memberName = requestTypes.REFUND; requestMemberName = requestTypes.REFUND_REQUEST; responseMemberName = requestTypes.REFUND_RESPONSE; } if (requestTypes.TRANSVAULT in data) { memberName = requestTypes.TRANSVAULT; requestMemberName = requestTypes.TRANSVAULT_REQUEST; responseMemberName = requestTypes.TRANSVAULT_RESPONSE; } if (requestTypes.CREATE_PAYMENT_INSTRUMENT in data) { memberName = requestTypes.CREATE_PAYMENT_INSTRUMENT; requestMemberName = requestTypes.CREATE_PAYMENT_INSTRUMENT_REQUEST; responseMemberName = requestTypes.CREATE_PAYMENT_INSTRUMENT_RESPONSE; } if (requestTypes.WALLET in data) { memberName = requestTypes.WALLET; requestMemberName = requestTypes.WALLET_REQUEST; responseMemberName = requestTypes.WALLET_RESPONSE; } if (requestTypes.STATUS in data) { memberName = requestTypes.STATUS; requestMemberName = requestTypes.STATUS_REQUEST; responseMemberName = requestTypes.STATUS_RESPONSE; } if (requestTypes.CHARGE_RESPONSE in data) { memberName = requestTypes.CHARGE_RESPONSE; isResponse = true; } if (requestTypes.REFUND_RESPONSE in data) { memberName = requestTypes.REFUND_RESPONSE; isResponse = true; } if (requestTypes.TRANSVAULT_RESPONSE in data) { memberName = requestTypes.TRANSVAULT_RESPONSE; isResponse = true; } if (requestTypes.SIGN_IN_RESPONSE in data) { memberName = requestTypes.SIGN_IN_RESPONSE; isResponse = true; } if (requestTypes.CREATE_PAYMENT_INSTRUMENT_RESPONSE in data) { memberName = requestTypes.CREATE_PAYMENT_INSTRUMENT_RESPONSE; isResponse = true; } if (requestTypes.WALLET_RESPONSE in data) { memberName = requestTypes.WALLET_RESPONSE; isResponse = true; } if (requestTypes.STATUS_RESPONSE in data) { memberName = requestTypes.STATUS_RESPONSE; isResponse = true; } if (memberName === "") { throw new Error("hosted-payments.utils.js - Could not parse data from response/request object."); } if (!isResponse) { if (typeof data[memberName][responseMemberName] !== "undefined") { result = data[memberName][responseMemberName]; } else if (typeof data[memberName][requestMemberName] !== "undefined") { result = data[memberName][requestMemberName]; } else { throw new Error("hosted-payments.utils.js - Could not parse data from response/request object."); } } else { result = data[memberName]; } return result; }; var promptAvs = function($element) { var deferred = jQuery.Deferred(); if (!hp.Utils.defaults.promptForAvs) { deferred.resolve(); return deferred; } if (typeof $element === "undefined") { $element = $(".hp-form"); } if ($element.find(".hp-avs-prompt").length) { $element.find(".hp-avs-prompt").remove(); } setTimeout(function() { var template = [ '<div class="hp-avs-prompt">', '<div class="hp-avs-prompt-container">', '<p>Billing Address</p>', '<div class="hp-avs-prompt-left">', '<label class="hp-label-avs" for="avsStreet">Address <span class="hp-avs-required">*</span></label>', '<div class="hp-input hp-input-avs hp-input-avs-street">', '<input placeholder="Street Address" value="' + hp.Utils.defaults.billingAddress.addressLine1 + '" name="avsStreet" id="avsStreet" autocomplete="on" type="text" pattern="\\d*">', '</div>', '</div>', '<div class="hp-avs-prompt-right">', '<div class="hp-pull-left">', '<label class="hp-label-avs" for="avsZip">City</label>', '<div class="hp-input hp-input-avs hp-input-avs-city">', '<input placeholder="City" autocomplete="on" type="text">', '</div>', '</div>', '<div class="hp-pull-left">', '<label class="hp-label-avs" for="avsZip">State</label>', '<div class="hp-input hp-input-avs hp-input-avs-state">', '<input placeholder="State" autocomplete="on" type="text">', '</div>', '</div>', '<div class="hp-pull-left">', '<label class="hp-label-avs" for="avsZip">Zip <span class="hp-avs-required">*</span></label>', '<div class="hp-input hp-input-avs hp-input-avs-zip">', '<input placeholder="Zipcode" value="' + hp.Utils.defaults.billingAddress.postalCode + '" name="avsZip" id="avsZip" autocomplete="on" type="text" pattern="\\d*">', '</div>', '</div>', '</div>', '<br class="hp-break" />', '<hr>', '<button class="hp-submit hp-avs-submit">Submit Payment</button>', hp.Utils.defaults.allowAvsSkip ? '<a class="hp-avs-skip" href="javascript:;">Skip \'Address Verification\'</a>' : '', '</div>', '</div>' ].join(""); $element.prepend(template); var $avsPrompt = $element.find(".hp-avs-prompt"), avsZipValue = "", avsStreetValue = ""; var handleSubmit = function(e) { e.preventDefault(); hp.Utils.updateAvsInfo(avsStreetValue, avsZipValue); $element.removeClass("hp-avs-active"); $avsPrompt.removeClass("active"); deferred.resolve(); setTimeout(function() { $element.find(".hp-avs-prompt").remove(); }, 0); }; $avsPrompt.find(".hp-input-avs input").on("focus blur keyup", function(e) { e.preventDefault(); if ($(this).attr("name") === "avsStreet") { avsStreetValue = $(this).val(); } if ($(this).attr("name") === "avsZip") { avsZipValue = $(this).val(); } var keycode = (e.keyCode ? e.keyCode : e.which); if (keycode === 13) { handleSubmit(e); } }); $avsPrompt.find(".hp-avs-submit").on("click", handleSubmit); if (hp.Utils.defaults.allowAvsSkip) { $avsPrompt.find(".hp-avs-skip").on("click", function(e) { e.preventDefault(); $element.removeClass("hp-avs-active"); $avsPrompt.removeClass("active"); deferred.resolve(); setTimeout(function() { $element.find(".hp-avs-prompt").remove(); }, 0); hp.Utils.defaults.onAvsDismissCallback(); }); } $element.addClass("hp-avs-active"); $avsPrompt.addClass("active"); }, 0); $element.find(".hp-input-avs-street input").focus(); return deferred; }; // basic http requests var makeRequest = function(data, isSync) { var deferred = jQuery.Deferred(); var requestObject = { url: hp.Utils.defaults.baseUrl + encodeURI("?dt=" + new Date().getTime()), type: "POST", dataType: "json", contentType: "application/json", crossDomain: true, data: JSON.stringify(data) }; if (isSync) { requestObject.async = false; } $.ajax(requestObject).done(function(res) { var requestData = getObjectResponseFromData(data); if (res.error) { res.error.request = requestData; deferred.resolve(res.error); return; } var result = getObjectResponseFromData(res); result.request = requestData; deferred.resolve(result); }) .fail(deferred.reject) .catch(deferred.reject); return deferred; }; var reset = function(options) { hp.Utils.log("Checking options to reset with...", options); if (typeof options === "undefined") { options = {}; } if (options === null) { options = {}; } hp.Utils.log("Getting instance element...", hp.Utils.__instance.element); var element = $(hp.Utils.__instance.element); /* * If transvault is active, cancelTransaction before resetting plugin */ if ($(".hp-form-transvault").length) { hp.Utils.plugins.Transvault.cancelTransaction(true); } hp.Utils.log("Emptying the container element..."); element.empty(); hp.Utils.__instance.element = element.get(); hp.Utils.log("Handle special option types..."); if (typeof options.entryType !== "undefined") { options.entryType = hp.Utils.setEntryType(options.entryType); } if (typeof options.paymentType !== "undefined") { options.paymentType = hp.Utils.setPaymentType(options.paymentType); } if (typeof options.paymentService !== "undefined") { options.paymentService = hp.Utils.setPaymentService(options.paymentService); } if (typeof options.amount !== "undefined") { options.amount = hp.Utils.setAmount(options.amount); } hp.Utils.log("Merging plugin defaults with newly provided options..."); hp.Utils.defaults = jQuery.extend({}, hp.Utils.defaults, options); element.data(options); setTimeout(function() { hp.Utils.log("Reinitialized plugin with new options!"); hp.Utils.__instance.init(); hp.Utils.__instance = hp.Utils.__instance; }); }; var signIn = function(bypassSessionStorage) { var deferred = jQuery.Deferred(), createdOn = (new Date()).toISOString(), sessionId = getSession().sessionToken, apiKey = getSession().apiKey, sessionSpan = 1800, shouldBypassSessionStorage = (typeof bypassSessionStorage === "undefined") ? true : bypassSessionStorage; /* * Skip sign in */ if (hp.Utils.defaults.paymentService === hp.PaymentService.TEST) { hp.Utils.log("Sign In: Bypassed."); hp.Utils.setSession(apiKey); deferred.resolve(apiKey); return deferred; } /* * Handle refresh */ if (!shouldBypassSessionStorage && (sessionStorage.getItem("hp.sessionToken") !== null && sessionStorage.getItem("hp.sessionTokenTS") !== null)) { var sessionTokenTS = new Date(sessionStorage.getItem("hp.sessionTokenTS")); var now = new Date(createdOn); var timeSpan = Math.floor((now.getTime() - sessionTokenTS.getTime()) / (1000)); if (timeSpan < sessionSpan) { var sessionHash = sessionStorage.getItem("hp.sessionToken"); var sessionDecoded = Base64.decode(sessionHash); var sessionToken = sessionDecoded.split("|")[0]; var sessionHref = sessionDecoded.split("|")[1]; var sessionBaseUrl = sessionDecoded.split("|")[2]; if (sessionHref === location.href && sessionBaseUrl === hp.Utils.defaults.baseUrl) { hp.Utils.log("Sign In: Total time span " + timeSpan + "."); hp.Utils.log("Sign In: Retrieved from sessionStorage.", sessionToken); hp.Utils.setSession(sessionToken); deferred.resolve(sessionToken); return deferred; } } else { hp.Utils.log("Sign In: Session expired. Generating new session."); sessionStorage.clear(); } } hp.Utils.makeRequest({ "signIn": { "signInRequest": { "apiKey": apiKey } } }).then(function(res) { hp.Utils.setSession(res.token); hp.Utils.setIpAddress(res.ipAddress); deferred.resolve(res); if (!shouldBypassSessionStorage) { sessionStorage.setItem("hp.sessionToken", Base64.encode(res.token + "|" + location.href + "|" + hp.Utils.defaults.baseUrl)); sessionStorage.setItem("hp.sessionTokenTS", createdOn); } hp.Utils.log("Sign In: Retrieved from server."); }, function(res) { if (typeof res === "undefined" || res === null || res === "") { hp.Utils.reset(); return; } var errorResponse = { "status": "Error", "message": "We're sorry. Payments cannot accepted at this time. Please try again later.", "created_on": createdOn, "token": sessionId }; if (!hp.Utils.shouldErrorPostBack()) { hp.Utils.showError(errorResponse.message); hp.Utils.defaults.errorCallback(errorResponse); } else { hp.Utils.buildFormFromObject(errorResponse).then(function($form) { $form.attr("action", hp.Utils.defaults.errorCallback).submit(); }); } deferred.reject(); }); return deferred; }; var formatCurrency = function(amount) { var aDigits = amount.toFixed(2).split("."); aDigits[0] = aDigits[0].split("").reverse().join("").replace(/(\d{3})(?=\d)/g, "$1,").split("").reverse().join(""); return "$" + aDigits.join("."); }; var hasChecked = false; var checkHttpsConnection = function() { if (!hasChecked && (location.hostname === "localhost" || location.hostname === "")) { hasChecked = true; } if (!hp.Utils.defaults.allowHttpsSkip) { if (location.protocol !== "https:" && !hasChecked) { hp.Utils.showError("This connection is untrusted. Make sure you're visting this website using 'HTTPS'!"); } } }; var getBalance = function(sessionId, cardNumber) { var balance = 0, settings = { url: hp.Utils.defaults.baseUrl + encodeURI("?dt=" + new Date().getTime()), type: "POST", dataType: "json", contentType: "application/json", crossDomain: true, data: JSON.stringify({ "balance": { "balanceRequest": { "token": sessionId, "cardNumber": cardNumber } } }), async: false }; $.ajax(settings).done(function(res) { if (res.balanceResponse) { balance = res.balanceResponse.balance; } }).fail(function() { balance = 0; }); return balance; }; var isEmail = function(email) { return /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(email); }; var validateEMoneyData = function(formData, callback) { var errors = []; if (typeof formData.email === "undefined" || formData.email === "") { errors.push({ type: "email", message: "Please provide an email address." }); } if (typeof formData.email !== "undefined" && !isEmail(formData.email)) { errors.push({ type: "email", message: "The email provided did not validate." }); } if (typeof formData.password === "undefined" || formData.password === "") { errors.push({ type: "password", message: "Please provide a password." }); } if (typeof formData.password !== "undefined" && formData.password.length <= 6) { errors.push({ type: "password", message: "Please provide a valid password." }); } if (errors.length) { return callback(errors, formData); } return callback(null, formData); }; var validateBankAccountData = function(formData, callback) { var errors = []; if (typeof formData.accountNumber === "undefined" || formData.accountNumber === "") { errors.push({ type: "accountNumber", message: "Account number on card cannot be empty." }); } if (typeof formData.accountNumber !== "undefined" && formData.accountNumber.length <= 8) { errors.push({ type: "accountNumber", message: "The account number must be atleast 8 characters." }); } if (typeof formData.routingNumber === "undefined" || formData.routingNumber === "") { errors.push({ type: "routingNumber", message: "Routing number be empty." }); } if (typeof formData.routingNumber !== "undefined" && formData.routingNumber.length !== 9) { errors.push({ type: "routingNumber", message: "Routing number must be 9 characters." }); } if (typeof formData.name === "undefined" || formData.name === "") { errors.push({ type: "name", message: "Name cannot be empty." }); } if (typeof formData.name !== "undefined" && formData.name.length <= 1) { errors.push({ type: "name", message: "Name must be greater than one character." }); } if (errors.length) { return callback(errors, formData); } return callback(null, formData); }; var shouldErrorPostBack = function() { var options = hp.Utils.defaults; if (typeof options.errorCallback !== "function" && typeof options.errorCallback !== "undefined") { return true; } return false; }; var shouldSuccessPostBack = function() { var options = hp.Utils.defaults; if (typeof options.successCallback !== "function" && typeof options.successCallback !== "undefined") { return true; } return false; }; // Validate Credit Card Data var validateCreditCardData = function(formData, callback) { var errors = []; if (!$.payment.validateCardNumber(formData.cardNumber)) { errors.push({ type: "cc", message: "Card number is invalid." }); } if (!$.payment.validateCardExpiry(formData._expiryMonth, formData._expiryYear)) { errors.push({ type: "date", message: "Expiration date is invalid." }); } if (!$.payment.validateCardCVC(formData.cvv, formData.cardType)) { errors.push({ type: "cvv", message: "CVV is not valid for this card type." }); } if (typeof formData.name === "undefined" || formData.name === "") { errors.push({ type: "name", message: "Name on card cannot be empty." }); } if (typeof formData.name !== "undefined" && formData.name.length <= 1) { errors.push({ type: "name", message: "Name on card must be greater than one character." }); } if (errors.length) { return callback(errors, formData); } return callback(null, formData); }; var buildAntiForgeryInput = function() { var result = ""; if (hp.Utils.defaults.antiForgeryToken === "" || hp.Utils.defaults.antiForgeryName === "") { return null; } if (hp.Utils.defaults.antiForgeryToken.startsWith(".") || hp.Utils.defaults.antiForgeryToken.startsWith("#") || hp.Utils.defaults.antiForgeryToken.includes("[")) { result = $(hp.Utils.defaults.antiForgeryToken).eq(0).val() || $(hp.Utils.defaults.antiForgeryToken).eq(0).text(); } else { result = hp.Utils.defaults.antiForgeryToken; } if (typeof result === "undefined" || result === "") { return null; } return $("<input />", { "type": "hidden", "name": hp.Utils.defaults.antiForgeryName, "value": result }); }; var buildFormFromObject = function(obj) { var deferred = jQuery.Deferred(), $antiForgeryInput = buildAntiForgeryInput(); setTimeout(function() { var formId = "FRM" + (new Date()).getTime().toString(), $form = $("<form />", { "method": "POST", "id": formId }); if (!$.isEmptyObject(obj)) { if (typeof obj.push === "function") { for (var i = obj.length - 1; i >= 0; i--) { var objInArray = obj[i]; for (var objKey in objInArray) { $form.append($("<input />", { "type": "hidden", "name": objKey + "[" + i + "]", "value": objInArray[objKey] })); } } } else { for (var key in obj) { $form.append($("<input />", { "type": "hidden", "name": key, "value": obj[key] })); } } if ($antiForgeryInput) { $form.append($antiForgeryInput); } $(document.body).prepend($form); return deferred.resolve($("#" + formId)); } return deferred.reject(); }, 0); return deferred; }; var getTerminalId = function() { return hp.Utils.defaults.terminalId || ""; }; var getCorrelationId = function() { return hp.Utils.defaults.correlationId.length ? hp.Utils.defaults.correlationId : generateGuild(); }; var setContainerClass = function($instance) { var mobileClass = "hp-form-mobile", tabletClass = "hp-form-tablet", desktopClass = "hp-form-desktop"; var currentWidth = $instance.outerWidth(true, true), containerElement = $instance.find(".hp"); containerElement .removeClass(mobileClass) .removeClass(tabletClass) .removeClass(desktopClass); setTimeout(function() { if (currentWidth >= 615) { containerElement.addClass(desktopClass); return; } if (currentWidth >= 420) { containerElement.addClass(tabletClass); return; } if (currentWidth >= 320) { containerElement.addClass(mobileClass); return; } }, 0); }; var handleError = function(res) { var errorResponse = { "status": "Error", "message": "Your session is no longer valid. Please refresh your page and try again.", "created_on": (new Date()).toISOString(), "token": getSession().sessionToken }; if (typeof res === "undefined") { if (!hp.Utils.shouldErrorPostBack()) { hp.Utils.showError(errorResponse.message); hp.Utils.defaults.errorCallback(errorResponse); } else { hp.Utils.buildFormFromObject(errorResponse).then(function($form) { $form.attr("action", hp.Utils.defaults.errorCallback).submit(); }); } return; } var message = ""; if (typeof res.message !== "undefined") { message = res.message; } else if (typeof res.description !== "undefined") { message = res.description; } else if (typeof res.error !== "undefined" && typeof res.error.description !== "undefined") { message = res.error.description; } else { message = res; } errorResponse.message = message; if (hp.Utils.shouldErrorPostBack()) { hp.Utils.buildFormFromObject(errorResponse).then(function($form) { $form.attr("action", hp.Utils.defaults.errorCallback).submit(); }); } else { hp.Utils.showError(errorResponse.message); hp.Utils.defaults.errorCallback(errorResponse); } }; var handleSuccess = function(res) { console.log(res); var errorResponse = { "status": "Error", "message": "Your session is no longer valid. Please refresh your page and try again.", "created_on": (new Date()).toISOString(), "token": getSession().sessionToken }; if (typeof res === "undefined") { if (!hp.Utils.shouldErrorPostBack()) { hp.Utils.showError(errorResponse.message); hp.Utils.defaults.errorCallback(errorResponse); } else { hp.Utils.buildFormFromObject(errorResponse).then(function($form) { $form.attr("action", hp.Utils.defaults.errorCallback).submit(); }); } return; } var response = res.length > 1 ? res : res[0]; if (hp.Utils.shouldSuccessPostBack()) { hp.Utils.buildFormFromObject(response).then(function($form) { $form.attr("action", hp.Utils.defaults.successCallback).submit(); }); } else { hp.Utils.defaults.successCallback(response); } }; var setupPluginInstances = function($element) { var deferred = jQuery.Deferred(); // Handle instance hp.Utils.createInstance($element, function(instance) { // The same elements across many instances var $this = $element, $submit = $this.find(".hp-submit"), $all = $this.find(".hp-input"), clearInputs = $.noop(); hp.Utils.checkHttpsConnection(); instance.init(); instance.attachEvents(); /* * Transvault * Methods for handling swipes through a terminal * @description: * Invoke terminal and communicate to this instance unqiuely */ if (instance.isTransvault()) { $this .off() .on("hp.transvaultSuccess", function(e, data) { var _response = data; instance.showSuccess(); hp.Utils.hideLoader(); if (!hp.Utils.shouldSuccessPostBack()) { hp.Utils.defaults.successCallback(_response); } else { hp.Utils.buildFormFromObject(_response).then(function($form) { $form.attr("action", hp.Utils.defaults.successCallback).submit(); }); } }) .on("hp.transvaultError", function(e, data) { var message = ""; var bypass = false; var createdOn = (new Date()).toISOString(); var sessionId = hp.Utils.getSession().sessionToken; if (typeof data !== "undefined" && typeof data.error !== "undefined") { message = data.error.description; } else if (typeof data !== "undefined" && typeof data.error === "undefined") { message = data; } else { message = "Unable to parse message from server. Most likely an unhandled event."; bypass = true; } var errorResponse = { "status": bypass ? "Warning" : "Error", "message": message, "created_on": createdOn, "token": sessionId }; if (bypass) { return; } if (!hp.Utils.shouldErrorPostBack()) { hp.Utils.showError(errorResponse.message); hp.Utils.defaults.errorCallback(errorResponse); } else { hp.Utils.buildFormFromObject(errorResponse).then(function($form) { $form.attr("action", hp.Utils.defaults.errorCallback).submit(); }); } try { hp.Utils.plugins.Transvault.cancelTransaction(true); $.connection.hub.stop(); } catch (ex) { hp.Utils.log(ex); } }); } /* * Code * Methods for handling barcodes & swipes * @description: * Should handle encrypted MSR reads * Should handle non-encrypted MSR reads * Should handle non-encrypted Barcode reads */ if (instance.isCode() || instance.isBankAccount() || instance.isCreditCard() || instance.isGiftCard()) { $this .off() .on("hp.submit", function(e, eventResponse) { if (eventResponse.type === instance.requestTypes.charge) { instance.handleSuccess(eventResponse.res); hp.Utils.hideLoader(); } if (eventResponse.type === instance.requestTypes.error) { instance.handleError(eventResponse.res); hp.Utils.hideLoader(); } instance.clearInputs(); }); } deferred.resolve(); }); return deferred; }; /* * Export "Utils" */ hp.Utils.handleLegacyCssClassApplication = handleLegacyCssClassApplication; hp.Utils.makeRequest = makeRequest; hp.Utils.validateCreditCardData = validateCreditCardData; hp.Utils.validateBankAccountData = validateBankAccountData; hp.Utils.validateEMoneyData = validateEMoneyData; hp.Utils.buildFormFromObject = buildFormFromObject; hp.Utils.buildAntiForgeryInput = buildAntiForgeryInput; hp.Utils.createInstance = createInstance; hp.Utils.showSuccessPage = showSuccessPage; hp.Utils.getAmount = getAmount; hp.Utils.setAmount = setAmount; hp.Utils.getSession = getSession; hp.Utils.setSession = setSession; hp.Utils.setIpAddress = setIpAddress; hp.Utils.getIpAddress = getIpAddress; hp.Utils.getBalance = getBalance; hp.Utils.formatCurrency = formatCurrency; hp.Utils.buildResultObjectByType = buildResultObjectByType; hp.Utils.generateGuild = generateGuild; hp.Utils.createOrder = createOrder; hp.Utils.createNav = createNav; hp.Utils.getCorrelationId = getCorrelationId; hp.Utils.setContainerClass = setContainerClass; hp.Utils.shouldSuccessPostBack = shouldSuccessPostBack; hp.Utils.shouldErrorPostBack = shouldErrorPostBack; hp.Utils.getTerminalId = getTerminalId; hp.Utils.getVersion = getVersion; hp.Utils.setVersion = setVersion; hp.Utils.showLoader = showLoader; hp.Utils.hideLoader = hideLoader; hp.Utils.showError = showError; hp.Utils.hideError = hideError; hp.Utils.setPaymentInstrument = setPaymentInstrument; hp.Utils.log = log; hp.Utils.setEntryType = setEntryType; hp.Utils.setPaymentType = setPaymentType; hp.Utils.updateAvsInfo = updateAvsInfo; hp.Utils.promptAvs = promptAvs; hp.Utils.checkHttpsConnection = checkHttpsConnection; hp.Utils.handleError = handleError; hp.Utils.handleSuccess = handleSuccess; hp.Utils.signIn = signIn; hp.Utils.setupPluginInstances = setupPluginInstances; hp.Utils.reset = reset; hp.Utils.setPaymentService = setPaymentService; hp.Utils.retrieveTransactionStatus = retrieveTransactionStatus; })(jQuery, window, document); (function($, window, document, undefined) { "use strict"; /* * Export "hp" */ window.hp = hp || {}; function Success($element) { this.context = null; this.$parent = null; this.$content = null; this.$element = $element; this.formData = { _isValid: false }; } Success.prototype.init = function () { var context = hp.Utils.handleLegacyCssClassApplication("success", this.$element), $parent = context.parent, $content = context.content; $parent .find(".icon.success") .addClass("animate") .show(); this.context = context; this.$parent = $parent; this.$content = $content; }; Success.prototype.createTemplate = function() { var $html = [ '<div class="hp-success-visual"></div>', '<h2 class="hp-success-label">{{successLabel}}</h2>', '<p class="text-muted">{{redirectLabel}}</p>' ].join(""); return $html; }; Success.prototype.showSuccess = function(delay) { return hp.Utils.showSuccessPage(delay); }; Success.prototype.isCreditCard = function() { return false; }; Success.prototype.isBankAccount = function() { return false; }; Success.prototype.isEMoney = function() { return false; }; Success.prototype.isSuccessPage = function() { return true; }; Success.prototype.isCode = function() { return false; }; Success.prototype.isGiftCard = function() { return false; }; /* * Export "Credit Card" */ hp.Success = Success; })(jQuery, window, document); (function($, window, document, undefined) { "use strict"; /* * Export "hp" */ window.hp = hp || {}; /* * Credit Card Class */ function CreditCard($element) { this.context = null; this.$parent = null; this.$content = null; this.$loader = null; this.$element = $element; this.formData = { _isValid: false }; this.requestTypes = {}; this.requestTypes.createPaymentInstrument = 0; this.requestTypes.charge = 1; this.requestTypes.error = 9; // session this.instrumentId = ""; this.transactionId = ""; } var $cc = null, $cvv = null, $month = null, $year = null, $name = null, $submit = null, $visualcc = null, $visualmonth = null, $visualyear = null, $visualname = null, $visualcard = null, $all = null, $fancy = null; var sessionId = "", createdOn = (new Date()).toISOString(); CreditCard.prototype.init = function() { sessionId = hp.Utils.getSession().sessionToken; // utils call var context = hp.Utils.handleLegacyCssClassApplication("cc", this.$element), $parent = context.parent, $content = context.content; // Clean parent, notify on complete. $parent .removeClass("hp-back") .trigger("hp.notify"); this.context = context; this.$parent = $parent; this.$content = $content; this.$loader = $parent.find(".hp-img-loading").eq(0); this.wasOnceEMoney = false; $cc = this.$content.find(".hp-input-cc input"); $cvv = this.$content.find(".hp-input-cvv input"); $month = this.$content.find(".hp-input-month select"); $year = this.$content.find(".hp-input-year select"); $name = this.$content.find(".hp-input-name input"); $submit = this.$content.find(".hp-submit"); $visualcc = this.$content.find(".hp-card-visual-number"); $visualmonth = this.$content.find(".hp-card-visual-expiry-month"); $visualyear = this.$content.find(".hp-card-visual-expiry-year"); $visualname = this.$content.find(".hp-card-visual-name"); $visualcard = this.$content.find(".hp-card-visual"); $visualcard = this.$content.find(".hp-card-visual"); $all = this.$content.find(".hp-input"); $fancy = $([$month, $year]); $fancy.fancySelect({ includeBlank: true }); this.transactionId = hp.Utils.defaults.transactionId; }; CreditCard.prototype.clearInputs = function() { this.formData = { _isValid: false }; $visualcc.html(hp.Utils.defaults.defaultCardCharacters); $visualmonth.html(hp.Utils.defaults.defaultDateCharacters); $visualyear.html(hp.Utils.defaults.defaultDateCharacters); $visualname.text(hp.Utils.defaults.defaultNameOnCardName); $visualcard.parent().removeClass().addClass("hp-content hp-content-cc hp-content-active"); $name.removeAttr("disabled").val(""); $month.removeAttr("disabled"); $year.removeAttr("disabled"); $cvv.removeAttr("disabled").val(""); $cc.removeAttr("disabled").val(""); $submit.removeAttr("disabled"); $submit.text("Submit Payment"); }; CreditCard.prototype.createTemplate = function(defaultCardCharacters, defaultNameOnCardName, defaultDateCharacters) { if (hp.Utils.defaults.paymentTypeOrder.indexOf(0) < 0) { return ""; } if (typeof defaultCardCharacters === "undefined" || typeof defaultNameOnCardName === "undefined" || typeof defaultDateCharacters === "undefined") { throw new Error("hosted-payments.credit-card.js : Cannot create template. Arguments are null or undefined."); } var generateYearList = function(input) { var min = new Date().getFullYear(), max = (new Date().getFullYear()) + 10, select = ""; for (var i = min; i <= max; i++) { if (i === min) { select += '<option selected="selected">'; } else { select += "<option>"; } select += i.toString(); select += "</option>"; } return select; }; var generateMonthList = function(input) { var min = 1, select = ""; for (var i = min; i <= 12; i++) { if (i === (new Date().getMonth() + 1)) { select += '<option selected="selected">'; } else { select += "<option>"; } if (i < 10) { select += "0" + i.toString(); } else { select += i.toString(); } select += "</option>"; } return select; }; var parseDatesTemplates = function(input) { return input .replace("{{monthList}}", generateMonthList()) .replace("{{yearList}}", generateYearList()); }; var $html = [ '<div class="hp-card-visual">', '<div class="hp-card-visual-number">' + defaultCardCharacters + '</div>', '<div class="hp-card-visual-name">' + defaultNameOnCardName + '</div>', '<div class="hp-card-visual-expiry">', '<span class="hp-card-visual-expiry-label">Month/Year</span>', '<span class="hp-card-visual-expiry-label-alt">Valid Thru</span>', '<span class="hp-card-visual-expiry-value"><span class="hp-card-visual-expiry-month">' + defaultDateCharacters + '</span><span>/</span><span class="hp-card-visual-expiry-year">' + defaultDateCharacters + '</span></span>', '</div>', '</div>', '<div class="hp-input-wrapper">', '<div class="hp-input hp-input-cc">', '<input placeholder="Enter Card Number" autocomplete="on" type="text" pattern="\\d*">', '</div>', '<div class="hp-input hp-input-name">', '<input placeholder="Enter Full Name" value="' + hp.Utils.defaults.customerName + '" autocomplete="on" type="text">', '</div>', '<br class="hp-break" />', '<div class="hp-input-container hp-input-container-date">', '<div class="hp-input hp-input-month">', '<select autocomplete="on">', '{{monthList}}', '</select>', '</div>', '<div class="hp-input hp-input-year">', '<select autocomplete="on">', '{{yearList}}', '</select>', '</div>', '</div>', '<div class="hp-input hp-input-third hp-input-cvv">', '<input placeholder="Enter CVV" autocomplete="off" type="text" pattern="\\d*">', '<span class="hp-input-cvv-image"></span>', '</div>', '<br class="hp-break" />', '<button class="hp-submit">' + (hp.Utils.defaults.promptForAvs ? "Verify Billing Address &#10144;" : "Submit Payment") + '</button>', '</div>' ].join(""); return parseDatesTemplates($html); }; CreditCard.prototype.showSuccess = function(delay) { return hp.Utils.showSuccessPage(delay); }; CreditCard.prototype.detachEvents = function() { $cc.off().val(""); $cvv.off().val(""); $name.off().val(hp.Utils.defaults.customerName); $submit.off(); $month.off("focus"); $year.off("focus"); $fancy.trigger("disable.fs"); this.$parent.trigger("hp.notify"); this.handleNotify(); }; CreditCard.prototype.handleCreditCardInput = function(cardNumber) { if (cardNumber === "") { $visualcc.html(hp.Utils.defaults.defaultCardCharacters); return; } var cardType = $.payment.cardType(cardNumber); if ((cardType === null || cardType !== "emoney") && this.wasOnceEMoney) { var date = new Date(); $name.val("").trigger("keyup").removeAttr("readonly"); $month.removeAttr("readonly").val(date.getMonth() <= 9 ? "0" + date.getMonth() : date.getMonth()).trigger("change"); $year.removeAttr("readonly").val(date.getFullYear()).trigger("change"); $fancy.trigger("enable.fs"); $cvv.val("").trigger("keyup").removeAttr("readonly"); } if (cardType === "emoney") { $name.val("EMoney Card").trigger("keyup").attr("readonly", "readonly"); $month.val("12").trigger("change").attr("readonly", "readonly"); $year.val("2025").trigger("change").attr("readonly", "readonly"); $cvv.val("999").trigger("keyup").attr("readonly", "readonly"); $fancy.trigger("disable.fs"); this.wasOnceEMoney = true; } this.formData.cardNumber = cardNumber.replace(/\s/gi, ""); this.formData.cardType = cardType; $visualcc.text(cardNumber); }; CreditCard.prototype.handleMonthInput = function(expiryMonth) { if (expiryMonth === "") { $visualmonth.html(hp.Utils.defaults.defaultDateCharacters); return; } this.formData._expiryMonth = $.trim(expiryMonth); $visualmonth.text(expiryMonth); setTimeout(function() { $month.next().text(expiryMonth); }, 0); }; CreditCard.prototype.handleYearInput = function(expiryYear) { if (expiryYear === "") { $visualyear.html(hp.Utils.defaults.defaultDateCharacters); return; } this.formData._expiryYear = $.trim(expiryYear); $visualyear.text(expiryYear.substring(2)); setTimeout(function() { $year.next().text(expiryYear); }, 0); }; CreditCard.prototype.handleNameInput = function(name) { if (name === "") { $visualname.text(hp.Utils.defaults.defaultNameOnCardName); return; } this.formData.name = $.trim(name); $visualname.text(name); }; CreditCard.prototype.handleCVVInput = function(cvv) { this.formData.cvv = $.trim(cvv); }; CreditCard.prototype.handleCharge = function(res) { var that = this, hasBalance = true, cardBalance = 0; var errorResponse = { "status": "Error", "message": "The payment instrument provided had no remaining funds and will not be applied to the split payment.", "created_on": createdOn, "token": sessionId }; var requestModel = {}; if (hp.Utils.defaults.paymentType == hp.PaymentType.CHARGE) { requestModel = { "charge": { "chargeRequest": { "token": hp.Utils.getSession().sessionToken, "transactionId": this.transactionId, "amount": hp.Utils.getAmount(), "entryType": hp.Utils.defaults.entryType, "instrumentId": this.instrumentId, "correlationId": hp.Utils.getCorrelationId(), "__request": res.request } } }; } if (hp.Utils.defaults.paymentType == hp.PaymentType.REFUND) { requestModel = { "refund": { "refundRequest": { "token": hp.Utils.getSession().sessionToken, "transactionId": this.transactionId, "amount": hp.Utils.getAmount(), "entryType": hp.Utils.defaults.entryType, "instrumentId": this.instrumentId, "correlationId": hp.Utils.getCorrelationId(), "__request": res.request } } }; } hp.Utils.makeRequest(requestModel) .then(hp.Utils.buildResultObjectByType) .then(function(promiseResponse) { that.$parent.trigger("hp.submit", { "type": that.requestTypes.charge, "res": promiseResponse }); }) .fail(function(promiseResponse) { if (typeof promiseResponse.responseJSON !== "undefined") { promiseResponse = promiseResponse.responseJSON; } that.$parent.trigger("hp.submit", { "type": that.requestTypes.error, "res": promiseResponse }); }); }; CreditCard.prototype.handleSubmit = function() { var that = this; if (!that.formData._isValid) { $visualcard.addClass("hp-card-invalid"); setTimeout(function() { $visualcard.removeClass("hp-card-invalid"); }, 2000); return; } $submit.attr("disabled", "disabled").text("Submitting..."); hp.Utils.promptAvs().then(function() { hp.Utils.showLoader(); return hp.Utils.makeRequest({ "createPaymentInstrument": { "createPaymentInstrumentRequest": { "correlationId": hp.Utils.getCorrelationId(), "transactionId": that.transactionId, "token": hp.Utils.getSession().sessionToken, "name": that.formData.name, "properties": { "cardNumber": that.formData.cardNumber, "expirationDate": that.formData._expiryMonth + "/" + that.formData._expiryYear, "cvv": that.formData.cvv, "nameOnCard": that.formData.name }, "billingAddress": { "addressLine1": hp.Utils.defaults.billingAddress.addressLine1, "postalCode": hp.Utils.defaults.billingAddress.postalCode } } } }); }) .then(function(res) { if (res.isException) { that.$parent.trigger("hp.submit", { "type": 9, "res": res }); return; } that.instrumentId = res.instrumentId; that.transactionId = (typeof res.transactionId !== "undefined") ? res.transactionId : that.transactionId; that.$parent.trigger("hp.submit", { "type": 0, "res": res }); that.handleCharge(res); }).fail(function(err) { if (typeof err.responseJSON !== "undefined") { err = err.responseJSON; } that.$parent.trigger("hp.submit", { "type": 9, "res": err }); }); }; CreditCard.prototype.handleSuccess = function(res) { hp.Utils.handleSuccess(res); this.showSuccess(); }; CreditCard.prototype.handleError = function(res) { hp.Utils.handleError(res); this.clearInputs(); }; CreditCard.prototype.attachEvents = function() { this.detachEvents(); var $this = this; $fancy.trigger("enable.fs"); hp.Utils.setContainerClass($this.$element); $cc .payment('formatCardNumber') .on("keyup", function() { var cardNumber = $(this).val(); var cardType = $.payment.cardType(cardNumber); $this.$parent.removeClass("hp-back"); if (cardType) { $this.$content .removeClass() .addClass("hp-content hp-content-cc hp-content-active") .addClass("hp-content-card-" + cardType); } $this.handleCreditCardInput(cardNumber); $this.$parent.trigger("hp.cc", cardNumber); $this.$parent.trigger("hp.notify"); $this.handleNotify(); }); $cvv .payment('formatCardCVC').on("focus", function() { $this.$parent.addClass("hp-back"); $this.$parent.trigger("hp.notify"); $this.handleNotify(); }).on("keyup", function(e) { var cvv = $(this).val(); $this.handleCVVInput(cvv); $this.$parent.trigger("hp.cvv", cvv); $this.$parent.trigger("hp.notify"); $this.handleNotify(); }); $name .on("focus", function() { $this.$parent.trigger("hp.notify"); $this.handleNotify(); $this.$parent.removeClass("hp-back"); }).on("keyup", function(e) { var name = $(this).val(); $this.handleNameInput(name); $this.$parent.trigger("hp.name", name); $this.$parent.trigger("hp.notify"); $this.handleNotify(); }); if (hp.Utils.defaults.customerName !== "") { $name.trigger("keyup"); } $month .on("focus", function(e) { $(".hp-input-active").removeClass("hp-input-active"); $(this).parents(".hp-input").addClass("hp-input-active"); }) .on("change.fs", function(e) { var month = $(this).val(); $this.handleMonthInput(month); $this.$parent.removeClass("hp-back"); $this.$parent.trigger("hp.expiryMonth", month); $this.$parent.trigger("hp.notify"); $this.handleNotify(); }) .on("blur", function(e) { $(".hp-input-active").removeClass("hp-input-active"); }) .trigger("change.fs"); $year .on("focus", function(e) { $(".hp-input-active").removeClass("hp-input-active"); $(this).parents(".hp-input").addClass("hp-input-active"); }) .on("change.fs", function(e) { var year = $(this).val(); $this.handleYearInput(year); $this.$parent.removeClass("hp-back"); $this.$parent.trigger("hp.expiryYear", year); $this.$parent.trigger("hp.notify"); $this.handleNotify(); }) .on("blur", function(e) { $(".hp-input-active").removeClass("hp-input-active"); }) .trigger("change.fs"); $submit .on("click", function(e) { e.preventDefault(); $this.handleSubmit(); $this.$parent.trigger("hp.notify"); $this.handleNotify(); }); this.$parent.trigger("hp.notify"); this.handleNotify(); }; CreditCard.prototype.handleNotify = function() { if (typeof this.formData._expiryYear !== "undefined" && typeof this.formData._expiryMonth !== "undefined") { this.formData.expirationDate = $.trim(this.formData._expiryMonth + this.formData._expiryYear.substring(2)); } var $this = this; hp.Utils.validateCreditCardData(this.formData, function(error, data) { $all.removeClass("hp-error"); if (!error) { $this.formData._isValid = true; return; } for (var err in error) { if (error[err].type === "cc") { if ($cc.val() !== "") { $cc.parent().addClass("hp-error"); } } if (error[err].type === "cvv") { if ($cvv.val() !== "") { $cvv.parent().addClass("hp-error"); } } if (error[err].type === "date") { if ($year.val() !== "" && $month.val() !== "") { $year.parent().addClass("hp-error"); $month.parent().addClass("hp-error"); } } if (error[err].type === "name") { if ($name.val() !== "") { $name.parent().addClass("hp-error"); } } } }); }; CreditCard.prototype.isCreditCard = function() { return true; }; CreditCard.prototype.isBankAccount = function() { return false; }; CreditCard.prototype.isEMoney = function() { return false; }; CreditCard.prototype.isCode = function() { return false; }; CreditCard.prototype.isSuccessPage = function() { return false; }; CreditCard.prototype.isTransvault = function() { return false; }; CreditCard.prototype.isGiftCard = function() { return false; }; /* * Export "Credit Card" */ hp.CreditCard = CreditCard; })(jQuery, window, document); (function($, window, document, undefined) { "use strict"; /* * Export "hp" */ window.hp = hp || {}; /* * Gift Card Class */ function GiftCard($element) { this.context = null; this.$parent = null; this.$content = null; this.$loader = null; this.$element = $element; this.formData = { _isValid: false }; this.currrentPage = 0; this.transactionId = ""; } var sessionId = "", createdOn = (new Date()).toISOString(); GiftCard.prototype.init = function() { sessionId = hp.Utils.getSession().sessionToken; // utils call var context = hp.Utils.handleLegacyCssClassApplication("gc", this.$element), $parent = context.parent, $content = context.content; // Clean parent, notify on complete. $parent .removeClass("hp-back") .trigger("hp.notify"); this.context = context; this.$parent = $parent; this.$content = $content; this.totalPages = $content.find(".hp-page").length; this.currrentPage = 0; this.transactionId = hp.Utils.defaults.transactionId; }; GiftCard.prototype.clearInputs = function() { this.formData = { _isValid: false }; }; GiftCard.prototype.createTemplate = function(defaultCardCharacters, defaultNameOnCardName, defaultDateCharacters) { if (hp.Utils.defaults.paymentTypeOrder.indexOf(4) < 0) { return ""; } var $html = [ '<div class="hp-page hp-page-0 hp-page-active">', '<h2>Swipe, scan, or manually<br /> enter a gift card.</h2><br />', '<div class="hp-card-visual">', '<div class="hp-card-visual-number">' + defaultCardCharacters + '</div>', '<div class="hp-card-visual-name">' + defaultNameOnCardName + '</div>', '<div class="hp-card-visual-expiry">', '<span class="hp-card-visual-expiry-label">Month/Year</span>', '<span class="hp-card-visual-expiry-label-alt">Valid Thru</span>', '<span class="hp-card-visual-expiry-value"><span class="hp-card-visual-expiry-month">12</span><span>/</span><span class="hp-card-visual-expiry-year">' + defaultDateCharacters + '</span></span>', '</div>', '</div>', '<div class="hp-input-wrapper">', '<div class="hp-input-group hp-clearfix">', '<div class="hp-input hp-input-gc hp-pull-left">', '<input placeholder="Enter Card Number" autocomplete="on" type="text" pattern="\\d*">', '</div>', '<button class="hp-submit hp-pull-left">Submit</button>', '</div>', '<hr />', '<button class="hp-submit hp-submit-success">Issue a new Gift Card</button>', '</div>', '</div>', '<div class="hp-page hp-page-1">', '<h2>Page 1.</h2><br />', '</div>', '<div class="hp-page hp-page-2">', '<h2>Page 2.</h2><br />', '</div>', '<div class="hp-page hp-page-3">', '<h2>Page 3.</h2><br />', '</div>', '<div class="hp-page hp-page-4">', '<h2>Page 4.</h2><br />', '</div>', '<div class="hp-page hp-page-5">', '<h2>Page 5.</h2><br />', '</div>', '<br />' ].join(""); return $html; }; GiftCard.prototype.getCurrentPageElement = function() { return this.$content.find(".hp-page-active").eq(0); }; GiftCard.prototype.goTo = function(pageNumber) { if (pageNumber === "first") { pageNumber = 0; } if (pageNumber === "last") { pageNumber = (this.totalPages - 1); } var num = +pageNumber; if (num < 0) { num = 0; } if (num > this.totalPages) { num = this.totalPages; } this.$content .find(".hp-page") .removeClass("hp-page-active") .filter(".hp-page-" + num) .addClass("hp-page-active"); this.currrentPage = num; this.$parent.trigger("hp.notify", { "type" : "page", "value" : num }); }; GiftCard.prototype.next = function() { var page = this.currrentPage + 1; this.goTo(page === this.totalPages ? "first" : page); }; GiftCard.prototype.prev = function() { this.goTo(this.currrentPage === 0 ? "last" : this.currrentPage - 1); }; GiftCard.prototype.showSuccess = function(delay) { return hp.Utils.showSuccessPage(delay); }; GiftCard.prototype.detachEvents = function() { this.$parent.trigger("hp.notify"); this.handleNotify(); }; GiftCard.prototype.handleCharge = function(res) { var that = this, hasBalance = true, cardBalance = 0; var errorResponse = { "status": "Error", "message": "The payment instrument provided had no remaining funds and will not be applied to the split payment.", "created_on": createdOn, "token": sessionId }; hp.Utils.makeRequest({ "charge": { "chargeRequest": { "correlationId": hp.Utils.getCorrelationId(), "token": hp.Utils.getSession().sessionToken, "transactionId": this.transactionId, "instrumentId": this.instrumentId, "entryType" : hp.Utils.defaults.entryType, "amount": hp.Utils.getAmount(), "__request": res.request } } }) .then(hp.Utils.buildResultObjectByType) .then(function(promiseResponse) { that.$parent.trigger("hp.submit", { "type": that.requestTypes.charge, "res": promiseResponse }); }) .fail(function(promiseResponse) { if (typeof promiseResponse.responseJSON !== "undefined") { promiseResponse = promiseResponse.responseJSON; } that.$parent.trigger("hp.submit", { "type": that.requestTypes.error, "res": promiseResponse }); }); }; GiftCard.prototype.handleSubmit = function() { var that = this; if (!that.formData._isValid) { return; } $submit.attr("disabled", "disabled").text("Submitting..."); hp.Utils.promptAvs().then(function(){ hp.Utils.showLoader(); return hp.Utils.makeRequest({ "createPaymentInstrument": { "createPaymentInstrumentRequest": { "correlationId": hp.Utils.getCorrelationId(), "token": hp.Utils.getSession().sessionToken, "name": that.formData.name, "properties": { "cardNumber": that.formData.cardNumber, "expirationDate": that.formData._expiryMonth + "/" + that.formData._expiryYear, "cvv": that.formData.cvv, "nameOnCard": that.formData.name }, "billingAddress": { "addressLine1": hp.Utils.defaults.billingAddress.addressLine1, "postalCode": hp.Utils.defaults.billingAddress.postalCode } } } }); }) .then(function(res) { if (res.isException) { that.$parent.trigger("hp.submit", { "type": 9, "res": res }); return; } that.instrumentId = res.instrumentId; that.transactionId = (typeof res.transactionId !== "undefined") ? res.transactionId : that.transactionId; that.$parent.trigger("hp.submit", { "type": 0, "res": res }); that.handleCharge(res); }).fail(function(err) { if (typeof err.responseJSON !== "undefined") { err = err.responseJSON; } that.$parent.trigger("hp.submit", { "type": 9, "res": err }); }); }; GiftCard.prototype.handleSuccess = function(res) { hp.Utils.handleSuccess(res); this.showSuccess(); }; GiftCard.prototype.handleError = function(res) { hp.Utils.handleError(res); this.clearInputs(); }; GiftCard.prototype.addScanSwipeListener = function(first_argument) { var $this = this; $(document).pos({ onEventName: "hp.global_giftcard_start", offEventName: "hp.global_giftcard_end", onSwipeScan: function(result){ $this.handleSubmit(data); } }); }; GiftCard.prototype.attachEvents = function() { var $this = this; $this.$parent.on("hp.notify", function(e, args) { if (typeof args === "undefined") { return; } if (typeof args.type === "undefined") { return; } if (args.type !== "page") { return; } var pageNum = args.value, pageFunc = "handlePage" + pageNum + "Events"; if (typeof $this[pageFunc] === "undefined") { return; } $this[pageFunc]($this.getCurrentPageElement()); }); $this.handlePage0Events($this.getCurrentPageElement()); $this.handleNotify(); }; GiftCard.prototype.handlePage0Events = function(container) { this.addScanSwipeListener(); container .find(".hp-input-gc input") .payment('formatCardNumber'); container .find(".hp-input-gc .hp-submit") .off() .on("click", function(e){ }); console.log("handlePage0Events", container); }; GiftCard.prototype.handlePage1Events = function(container) { console.log("handlePage1Events", container); }; GiftCard.prototype.handlePage2Events = function(container) { console.log("handlePage2Events", container); }; GiftCard.prototype.handlePage3Events = function(container) { console.log("handlePage3Events", container); }; GiftCard.prototype.handlePage4Events = function(container) { console.log("handlePage4Events", container); }; GiftCard.prototype.handlePage5Events = function(container) { console.log("handlePage5Events", container); }; GiftCard.prototype.handleNotify = function() { var $this = this; hp.Utils.validateCreditCardData(this.formData, function(error, data) { if (!error) { $this.formData._isValid = true; return; } for (var err in error) { } }); }; GiftCard.prototype.isCreditCard = function() { return true; }; GiftCard.prototype.isBankAccount = function() { return false; }; GiftCard.prototype.isEMoney = function() { return false; }; GiftCard.prototype.isCode = function() { return false; }; GiftCard.prototype.isSuccessPage = function() { return false; }; GiftCard.prototype.isTransvault = function() { return false; }; GiftCard.prototype.isGiftCard = function() { return true; }; /* * Export "Credit Card" */ hp.GiftCard = GiftCard; })(jQuery, window, document); (function($, window, document, undefined) { "use strict"; /* * Export "hp" */ window.hp = hp || {}; /* * Bank Account Class */ function BankAccount($element) { this.context = null; this.$parent = null; this.$content = null; this.$element = $element; this.formData = { _isValid: false }; this.requestTypes = {}; this.requestTypes.createPaymentInstrument = 0; this.requestTypes.charge = 1; this.requestTypes.error = 9; this.transactionId = ""; } var $fullname = null, $accountNumber = null, $routingNumber = null, $visualaccount = null, $visualbank = null, $visualrouting = null, $visualfullname = null, $all = null, $submit; var sessionId = "", createdOn = (new Date()).toISOString(); BankAccount.prototype.init = function() { sessionId = hp.Utils.getSession().sessionToken; // utils call var context = hp.Utils.handleLegacyCssClassApplication("bank", this.$element), $parent = context.parent, $content = context.content; // Clean parent, notify on complete. $parent .trigger("hp.notify"); this.context = context; this.$parent = $parent; this.$content = $content; $fullname = this.$content.find(".hp-input-fullname input"); $accountNumber = this.$content.find(".hp-input-account input"); $routingNumber = this.$content.find(".hp-input-routing input"); $visualaccount = this.$content.find(".hp-bank-visual-account"); $visualbank = this.$content.find(".hp-bank-visual"); $visualrouting = this.$content.find(".hp-bank-visual-routing"); $visualfullname = this.$content.find(".hp-bank-visual-name"); $submit = this.$content.find(".hp-submit"); $all = this.$content.find(".hp-input"); this.transactionId = hp.Utils.defaults.transactionId; }; BankAccount.prototype.clearInputs = function() { this.formData = { _isValid: false }; $all.each(function() { $(this).find("input").val(""); }); $visualfullname.html(hp.Utils.defaults.defaultName); $visualaccount.html(hp.Utils.defaults.defaultAccountNumberCharacters); $visualrouting.html(hp.Utils.defaults.defaultRoutingNumberCharacters); $visualbank.parent().removeClass().addClass("hp-content hp-content-bank hp-content-active"); }; BankAccount.prototype.createTemplate = function(defaultName, defaultAccountNumberCharacters, defaultRoutingNumberCharacters) { if (hp.Utils.defaults.paymentTypeOrder.indexOf(1) < 0) { return ""; } if (typeof defaultAccountNumberCharacters === "undefined" || typeof defaultRoutingNumberCharacters === "undefined" || typeof defaultName === "undefined") { throw new Error("hosted-payments.bank-account.js : Cannot create template. Arguments are null or undefined."); } var $html = [ '<div class="hp-bank-visual">', '<div class="hp-bank-visual-image"></div>', '<div class="hp-bank-visual-logo"></div>', '<div class="hp-bank-visual-name">' + defaultName + '</div>', '<div class="hp-bank-visual-account">' + defaultAccountNumberCharacters + '</div>', '<div class="hp-bank-visual-routing">' + defaultRoutingNumberCharacters + '</div>', '</div>', '<div class="hp-input-wrapper">', '<div class="hp-input hp-input-fullname">', '<input placeholder="Enter Full Name" value="' + hp.Utils.defaults.customerName + '" autocomplete="on" type="text">', '</div>', '<div class="hp-break" >', '<div class="hp-input hp-input-account">', '<input placeholder="Account Number" autocomplete="on" type="text" pattern="\\d*">', '</div>', '<div class="hp-input hp-input-routing">', '<input placeholder="Routing Number" autocomplete="on" type="text" pattern="\\d*">', '</div>', '</div>', '<button class="hp-submit">Submit Payment</button>', '<p class="info">* Please note that bank account (ACH) transactions may take up to 3 days to process. This time period varies depending on the your issuing bank. For more information please visit us at <a href="https://www.etsms.com/" target="_blank">https://etsms.com</a>.</p>', '</div>' ].join(""); return $html; }; BankAccount.prototype.detachEvents = function() { this.$content.find(".hp-input-account input").off().val(""); this.$content.find(".hp-input-fullname input").off().val(hp.Utils.defaults.customerName); this.$content.find(".hp-input-routing input").off().val(""); this.$content.find(".hp-submit").off(); this.$parent.trigger("hp.notify"); this.handleNotify(); }; BankAccount.prototype.handleRoutingInput = function(routingNumber) { if (routingNumber === "") { return $visualrouting.html(hp.Utils.defaults.defaultRoutingNumberCharacters); } this.formData.routingNumber = $.trim(routingNumber); $visualrouting.text(routingNumber); }; BankAccount.prototype.handleAccountInput = function(accountNumber) { if (accountNumber === "") { return $visualaccount.html(hp.Utils.defaults.defaultAccountNumberCharacters); } this.formData.accountNumber = $.trim(accountNumber); $visualaccount.text(accountNumber); }; BankAccount.prototype.handleNameInput = function(name) { if (name === "") { return $visualfullname.html(hp.Utils.defaults.defaultName); } this.formData.name = $.trim(name); $visualfullname.text(name); }; BankAccount.prototype.attachEvents = function() { this.detachEvents(); var $this = this; $this.$content.find(".hp-input-account input") .payment('restrictNumeric') .on("keyup, keydown, keypress, change, input", function() { var that = $(this), count = that.val().length; if (count > 16) { var value = that.val().substr(0, 16); that.val(value); } var accountNumber = $(this).val(); $this.$parent.removeClass("hp-back"); $this.$content .removeClass() .addClass("hp-content hp-content-bank hp-content-active"); $this.handleAccountInput(accountNumber); $this.$parent.trigger("hp.account", accountNumber); $this.$parent.trigger("hp.notify"); $this.handleNotify(); }); $this.$content.find(".hp-input-fullname input") .on("keyup, keydown, keypress, change, input", function() { var name = $(this).val(); $this.$parent.removeClass("hp-back"); $this.handleNameInput(name); $this.$parent.trigger("hp.name", name); $this.$parent.trigger("hp.notify"); $this.handleNotify(); }); if (hp.Utils.defaults.customerName !== "") { setTimeout(function() { $this.$content.find(".hp-input-fullname input").val(hp.Utils.defaults.customerName); $this.$content.find(".hp-input-fullname input").trigger("keyup"); $this.$parent.trigger("hp.name", hp.Utils.defaults.customerName); $this.handleNameInput(hp.Utils.defaults.customerName); $this.handleNotify(); }, 0); } $this.$content.find(".hp-input-routing input") .payment('restrictNumeric') .on("keyup, keydown, keypress, change, input", function(e) { var that = $(this), count = that.val().length; if (count > 9) { var value = that.val().substr(0, 9); that.val(value); } var routingNumber = $(this).val(); $this.$parent.removeClass("hp-back"); $this.handleRoutingInput(routingNumber); $this.$parent.trigger("hp.routing", routingNumber); $this.$parent.trigger("hp.notify"); $this.handleNotify(); }); $this.$content.find(".hp-submit") .on("click", function(e) { e.preventDefault(); $this.handleSubmit(); $this.$parent.trigger("hp.notify"); $this.handleNotify(); }); this.$parent.trigger("hp.notify"); this.handleNotify(); }; BankAccount.prototype.handleNotify = function() { var $this = this; hp.Utils.validateBankAccountData(this.formData, function(error, data) { $all.removeClass("hp-error"); if (!error) { $this.formData._isValid = true; return; } for (var err in error) { if (error[err].type === "accountNumber") { if ($accountNumber.val() !== "") { $accountNumber.parent().addClass("hp-error"); } } if (error[err].type === "routingNumber") { if ($routingNumber.val() !== "") { $routingNumber.parent().addClass("hp-error"); } } if (error[err].type === "name") { if ($fullname.val() !== "") { $fullname.parent().addClass("hp-error"); } } } }); }; BankAccount.prototype.showSuccess = function(delay) { return hp.Utils.showSuccessPage(delay); }; BankAccount.prototype.handleCharge = function(res) { var $this = this; var requestModel = {}; if (hp.Utils.defaults.paymentType == hp.PaymentType.CHARGE) { requestModel = { "charge": { "chargeRequest": { "correlationId": hp.Utils.getCorrelationId(), "token": hp.Utils.getSession().sessionToken, "transactionId": $this.transactionId, "instrumentId": $this.instrumentId, "amount": hp.Utils.getAmount(), "__request": res.request } } }; } if (hp.Utils.defaults.paymentType == hp.PaymentType.REFUND) { requestModel = { "refund": { "refundRequest": { "correlationId": hp.Utils.getCorrelationId(), "token": hp.Utils.getSession().sessionToken, "transactionId": $this.transactionId, "instrumentId": $this.instrumentId, "amount": hp.Utils.getAmount(), "__request": res.request } } }; } hp.Utils.makeRequest(requestModel) .then(hp.Utils.buildResultObjectByType) .then(function(promiseResponse) { $this.$parent.trigger("hp.submit", { "type": $this.requestTypes.charge, "res": promiseResponse }); }) .fail(function(promiseResponse) { if (typeof promiseResponse.responseJSON !== "undefined") { promiseResponse = promiseResponse.responseJSON; } $this.$parent.trigger("hp.submit", { "type": $this.requestTypes.error, "res": promiseResponse }); }); }; BankAccount.prototype.handleSuccess = function(res) { hp.Utils.handleSuccess(res); this.showSuccess(); }; BankAccount.prototype.handleError = function(res) { hp.Utils.handleError(res); this.clearInputs(); }; BankAccount.prototype.handleSubmit = function() { var $this = this; if (!$this.formData._isValid) { $visualbank.addClass("hp-bank-invalid"); setTimeout(function() { $visualbank.removeClass("hp-bank-invalid"); }, 2000); return; } $submit.attr("disabled", "disabled").text("Submitting..."); hp.Utils.showLoader(); $submit .attr("disabled", "disabled") .text("Processing payment..."); hp.Utils.makeRequest({ "createPaymentInstrument": { "createPaymentInstrumentRequest": { "correlationId": hp.Utils.getCorrelationId(), "transactionId": $this.transactionId, "token": hp.Utils.getSession().sessionToken, "name": $this.formData.name, "properties": { "accountNumber": $this.formData.accountNumber, "routingNumber": $this.formData.routingNumber, "bankName": $this.formData.name }, "billingAddress": { "addressLine1": hp.Utils.defaults.billingAddress.addressLine1, "postalCode": hp.Utils.defaults.billingAddress.postalCode } } } }).then(function(res) { if (res.isException) { $this.$parent.trigger("hp.submit", { "type": 9, "res": res }); return; } $this.instrumentId = res.instrumentId; $this.transactionId = (typeof res.transactionId !== "undefined") ? res.transactionId : $this.transactionId; $this.$parent.trigger("hp.submit", { "type": 0, "res": res }); $this.handleCharge(res); }).fail(function(err) { if (typeof err.responseJSON !== "undefined") { err = err.responseJSON; } $this.$parent.trigger("hp.submit", { "type": 9, "res": err }); }); }; BankAccount.prototype.isCreditCard = function() { return false; }; BankAccount.prototype.isBankAccount = function() { return true; }; BankAccount.prototype.isEMoney = function() { return false; }; BankAccount.prototype.isSuccessPage = function() { return false; }; BankAccount.prototype.isCode = function() { return false; }; BankAccount.prototype.isTransvault = function() { return false; }; BankAccount.prototype.isGiftCard = function() { return false; }; /* * Export "Bank Account" */ hp.BankAccount = BankAccount; })(jQuery, window, document); (function($, window, document, undefined) { "use strict"; /* * Export "hp" */ window.hp = hp || {}; /* * Code Class */ function Code($element) { this.context = null; this.$parent = null; this.$content = null; this.$element = $element; this.requestTypes = {}; this.requestTypes.createPaymentInstrument = 0; this.requestTypes.charge = 1; this.requestTypes.error = 9; // session this.instrumentId = ""; this.transactionId = ""; this.formData = { _isValid: false }; } var $visualcodecc = null, $visualcodemonth = null, $visualcodeyear = null, $visualcodename = null, $visualcode = null, $all = null; var sessionId = "", createdOn = (new Date()).toISOString(); Code.prototype.init = function() { sessionId = hp.Utils.getSession().sessionToken; // utils call var context = hp.Utils.handleLegacyCssClassApplication("code", this.$element), $parent = context.parent, $content = context.content; // Clean parent, notify on complete. $parent .trigger("hp.notify"); this.context = context; this.$parent = $parent; this.$content = $content; $visualcodecc = this.$content.find(".hp-card-visual-number"); $visualcodemonth = this.$content.find(".hp-card-visual-expiry-month"); $visualcodeyear = this.$content.find(".hp-card-visual-expiry-year"); $visualcodename = this.$content.find(".hp-card-visual-name"); $visualcode = this.$content.find(".hp-card-visual.hp-card-visual-flat"); $all = this.$content.find(".hp-input"); this.transactionId = hp.Utils.defaults.transactionId; }; Code.prototype.clearInputs = function() { this.formData = { _isValid: false }; $visualcode.removeClass("hp-card-visual-flat-active"); $visualcodecc.html(hp.Utils.defaults.defaultCardCharacters); $visualcodemonth.html(hp.Utils.defaults.defaultDateCharacters); $visualcodeyear.html(hp.Utils.defaults.defaultDateCharacters); $visualcodename.html(hp.Utils.defaults.defaultNameOnCardNameSwipe); }; Code.prototype.createTemplate = function(defaultCardCharacters, defaultNameOnCardName, defaultDateCharacters) { if (hp.Utils.defaults.paymentTypeOrder.indexOf(2) < 0) { return ""; } if (typeof defaultCardCharacters === "undefined" || typeof defaultNameOnCardName === "undefined" || typeof defaultDateCharacters === "undefined") { throw new Error("hosted-payments.code.js : Cannot create template. Arguments are null or undefined."); } var $html = [ '<div class="hp-code-title">To begin: Swipe a card or scan a barcode.</div>', '<div class="hp-code-image"></div>', '<div class="hp-card-visual hp-card-visual-flat">', '<div class="hp-card-visual-number">' + defaultCardCharacters + '</div>', '<div class="hp-card-visual-name">' + defaultNameOnCardName + '</div>', '<div class="hp-card-visual-expiry">', '<span class="hp-card-visual-expiry-label">Month/Year</span>', '<span class="hp-card-visual-expiry-label-alt">Valid Thru</span>', '<span class="hp-card-visual-expiry-value"><span class="hp-card-visual-expiry-month">' + defaultDateCharacters + '</span><span>/</span><span class="hp-card-visual-expiry-year">' + defaultDateCharacters + '</span></span>', '</div>', '</div>' ].join(""); return $html; }; Code.prototype.detachEvents = function() { this.$content.find(".hp-submit").off(); this.$parent.off("hp.swipped"); this.$parent.trigger("hp.notify"); $(document).off("hp.global_swipped"); $(window).off("keydown"); }; Code.prototype.attachEvents = function() { this.detachEvents(); var $this = this; $(document).pos(); $(document).on("hp.global_swipped_start", function(event, data) { hp.Utils.showLoader(); hp.Utils.defaults.onSwipeStartCallback(); }); $(document).on("hp.global_swipped_end", function(event, data) { hp.Utils.defaults.onSwipeEndCallback(data); if (!hp.Utils.defaults.ignoreSubmission) { $this.handleSubmit(data); } }); // Kills spacebar page-down event $(window).on("keydown", function(e) { if (e.target == document.body) { return e.keyCode != 32; } }); }; Code.prototype.handleCharge = function(res) { var hasBalance = true, $this = this, cardBalance = 0; var errorResponse = { "status": "Error", "message": "The payment instrument provided had no remaining funds and will not be applied to the split payment.", "created_on": createdOn, "token": sessionId }; var requestModel = {}; if (hp.Utils.defaults.paymentType == hp.PaymentType.CHARGE) { requestModel = { "charge": { "chargeRequest": { "correlationId": hp.Utils.getCorrelationId(), "token": hp.Utils.getSession().sessionToken, "transactionId": res.transactionId, "instrumentId": res.instrumentId, "amount": hp.Utils.getAmount(), "entryType": hp.Utils.defaults.entryType, "__request": res.request } } }; } if (hp.Utils.defaults.paymentType == hp.PaymentType.REFUND) { requestModel = { "refund": { "refundRequest": { "correlationId": hp.Utils.getCorrelationId(), "token": hp.Utils.getSession().sessionToken, "transactionId": res.transactionId, "instrumentId": res.instrumentId, "amount": hp.Utils.getAmount(), "entryType": hp.Utils.defaults.entryType, "__request": res.request } } }; } hp.Utils.makeRequest(requestModel) .then(hp.Utils.buildResultObjectByType) .then(function(promiseResponse) { $this.$parent.trigger("hp.submit", { "type": $this.requestTypes.charge, "res": promiseResponse }); }) .fail(function(promiseResponse) { if (typeof promiseResponse.responseJSON !== "undefined") { promiseResponse = promiseResponse.responseJSON; } $this.$parent.trigger("hp.submit", { "type": $this.requestTypes.error, "res": promiseResponse }); }); }; Code.prototype.handleSubmit = function(data) { var $this = this; if (!data.is_valid) { $this.$parent.trigger("hp.submit", { "type": $this.requestTypes.error, "res": "Bad swipe. Please try again." }); return; } if (data.name_on_card) { $this.formData.nameOnCard = data.name_on_card; } if (data.card_exp_date_year) { $this.formData.expYear = data.current_year + data.card_exp_date_year; } if (data.card_exp_date_month) { $this.formData.expMonth = data.card_exp_date_month; } if (data.card_number) { $this.formData.cardNumber = $.payment.formatCardNumber(data.card_number); $this.formData.cardType = $.payment.cardType(data.card_number); } $visualcodename.text($this.formData.nameOnCard); $visualcodecc.text($this.formData.cardNumber); $visualcodeyear.text($this.formData.expYear.substring($this.formData.expYear.length - 2)); $visualcodemonth.text($this.formData.expMonth); $this.formData.trackOne = data.track_one; $this.formData.trackTwo = data.track_two; $this.formData.trackThree = data.track_three; $this.formData.ksn = data.ksn; $visualcode.addClass("hp-card-visual-flat-active"); $this.formData._isValid = data.is_valid; $this.formData._isEMoney = data.is_emoney; var cardProperties = {}; if ($this.formData._isValid && $this.formData.ksn !== "" && !$this.formData._isEMoney) { cardProperties = { "trackOne": $this.formData.trackOne, "trackTwo": $this.formData.trackTwo, "trackThree": $this.formData.trackThree, "ksn": $this.formData.ksn }; } if (this.formData._isValid && $this.formData.ksn === "" && !$this.formData._isEMoney) { cardProperties = { "trackOne": $this.formData.trackOne, "trackTwo": $this.formData.trackTwo, "trackThree": "", "ksn": "" }; } if (this.formData._isValid && $this.formData._isEMoney) { cardProperties = { "cardNumber": $this.formData.cardNumber.replace(/\s/gi, ""), "cvv": "999", "expirationDate": $this.formData.expMonth + "/" + $this.formData.expYear, "nameOnCard": $this.formData.nameOnCard }; } hp.Utils.promptAvs().then(function() { return hp.Utils.makeRequest({ "createPaymentInstrument": { "createPaymentInstrumentRequest": { "correlationId": hp.Utils.getCorrelationId(), "transactionId": $this.transactionId, "token": hp.Utils.getSession().sessionToken, "name": $this.formData.nameOnCard, "properties": cardProperties, "billingAddress": { "addressLine1": hp.Utils.defaults.billingAddress.addressLine1, "postalCode": hp.Utils.defaults.billingAddress.postalCode }, "__swipe": $this.formData } } }); }).then(function(res) { if (res.isException) { $this.$parent.trigger("hp.submit", { "type": $this.requestTypes.error, "res": res }); return; } $this.instrumentId = res.instrumentId; $this.transactionId = (typeof res.transactionId !== "undefined") ? res.transactionId : $this.transactionId; hp.Utils.showLoader(); $this.$parent.trigger("hp.submit", { "type": 0, "res": res }); $this.handleCharge(res); }).fail(function(err) { if (typeof err.responseJSON !== "undefined") { err = err.responseJSON; } $this.$parent.trigger("hp.submit", { "type": $this.requestTypes.error, "res": err }); }); }; Code.prototype.handleSuccess = function(res) { hp.Utils.handleSuccess(res); this.showSuccess(); }; Code.prototype.handleError = function(res) { hp.Utils.handleError(res); this.clearInputs(); }; Code.prototype.showSuccess = function(delay) { return hp.Utils.showSuccessPage(delay); }; Code.prototype.isCreditCard = function() { return false; }; Code.prototype.isCode = function() { return true; }; Code.prototype.isBankAccount = function() { return false; }; Code.prototype.isEMoney = function() { return false; }; Code.prototype.isSuccessPage = function() { return false; }; Code.prototype.isTransvault = function() { return false; }; Code.prototype.isGiftCard = function() { return false; }; /* * Export "Code" */ hp.Code = Code; })(jQuery, window, document); (function($, window, document, undefined) { "use strict"; /* * Export "hp" */ window.hp = hp || {}; /* * The default message shown when transactions are in progress... */ var transactionInProgressMessage = "Transaction in progress... Don't refresh!", authorizationInProgressMessage = "Authorization in progress... Don't refresh!", terminalActiveMessage = "Terminal active... Don't refresh!", waitingForSignatureMessage = "Waiting for signature... Don't refresh!", errorMessage = "Declined... Please try again.", cancelMessage = "Cancelled... Please try again."; var messages = { "AuthorizationResponse": authorizationInProgressMessage, "BeginSale": transactionInProgressMessage, "Login": terminalActiveMessage, "LoginSuccess": terminalActiveMessage, "ExecuteCommand": terminalActiveMessage, "DisplayAmount": transactionInProgressMessage, "DisplayForm": transactionInProgressMessage, "FindTermsAndConditions": transactionInProgressMessage, "InsertOrSwipe": transactionInProgressMessage, "Idle": transactionInProgressMessage, "Offline": errorMessage, "ProcessingError": errorMessage, "ReadCardRequest": transactionInProgressMessage, "SetEmvPaymentType": authorizationInProgressMessage, "Gratuity": waitingForSignatureMessage, "CardInserted": authorizationInProgressMessage, "CardRemoved": authorizationInProgressMessage, "WaitingForSignature": waitingForSignatureMessage, "DownloadingSignature": waitingForSignatureMessage, "Signature": waitingForSignatureMessage, "SignatureBlocks": waitingForSignatureMessage, "StopTransaction": authorizationInProgressMessage, "TermsAndConditions": authorizationInProgressMessage, "Cancelled": cancelMessage, "Connected": terminalActiveMessage, "Declined" : errorMessage, "Error" : errorMessage }; var getMessage = function(event) { var eventName = "Idle"; var eventValue = ""; if (event !== undefined && event !== null) { if (event.STATE !== undefined && event.STATE !== null) { eventName = event.STATE; } if (event.INFO !== undefined && event.INFO !== null) { eventName = event.INFO; } if (event.Message !== undefined && event.Message !== null) { eventName = event.Message; } if (event.GA !== undefined && event.GA !== null) { eventName = "Gratuity"; } if (event.OR !== undefined && event.OR !== null) { eventName = event.OR; if (eventName === "SUCCESS") { eventName = "AuthorizationResponse"; } if (eventName === "DECLINED") { eventName = "Declined"; } if (eventName === "CANCELLED") { eventName = "Cancelled"; } } } eventName = eventName.replace(/\s/gi, ""); eventValue = messages[eventName]; hp.Utils.log(eventName, eventValue); return { key: eventName, value: eventValue }; }; var getMessageKeyColor = function(message) { var result = ""; switch (message) { case transactionInProgressMessage: result = "red"; break; case authorizationInProgressMessage: result = "red"; break; case terminalActiveMessage: result = "#0062CC"; break; case waitingForSignatureMessage: result = "#0062CC"; break; case errorMessage: result = "red"; break; default: result = "#000000"; } return result; }; /* * Transvault Class */ function Transvault($element) { this.context = null; this.$parent = null; this.$content = null; this.$element = $element; this.hasSuccess = false; this.browserId = null; this.transactionId = ""; this.formData = { _isValid: false }; } Transvault.prototype.init = function() { // utils call var context = hp.Utils.handleLegacyCssClassApplication("transvault", this.$element), $parent = context.parent, $content = context.content; // Clean parent, notify on complete. $parent .trigger("hp.notify"); this.context = context; this.$parent = $parent; this.$content = $content; this.transvaultHub = $.connection.transvaultHub; this.shouldConnect = true; this.$btn = null; this.terminalId = hp.Utils.getTerminalId(); this.connectionId = "0"; this.correlationId = ""; this.transactionId = hp.Utils.defaults.transactionId; }; Transvault.prototype.createTemplate = function() { if (hp.Utils.defaults.paymentTypeOrder.indexOf(3) < 0) { return ""; } var $html = [ '<div class="hp-transvault-visual">', '<a class="hp-submit-refresh" href="javascript:;" title="Refresh Transvault">', '<img class="hp-submit-refresh-img" src="https://cdn.rawgit.com/etsms/0f62d83b5d3bf18ba57cb14648d913ac/raw/c5f48f7882ad1f48196450fa296caf05f674f48b/refresh-icon.svg" alt="Refresh Transvault Button" />', '</a>', '<div class="hp-transvault-visual-image {{isAlt}}">', '<img class="event event-default" src="https://cdn.rawgit.com/etsms/786cb7bdd1d077acc10d7d7e08a4241f/raw/58a2ec726610c18c21716ae6023f7c6d776b5a71/terminal-loading.svg" alt="Status" />', '</div>', '<p class="hp-input-transvault-message {{isAlt}}">', 'Disconnected <span></span>', '</p>', '<button class="hp-submit hp-submit-danger">Cancel Request</button>', '</div>' ].join(""); $html = $html.replace(/{{isAlt}}/gi, (hp.Utils.getTerminalId().startsWith("1") || hp.Utils.getTerminalId().startsWith("3")) ? "alt" : ""); return $html; }; Transvault.prototype.detachEvents = function() { this.$parent.off("hp.transvaultSuccess"); this.$parent.off("hp.transvaultError"); this.$parent.off("hp.transvaultProgress"); this.$parent.find(".hp-submit").off(); this.$parent.trigger("hp.notify"); this.$parent.find(".hp-submit-refresh").off(); try { this.transvaultHub.connection.stop(); } catch (e) { } }; Transvault.prototype.attachEvents = function() { this.detachEvents(); var $this = this; $this.transvaultHub.connection.url = hp.Utils.defaults.baseUrl + "/transvault"; $this.setupWebockets(); $this.$parent.find(".hp-submit-refresh").on("click", hp.Utils.reset); $this.$parent.find(".hp-submit").on("click", function(e) { e.preventDefault(); $this.cancelTransaction(); $(this).attr("disabled", "disabled").text("Canceling..."); $this.setMessage("Canceling transaction"); }); }; Transvault.prototype.onMessage = function(response) { var messageObject = getMessage(response); var eventKey = messageObject.key; var eventMessage = messageObject.value; var el = this.setMessage(eventMessage); el.css("color", getMessageKeyColor(eventMessage)); if (eventKey === "AuthorizationResponse") { this.onSuccess(response); return; } if (eventMessage === waitingForSignatureMessage) { hp.Utils.showLoader(); return; } if (eventMessage === cancelMessage) { this.onCancelled(); return; } if (eventMessage === errorMessage) { this.onError(response); return; } }; Transvault.prototype.onSuccess = function(response) { var $this = this, props = response; if (!props.ACCT) { props.ACCT = ""; } if (!props.AN) { props.AN = ""; } if (!props.AC) { props.AC = ""; } if (!props.PM) { props.PM = "Other"; } if (!props.SD) { props.SD = "https://images.pmoney.com/00000000"; } else { props.SD = props.SD.toLowerCase(); } if (!props.CRDT) { props.CRDT = ""; } else { props.CRDT = props.CRDT .toUpperCase() .replace("ETS", ""); } if (!props.RD) { props.RD = ""; } if (!props.CEM) { props.CEM = ""; } else { props.CEM = props.CEM .replace(/\s/gi, "_") .toUpperCase(); } if (!props.EMV_APAN) { props.EMV_APAN = ""; } if (!props.EMV_APN) { props.EMV_APN = ""; } if (!props.CHN) { props.CHN = ""; } if (!props.EMV_AID) { props.EMV_AID = ""; } if (!props.EMV_TVR) { props.EMV_TVR = ""; } if (!props.EMV_IAD) { props.EMV_IAD = ""; } if (!props.EMV_TSI) { props.EMV_TSI = ""; } if (!props.EMV_ARC) { props.EMV_ARC = ""; } if (!props.EMV_TA) { props.EMV_TA = ""; } if (!props.TCCT) { props.TCCT = "USD$"; } if (!props.EMD) { props.EMD = ""; } else { props.EMD = props.EMD .replace(/\s/gi, "_") .toUpperCase(); } if (!props.CVMD) { props.CVMD = ""; } if (!props.TT) { props.TT = "PURCHASE"; } if (!props.VA) { props.VA = 0; } else { if (typeof props.VA === "string") { props.VA = +(props.VA.replace("$", "")); } else { props.VA = +(props.VA); } } if (!props.GA) { props.GA = 0; } else { if (typeof props.GA === "string") { props.GA = +(props.GA.replace("$", "")); } else { props.GA = +(props.GA); } } if (!props.TAX) { props.TAX = 0; } else { if (typeof props.TAX === "string") { props.TAX = +(props.TAX.replace("$", "")); } else { props.TAX = +(props.TAX); } } if (!props.CBA) { props.CBA = 0; } else { if (typeof props.CBA === "string") { props.CBA = +(props.CBA.replace("$", "")); } else { props.CBA = +(props.CBA); } } if (!props.SA) { props.SA = 0; } else { if (typeof props.SA === "string") { props.SA = +(props.SA.replace("$", "")); } else { props.SA = +(props.SA); } } if (!props.ED) { props.ED = ""; } else { var year = (new Date().getFullYear().toString().substring(0, 2)) + props.ED.substr(2); var month = props.ED.substr(0, 2); props.ED = month + "/" + year; } if (props.AN === "" && props.EMV_APAN !== "") { props.AN = props.EMV_APAN; } if (props.AN !== "") { props.AN = props.AN.replace(/\*|\X|\x/gi, ""); } if (props.AN.length > 4) { props.AN = props.AN.substr(props.AN.length - 4); } if (props.EMV_APN !== "") { props.CHN = props.EMV_APN; } var successResponse = { "status": "Success", "message": $.trim(props.RD), "amount": props.TA, "token": hp.Utils.getSession().sessionToken, "anti_forgery_token": hp.Utils.defaults.antiForgeryToken, "transaction_id": props.ETT, "transaction_approval_code": props.AC, "transaction_avs_street_passed": true, "transaction_avs_postal_code_passed": true, "transaction_currency": props.TCCT, "transaction_status_indicator": props.EMV_TSI, "transaction_type": props.TT, "transaction_tax": props.TAX, "transaction_surcharge": props.SA, "transaction_gratuity": props.GA, "transaction_cashback": props.CBA, "transaction_total": props.VA, "instrument_id": props.ACCT, "instrument_type": props.CRDT, "instrument_method": props.PM, "instrument_last_four": props.AN, "instrument_routing_last_four": "", "instrument_expiration_date": props.ED, "instrument_verification_method": props.CVMD, "instrument_entry_type": props.CEM, "instrument_entry_type_description": props.EMD, "instrument_verification_results": props.EMV_TVR, "created_on": (new Date()).toISOString(), "customer_name": props.CHN, "customer_signature": props.SD, "correlation_id": $this.correlationId, "application_identifier": props.EMV_AID, "application_response_code": props.EMV_ARC, "application_issuer_data": props.EMV_IAD }; $this.$parent.trigger("hp.transvaultSuccess", successResponse); $this.hasSuccess = true; sessionStorage.clear(); }; Transvault.prototype.setMessage = function(message) { var el = this.$parent.find(".hp-input-transvault-message"); el.text(message); return el; }; Transvault.prototype.cancelTransaction = function(shouldNotNotify) { var token = hp.Utils.getSession().sessionToken, correlationId = hp.Utils.getCorrelationId(), deferred = jQuery.Deferred(); if (typeof shouldNotNotify !== "undefined") { shouldNotNotify = true; } var $this = this; hp.Utils.makeRequest({ "transvault": { "transvaultRequest": { "token": token, "amount": hp.Utils.getAmount(), "transactionId": $this.transactionId, "terminalId": $this.terminalId, "action": "CANCEL", "browserId": $this.browserId, "correlationId": "HP:FROM-GUI", "ipAddress": hp.Utils.getIpAddress() } } }).then(function(){ if (!shouldNotNotify) { $this.onCancelled(); } deferred.resolve(); }, deferred.reject); return deferred; }; Transvault.prototype.onCancelled = function() { this.$parent.find(".event-default").hide(); this.$parent.find(".hp-submit").hide(); var $this = this; setTimeout(function() { var createdOn = (new Date()).toISOString(); var sessionId = hp.Utils.getSession().sessionId; var message = "Transaction Cancelled."; hp.Utils.showError("Transaction Cancelled."); if (!hp.Utils.shouldErrorPostBack()) { hp.Utils.defaults.errorCallback({ "status": "Error", "message": message, "created_on": createdOn, "token": sessionId }); } try { $this.transvaultHub.connection.stop(); } catch (e) { } }, 50); }; Transvault.prototype.onError = function(response) { this.$parent.find(".event-default").hide(); this.$parent.find(".hp-submit").hide(); var $this = this; setTimeout(function() { var createdOn = (new Date()).toISOString(); var sessionId = hp.Utils.getSession().sessionId; var message = "Transaction Declined."; hp.Utils.showError("Transaction Declined."); if (!hp.Utils.shouldErrorPostBack()) { hp.Utils.defaults.errorCallback({ "status": "Error", "message": message, "created_on": createdOn, "token": sessionId }); } try { $this.transvaultHub.connection.stop(); } catch (e) { } }, 50); }; Transvault.prototype.setupWebockets = function(amount) { var $this = this, $message = $this.$parent.find(".hp-input-transvault-message"), token = hp.Utils.getSession().sessionToken; amount = amount || hp.Utils.getAmount(); $this.correlationId = hp.Utils.getCorrelationId(); if (!$this.shouldConnect) { return; } var messageHandler = function(response) { $this.onMessage(response); }; var reconnectHandler = function(response) { hp.Utils.log("Transvault: Connection error!"); setTimeout(function() { hp.Utils.log("Transvault: Connection reconnecting..."); $message.css("color", "#FDFDFD").text("Reconnecting in 5 seconds..."); location.href = location.href; }, 15000); }; var errorHandler = function(response) { if (response) { $message.css("color", "#FC5F45").text(response); return; } $message.css("color", "#FC5F45").text("Could not connect!"); reconnectHandler(response); }; $message.off("click").removeClass("hp-input-transvault-message-btn").text("Connecting"); hp.Utils.log("Transvault: Addding events..."); $this.transvaultHub.off("onMessage").on("onMessage", messageHandler); try { $this.transvaultHub.connection .start({ withCredentials: false, jsonp: true }) .done(function() { $(".hp-input-transvault-message") .text("Connected (listening)...") .css("color", "#F4854A"); hp.Utils.log("Your connection ID: " + $.connection.hub.id); $this.browserId = $.connection.hub.id; hp.Utils.makeRequest({ "transvault": { "transvaultRequest": { "token": token, "amount": amount, "transactionId": $this.transactionId, "correlationId": $this.correlationId, "entryType": hp.Utils.defaults.entryType, "terminalId": $this.terminalId, "action": hp.Utils.defaults.paymentType, "browserId": $this.browserId, "ipAddress": hp.Utils.getIpAddress() } } }).then(function(res) { $this.$parent.trigger("hp.transvaultProgress"); }, function(err) { $this.$parent.trigger("hp.transvaultError", err.responseJSON); errorHandler(); }); }) .fail(errorHandler); $this.transvaultHub.connection.error(reconnectHandler); $this.transvaultHub.connection.disconnected(reconnectHandler); } catch (error) { reconnectHandler("An unknown exception occurred. Reconnecting..."); } $this.$parent.trigger("hp.notify"); }; Transvault.prototype.showSuccess = function(delay) { hp.Utils.showSuccessPage(delay); }; Transvault.prototype.isCreditCard = function() { return false; }; Transvault.prototype.isBankAccount = function() { return false; }; Transvault.prototype.isEMoney = function() { return false; }; Transvault.prototype.isSuccessPage = function() { return false; }; Transvault.prototype.isCode = function() { return false; }; Transvault.prototype.isTransvault = function() { return true; }; Transvault.prototype.isGiftCard = function() { return false; }; /* * Export "Transvault" */ hp.Transvault = Transvault; })(jQuery, window, document); // Generated by CoffeeScript 1.7.1 (function() { var $, cardFromNumber, cardFromType, cards, defaultFormat, formatBackCardNumber, formatBackExpiry, formatCardNumber, formatExpiry, formatForwardExpiry, formatForwardSlashAndSpace, hasTextSelected, luhnCheck, reFormatCVC, reFormatCardNumber, reFormatExpiry, reFormatNumeric, replaceFullWidthChars, restrictCVC, restrictCardNumber, restrictExpiry, restrictNumeric, safeVal, setCardType, __slice = [].slice, __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }; $ = window.jQuery || window.Zepto || window.$; $.payment = {}; $.payment.fn = {}; $.fn.payment = function() { var args, method; method = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; return $.payment.fn[method].apply(this, args); }; defaultFormat = /(\d{1,4})/g; $.payment.cards = cards = [ { type: 'elo', patterns: [401178, 401179, 431274, 438935, 451416, 457393, 457631, 457632, 504175, 506699, 5067, 509, 627780, 636297, 636368, 650, 6516, 6550], format: defaultFormat, length: [16], cvcLength: [3], luhn: true }, { type: 'maestro', patterns: [5018, 502, 503, 506, 56, 58, 639, 6220, 67], format: defaultFormat, length: [12, 13, 14, 15, 16, 17, 18, 19], cvcLength: [3], luhn: true }, { type: 'forbrugsforeningen', patterns: [600], format: defaultFormat, length: [16], cvcLength: [3], luhn: true }, { type: 'dankort', patterns: [5019], format: defaultFormat, length: [16], cvcLength: [3], luhn: true }, { type: 'visa', patterns: [4], format: defaultFormat, length: [13, 16], cvcLength: [3], luhn: true }, { type: 'emoney', patterns: [627571], format: defaultFormat, length: [16], cvcLength: [3], luhn: true }, { type: 'mastercard', patterns: [51, 52, 53, 54, 55, 22, 23, 24, 25, 26, 27], format: defaultFormat, length: [16], cvcLength: [3], luhn: true }, { type: 'amex', patterns: [34, 37], format: /(\d{1,4})(\d{1,6})?(\d{1,5})?/, length: [15], cvcLength: [3, 4], luhn: true }, { type: 'dinersclub', patterns: [30, 36, 38, 39], format: /(\d{1,4})(\d{1,6})?(\d{1,4})?/, length: [14], cvcLength: [3], luhn: true }, { type: 'discover', patterns: [60, 64, 65, 622], format: defaultFormat, length: [16], cvcLength: [3], luhn: true }, { type: 'unionpay', patterns: [62, 88], format: defaultFormat, length: [16, 17, 18, 19], cvcLength: [3], luhn: false }, { type: 'jcb', patterns: [35], format: defaultFormat, length: [16], cvcLength: [3], luhn: true } ]; cardFromNumber = function(num) { var card, p, pattern, _i, _j, _len, _len1, _ref; num = (num + '').replace(/\D/g, ''); for (_i = 0, _len = cards.length; _i < _len; _i++) { card = cards[_i]; _ref = card.patterns; for (_j = 0, _len1 = _ref.length; _j < _len1; _j++) { pattern = _ref[_j]; p = pattern + ''; if (num.substr(0, p.length) === p) { return card; } } } }; cardFromType = function(type) { var card, _i, _len; for (_i = 0, _len = cards.length; _i < _len; _i++) { card = cards[_i]; if (card.type === type) { return card; } } }; luhnCheck = function(num) { var digit, digits, odd, sum, _i, _len; odd = true; sum = 0; digits = (num + '').split('').reverse(); for (_i = 0, _len = digits.length; _i < _len; _i++) { digit = digits[_i]; digit = parseInt(digit, 10); if ((odd = !odd)) { digit *= 2; } if (digit > 9) { digit -= 9; } sum += digit; } return sum % 10 === 0; }; hasTextSelected = function($target) { var _ref; if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== $target.prop('selectionEnd')) { return true; } if ((typeof document !== "undefined" && document !== null ? (_ref = document.selection) != null ? _ref.createRange : void 0 : void 0) != null) { if (document.selection.createRange().text) { return true; } } return false; }; safeVal = function(value, $target) { var currPair, cursor, digit, error, last, prevPair; try { cursor = $target.prop('selectionStart'); } catch (_error) { error = _error; cursor = null; } last = $target.val(); $target.val(value); if (cursor !== null && $target.is(":focus")) { if (cursor === last.length) { cursor = value.length; } if (last !== value) { prevPair = last.slice(cursor - 1, +cursor + 1 || 9e9); currPair = value.slice(cursor - 1, +cursor + 1 || 9e9); digit = value[cursor]; if (/\d/.test(digit) && prevPair === ("" + digit + " ") && currPair === (" " + digit)) { cursor = cursor + 1; } } $target.prop('selectionStart', cursor); return $target.prop('selectionEnd', cursor); } }; replaceFullWidthChars = function(str) { var chars, chr, fullWidth, halfWidth, idx, value, _i, _len; if (str == null) { str = ''; } fullWidth = '\uff10\uff11\uff12\uff13\uff14\uff15\uff16\uff17\uff18\uff19'; halfWidth = '0123456789'; value = ''; chars = str.split(''); for (_i = 0, _len = chars.length; _i < _len; _i++) { chr = chars[_i]; idx = fullWidth.indexOf(chr); if (idx > -1) { chr = halfWidth[idx]; } value += chr; } return value; }; reFormatNumeric = function(e) { var $target; $target = $(e.currentTarget); return setTimeout(function() { var value; value = $target.val(); value = replaceFullWidthChars(value); value = value.replace(/\D/g, ''); return safeVal(value, $target); }); }; reFormatCardNumber = function(e) { var $target; $target = $(e.currentTarget); return setTimeout(function() { var value; value = $target.val(); value = replaceFullWidthChars(value); value = $.payment.formatCardNumber(value); return safeVal(value, $target); }); }; formatCardNumber = function(e) { var $target, card, digit, length, re, upperLength, value; digit = String.fromCharCode(e.which); if (!/^\d+$/.test(digit)) { return; } $target = $(e.currentTarget); value = $target.val(); card = cardFromNumber(value + digit); length = (value.replace(/\D/g, '') + digit).length; upperLength = 16; if (card) { upperLength = card.length[card.length.length - 1]; } if (length >= upperLength) { return; } if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) { return; } if (card && card.type === 'amex') { re = /^(\d{4}|\d{4}\s\d{6})$/; } else { re = /(?:^|\s)(\d{4})$/; } if (re.test(value)) { e.preventDefault(); return setTimeout(function() { return $target.val(value + ' ' + digit); }); } else if (re.test(value + digit)) { e.preventDefault(); return setTimeout(function() { return $target.val(value + digit + ' '); }); } }; formatBackCardNumber = function(e) { var $target, value; $target = $(e.currentTarget); value = $target.val(); if (e.which !== 8) { return; } if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) { return; } if (/\d\s$/.test(value)) { e.preventDefault(); return setTimeout(function() { return $target.val(value.replace(/\d\s$/, '')); }); } else if (/\s\d?$/.test(value)) { e.preventDefault(); return setTimeout(function() { return $target.val(value.replace(/\d$/, '')); }); } }; reFormatExpiry = function(e) { var $target; $target = $(e.currentTarget); return setTimeout(function() { var value; value = $target.val(); value = replaceFullWidthChars(value); value = $.payment.formatExpiry(value); return safeVal(value, $target); }); }; formatExpiry = function(e) { var $target, digit, val; digit = String.fromCharCode(e.which); if (!/^\d+$/.test(digit)) { return; } $target = $(e.currentTarget); val = $target.val() + digit; if (/^\d$/.test(val) && (val !== '0' && val !== '1')) { e.preventDefault(); return setTimeout(function() { return $target.val("0" + val + " / "); }); } else if (/^\d\d$/.test(val)) { e.preventDefault(); return setTimeout(function() { var m1, m2; m1 = parseInt(val[0], 10); m2 = parseInt(val[1], 10); if (m2 > 2 && m1 !== 0) { return $target.val("0" + m1 + " / " + m2); } else { return $target.val("" + val + " / "); } }); } }; formatForwardExpiry = function(e) { var $target, digit, val; digit = String.fromCharCode(e.which); if (!/^\d+$/.test(digit)) { return; } $target = $(e.currentTarget); val = $target.val(); if (/^\d\d$/.test(val)) { return $target.val("" + val + " / "); } }; formatForwardSlashAndSpace = function(e) { var $target, val, which; which = String.fromCharCode(e.which); if (!(which === '/' || which === ' ')) { return; } $target = $(e.currentTarget); val = $target.val(); if (/^\d$/.test(val) && val !== '0') { return $target.val("0" + val + " / "); } }; formatBackExpiry = function(e) { var $target, value; $target = $(e.currentTarget); value = $target.val(); if (e.which !== 8) { return; } if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) { return; } if (/\d\s\/\s$/.test(value)) { e.preventDefault(); return setTimeout(function() { return $target.val(value.replace(/\d\s\/\s$/, '')); }); } }; reFormatCVC = function(e) { var $target; $target = $(e.currentTarget); return setTimeout(function() { var value; value = $target.val(); value = replaceFullWidthChars(value); value = value.replace(/\D/g, '').slice(0, 4); return safeVal(value, $target); }); }; restrictNumeric = function(e) { var input; if (e.metaKey || e.ctrlKey) { return true; } if (e.which === 32) { return false; } if (e.which === 0) { return true; } if (e.which < 33) { return true; } input = String.fromCharCode(e.which); return !!/[\d\s]/.test(input); }; restrictCardNumber = function(e) { var $target, card, digit, value; $target = $(e.currentTarget); digit = String.fromCharCode(e.which); if (!/^\d+$/.test(digit)) { return; } if (hasTextSelected($target)) { return; } value = ($target.val() + digit).replace(/\D/g, ''); card = cardFromNumber(value); if (card) { return value.length <= card.length[card.length.length - 1]; } else { return value.length <= 16; } }; restrictExpiry = function(e) { var $target, digit, value; $target = $(e.currentTarget); digit = String.fromCharCode(e.which); if (!/^\d+$/.test(digit)) { return; } if (hasTextSelected($target)) { return; } value = $target.val() + digit; value = value.replace(/\D/g, ''); if (value.length > 6) { return false; } }; restrictCVC = function(e) { var $target, digit, val; $target = $(e.currentTarget); digit = String.fromCharCode(e.which); if (!/^\d+$/.test(digit)) { return; } if (hasTextSelected($target)) { return; } val = $target.val() + digit; return val.length <= 4; }; setCardType = function(e) { var $target, allTypes, card, cardType, val; $target = $(e.currentTarget); val = $target.val(); cardType = $.payment.cardType(val) || 'unknown'; if (!$target.hasClass(cardType)) { allTypes = (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = cards.length; _i < _len; _i++) { card = cards[_i]; _results.push(card.type); } return _results; })(); $target.removeClass('unknown'); $target.removeClass(allTypes.join(' ')); $target.addClass(cardType); $target.toggleClass('identified', cardType !== 'unknown'); return $target.trigger('payment.cardType', cardType); } }; $.payment.fn.formatCardCVC = function() { this.on('keypress', restrictNumeric); this.on('keypress', restrictCVC); this.on('paste', reFormatCVC); this.on('change', reFormatCVC); this.on('input', reFormatCVC); return this; }; $.payment.fn.formatCardExpiry = function() { this.on('keypress', restrictNumeric); this.on('keypress', restrictExpiry); this.on('keypress', formatExpiry); this.on('keypress', formatForwardSlashAndSpace); this.on('keypress', formatForwardExpiry); this.on('keydown', formatBackExpiry); this.on('change', reFormatExpiry); this.on('input', reFormatExpiry); return this; }; $.payment.fn.formatCardNumber = function() { this.on('keypress', restrictNumeric); this.on('keypress', restrictCardNumber); this.on('keypress', formatCardNumber); this.on('keydown', formatBackCardNumber); this.on('keyup', setCardType); this.on('paste', reFormatCardNumber); this.on('change', reFormatCardNumber); this.on('input', reFormatCardNumber); this.on('input', setCardType); return this; }; $.payment.fn.restrictNumeric = function() { this.on('keypress', restrictNumeric); this.on('paste', reFormatNumeric); this.on('change', reFormatNumeric); this.on('input', reFormatNumeric); return this; }; $.payment.fn.cardExpiryVal = function() { return $.payment.cardExpiryVal($(this).val()); }; $.payment.cardExpiryVal = function(value) { var month, prefix, year, _ref; _ref = value.split(/[\s\/]+/, 2), month = _ref[0], year = _ref[1]; if ((year != null ? year.length : void 0) === 2 && /^\d+$/.test(year)) { prefix = (new Date).getFullYear(); prefix = prefix.toString().slice(0, 2); year = prefix + year; } month = parseInt(month, 10); year = parseInt(year, 10); return { month: month, year: year }; }; $.payment.validateCardNumber = function(num) { var card, _ref; num = (num + '').replace(/\s+|-/g, ''); if (!/^\d+$/.test(num)) { return false; } card = cardFromNumber(num); if (!card) { return false; } return (_ref = num.length, __indexOf.call(card.length, _ref) >= 0) && (card.luhn === false || luhnCheck(num)); }; $.payment.validateCardExpiry = function(month, year) { var currentTime, expiry, _ref; if (typeof month === 'object' && 'month' in month) { _ref = month, month = _ref.month, year = _ref.year; } if (!(month && year)) { return false; } month = $.trim(month); year = $.trim(year); if (!/^\d+$/.test(month)) { return false; } if (!/^\d+$/.test(year)) { return false; } if (!((1 <= month && month <= 12))) { return false; } if (year.length === 2) { if (year < 70) { year = "20" + year; } else { year = "19" + year; } } if (year.length !== 4) { return false; } expiry = new Date(year, month); currentTime = new Date; expiry.setMonth(expiry.getMonth() - 1); expiry.setMonth(expiry.getMonth() + 1, 1); return expiry > currentTime; }; $.payment.validateCardCVC = function(cvc, type) { var card, _ref; cvc = $.trim(cvc); if (!/^\d+$/.test(cvc)) { return false; } card = cardFromType(type); if (card != null) { return _ref = cvc.length, __indexOf.call(card.cvcLength, _ref) >= 0; } else { return cvc.length >= 3 && cvc.length <= 4; } }; $.payment.cardType = function(num) { var _ref; if (!num) { return null; } return ((_ref = cardFromNumber(num)) != null ? _ref.type : void 0) || null; }; $.payment.formatCardNumber = function(num) { var card, groups, upperLength, _ref; num = num.replace(/\D/g, ''); card = cardFromNumber(num); if (!card) { return num; } upperLength = card.length[card.length.length - 1]; num = num.slice(0, upperLength); if (card.format.global) { return (_ref = num.match(card.format)) != null ? _ref.join(' ') : void 0; } else { groups = card.format.exec(num); if (groups == null) { return; } groups.shift(); groups = $.grep(groups, function(n) { return n; }); return groups.join(' '); } }; $.payment.formatExpiry = function(expiry) { var mon, parts, sep, year; parts = expiry.match(/^\D*(\d{1,2})(\D+)?(\d{1,4})?/); if (!parts) { return ''; } mon = parts[1] || ''; sep = parts[2] || ''; year = parts[3] || ''; if (year.length > 0) { sep = ' / '; } else if (sep === ' /') { mon = mon.substring(0, 1); sep = ''; } else if (mon.length === 2 || sep.length > 0) { sep = ' / '; } else if (mon.length === 1 && (mon !== '0' && mon !== '1')) { mon = "0" + mon; sep = ' / '; } return mon + sep + year; }; }).call(this); (function($) { var defaults = {} $.fn.pos = function(options) { //define instance for use in child functions var $this = $(this), cardNumberRegex = new RegExp(/^(?:%B|\;)([0-9]+)/ig), nameOnCardRegex = new RegExp(/(?:\^(.*)\^)/ig), expirationDateRegex = new RegExp(/(?:\^(?:.*)\^|=)(\d{4})/ig), trackRegex = new RegExp(/\|([A-Z0-9]+)(?=\|)/ig), unencryptedTrackRegex = new RegExp(/^(.*?\?)(;.*)/ig), hasTrack = false; var data = { swipe: '' }; //set default options defaults = { swipe: true, onEventName: "hp.global_swipped_start", offEventName: "hp.global_swipped_end", onScanSwipe: $.noop }; // helper var hasValue = function(match, index) { var result = false; try { result = typeof match[index] !== "undefined"; } catch (err) {} return result; } //extend options $this.options = $.extend(true, {}, defaults, options); $this.off("keypress").on("keypress", function(event) { if ($this.options.swipe) { if (event.which != 13) { data.swipe += String.fromCharCode(event.which); if (data.swipe.length == 2 && data.swipe == "%B") { $this.trigger($this.options.onEventName); } return; } var result = { track_one: "", track_two: "", track_three: "", ksn: "", card_number: "", name_on_card: "", card_exp_date_month: "", card_exp_date_year: "", is_valid: true, is_emoney: false, current_year: new Date().getFullYear().toString().substring(0, 2) }; var parsedCardNumberResult = cardNumberRegex.exec(data.swipe), parsedNameOnCardResult = nameOnCardRegex.exec(data.swipe), parsedExpirationDateResult = expirationDateRegex.exec(data.swipe), parsedTrackResult = data.swipe.match(trackRegex), parsedUnencryptedResult = unencryptedTrackRegex.exec(data.swipe); // Assign card number result: if (parsedCardNumberResult != null && parsedCardNumberResult.length) { result.card_number = parsedCardNumberResult[1]; } // Assign name on card result: if (parsedNameOnCardResult != null && parsedNameOnCardResult.length) { var name = parsedNameOnCardResult[1]; if (name.indexOf(",") === -1) { name = name.replace(/\/+|\d+/gi, " "); } else { name = $.trim(name.replace(/\//gi, " ").replace(/\W+/gi, " ")); } if (name.split(" ").length > 2) { name = name.split(" ")[1] + " " + name.split(" ")[2] + " " + name.split(" ")[0]; } else { name = name.split(" ")[1] + " " + name.split(" ")[0]; } result.name_on_card = name; } // Assign expiration date result: if (parsedExpirationDateResult != null && parsedExpirationDateResult.length) { var date = parsedExpirationDateResult[1], year = date.substring(0, 2), month = date.substring(2); // current century : new Date().getFullYear().toString().substring(0, 2) result.card_exp_date_year = year; result.card_exp_date_month = month; } // Clean matches if (parsedTrackResult != null && parsedTrackResult.length) { parsedTrackResult = parsedTrackResult.map(function(match) { return match.replace("|", ""); }); // Assign track one result: if (hasValue(parsedTrackResult, 1)) { result.track_one = parsedTrackResult[1]; } // Assign track two result: if (hasValue(parsedTrackResult, 2)) { result.track_two = parsedTrackResult[2]; } // Assign track three result: if (parsedTrackResult.length >= 10 && hasValue(parsedTrackResult, 3)) { result.track_three = parsedTrackResult[3]; } // Assign ksn result: if (parsedTrackResult.length >= 10 && hasValue(parsedTrackResult, 8)) { result.ksn = parsedTrackResult[8]; } else if (parsedTrackResult.length === 9) { result.ksn = parsedTrackResult[7]; } } else if (parsedUnencryptedResult != null && parsedUnencryptedResult.length >= 3) { result.track_one = parsedUnencryptedResult[1]; result.track_two = parsedUnencryptedResult[2]; } else { result.is_valid = false; } if (event.which == 13) { // Handles Gift Card Scan if (!result.is_valid && result.card_number.indexOf("627571") !== -1) { result.is_valid = true; result.is_emoney = true; result.name_on_card = "EMoney Card"; result.card_exp_date_year = (+(new Date().getFullYear().toString().substring(2)) + 9).toString(); result.card_exp_date_month = "12"; } if (data.swipe.indexOf("%E?") !== -1 || data.swipe.indexOf("+E?") !== -1 || data.swipe.indexOf(";E?") !== -1) { result.is_valid = false; } if (result.name_on_card === "") { result.name_on_card = "Unknown Card"; } result.name_on_card = $.trim(result.name_on_card.replace("undefined", "")); $this.trigger($this.options.offEventName, result); $this.options.onScanSwipe(result); data.swipe = ''; } } }); }; })(jQuery); // Generated by CoffeeScript 1.4.0 (function() { var $; $ = window.jQuery || window.Zepto || window.$; $.fn.fancySelect = function(opts) { var isiOS, settings; if (opts == null) { opts = {}; } settings = $.extend({ forceiOS: false, includeBlank: false, optionTemplate: function(optionEl) { return optionEl.text(); }, triggerTemplate: function(optionEl) { return optionEl.text(); } }, opts); isiOS = !!navigator.userAgent.match(/iP(hone|od|ad)/i); return this.each(function() { var copyOptionsToList, disabled, options, sel, trigger, updateTriggerText, wrapper; sel = $(this); if (sel.hasClass('fancified') || sel[0].tagName !== 'SELECT') { return; } sel.addClass('fancified'); sel.css({ width: 1, height: 1, display: 'block', position: 'absolute', top: 0, left: 0, opacity: 0 }); sel.wrap('<div class="fancy-select">'); wrapper = sel.parent(); if (sel.data('class')) { wrapper.addClass(sel.data('class')); } wrapper.append('<div class="trigger">'); if (!(isiOS && !settings.forceiOS)) { wrapper.append('<ul class="options">'); } trigger = wrapper.find('.trigger'); options = wrapper.find('.options'); disabled = sel.prop('disabled'); if (disabled) { wrapper.addClass('disabled'); } updateTriggerText = function() { var triggerHtml; triggerHtml = settings.triggerTemplate(sel.find(':selected')); return trigger.html(triggerHtml); }; sel.on('blur.fs', function() { if (trigger.hasClass('open')) { return setTimeout(function() { return trigger.trigger('close.fs'); }, 120); } }); trigger.on('close.fs', function() { trigger.removeClass('open'); return options.removeClass('open'); }); trigger.on('click.fs', function() { var offParent, parent; if (!disabled) { trigger.toggleClass('open'); if (isiOS && !settings.forceiOS) { if (trigger.hasClass('open')) { return sel.focus(); } } else { if (trigger.hasClass('open')) { parent = trigger.parent(); offParent = parent.offsetParent(); if ((parent.offset().top + parent.outerHeight() + options.outerHeight() + 20) > $(window).height() + $(window).scrollTop()) { options.addClass('overflowing'); } else { options.removeClass('overflowing'); } } options.toggleClass('open'); if (!isiOS) { return sel.focus(); } } } }); sel.on('enable', function() { sel.prop('disabled', false); wrapper.removeClass('disabled'); disabled = false; return copyOptionsToList(); }); sel.on('disable', function() { sel.prop('disabled', true); wrapper.addClass('disabled'); return disabled = true; }); sel.on('change.fs', function(e) { if (e.originalEvent && e.originalEvent.isTrusted) { return e.stopPropagation(); } else { return updateTriggerText(); } }); sel.on('keydown', function(e) { var hovered, newHovered, w; w = e.which; hovered = options.find('.hover'); hovered.removeClass('hover'); if (!options.hasClass('open')) { if (w === 13 || w === 32 || w === 38 || w === 40) { e.preventDefault(); return trigger.trigger('click.fs'); } } else { if (w === 38) { e.preventDefault(); if (hovered.length && hovered.index() > 0) { hovered.prev().addClass('hover'); } else { options.find('li:last-child').addClass('hover'); } } else if (w === 40) { e.preventDefault(); if (hovered.length && hovered.index() < options.find('li').length - 1) { hovered.next().addClass('hover'); } else { options.find('li:first-child').addClass('hover'); } } else if (w === 27) { e.preventDefault(); trigger.trigger('click.fs'); } else if (w === 13 || w === 32) { e.preventDefault(); hovered.trigger('mousedown.fs'); } else if (w === 9) { if (trigger.hasClass('open')) { trigger.trigger('close.fs'); } } newHovered = options.find('.hover'); if (newHovered.length) { options.scrollTop(0); return options.scrollTop(newHovered.position().top - 12); } } }); options.on('mousedown.fs', 'li', function(e) { var clicked; clicked = $(this); sel.val(clicked.data('raw-value')); if (!isiOS) { sel.trigger('blur.fs').trigger('focus.fs'); } options.find('.selected').removeClass('selected'); clicked.addClass('selected'); trigger.addClass('selected'); return sel.val(clicked.data('raw-value')).trigger('change.fs').trigger('blur.fs').trigger('focus.fs'); }); options.on('mouseenter.fs', 'li', function() { var hovered, nowHovered; nowHovered = $(this); hovered = options.find('.hover'); hovered.removeClass('hover'); return nowHovered.addClass('hover'); }); options.on('mouseleave.fs', 'li', function() { return options.find('.hover').removeClass('hover'); }); copyOptionsToList = function() { var selOpts; updateTriggerText(); if (isiOS && !settings.forceiOS) { return; } selOpts = sel.find('option'); return sel.find('option').each(function(i, opt) { var optHtml; opt = $(opt); if (!opt.prop('disabled') && (opt.val() || settings.includeBlank)) { optHtml = settings.optionTemplate(opt); if (opt.prop('selected')) { return options.append("<li data-raw-value=\"" + (opt.val()) + "\" class=\"selected\">" + optHtml + "</li>"); } else { return options.append("<li data-raw-value=\"" + (opt.val()) + "\">" + optHtml + "</li>"); } } }); }; sel.on('update.fs', function() { wrapper.find('.options').empty(); return copyOptionsToList(); }); return copyOptionsToList(); }); }; }).call(this); /* * jQuery Hosted Payments - v3.6.38 * * Made by Erik Zettersten * Under MIT License */ (function($, window, document, undefined) { var pluginName = "hp", defaults = {}; defaults.version = "v3.6.38"; defaults.amount = 0; defaults.baseUrl = "https://transact.etsemoney.com/hp/v3/adapters"; defaults.defaultCardCharacters = "&middot;&middot;&middot;&middot; &middot;&middot;&middot;&middot; &middot;&middot;&middot;&middot; &middot;&middot;&middot;&middot;"; defaults.defaultDateCharacters = "&middot;&middot;"; defaults.defaultNameOnCardName = "Name On Card"; defaults.defaultNameOnCardNameSwipe = "Swipe/Scan Card"; defaults.defaultName = "Full Name"; defaults.defaultPhone = "800-834-7790"; defaults.defaultErrorLabel = "Declined"; defaults.defaultRedirectLabel = ""; defaults.defaultSuccessLabel = "Transaction Complete!"; defaults.paymentTypeOrder = [0, 1]; defaults.paymentService = hp.PaymentService.EFT; // EFT, EMONEY, TEST defaults.defaultAccountNumberCharacters = "&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;"; defaults.defaultRoutingNumberCharacters = "&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;&middot;"; defaults.correlationId = ""; defaults.successCallback = $.noop; defaults.errorCallback = $.noop; defaults.onSwipeStartCallback = $.noop; defaults.onSwipeEndCallback = $.noop; defaults.onAvsDismissCallback = $.noop; defaults.onErrorDismissCallback = $.noop; defaults.ignoreSubmission = false; defaults.terminalId = ""; defaults.transactionId = hp.Utils.generateGuild(); defaults.instrumentId = ""; defaults.apiKey = ""; defaults.paymentType = hp.PaymentType.CHARGE; // "CHARGE", "REFUND", "CREATE_INSTRUMENT" defaults.entryType = hp.EntryType.KEYED_CARD_NOT_PRESENT; // "DEVICE_CAPTURED", "KEYED_CARD_PRESENT", "KEYED_CARD_NOT_PRESENT" defaults.billingAddress = {}; defaults.billingAddress.addressLine1 = ""; defaults.billingAddress.postalCode = ""; defaults.antiForgeryToken = ""; defaults.antiForgeryName = "__RequestVerificationToken"; defaults.customerName = ""; defaults.promptForAvs = false; defaults.allowAvsSkip = true; defaults.allowHttpsSkip = false; defaults.ipAddress = ""; function Plugin(element, options) { this._name = pluginName; this.element = element; if (typeof options === "undefined") { options = {}; } if (typeof options.entryType !== "undefined") { options.entryType = hp.Utils.setEntryType(options.entryType); } if (typeof options.paymentType !== "undefined") { options.paymentType = hp.Utils.setPaymentType(options.paymentType); } if (typeof options.paymentService !== "undefined") { options.paymentService = hp.Utils.setPaymentService(options.paymentService); } if (typeof options.amount !== "undefined") { options.amount = hp.Utils.setAmount(options.amount); } hp.Utils.defaults = jQuery.extend({}, defaults, options); this.init(); hp.Utils.__instance = this; } /* * Main */ var intialize = function() { var that = this, $element = $(that.element), sessionId = "", apiKey = "", createdOn = (new Date()).toISOString(); if (hp.Utils.getSession().apiKey === "") { if (typeof $element.data("etsKey") !== "undefined") { apiKey = $element.data("etsKey").toString(); hp.Utils.defaults.apiKey = apiKey; } else { apiKey = hp.Utils.defaults.apiKey; } hp.Utils.setSession(apiKey, true); } if (typeof $element.data("transactionId") !== "undefined") { hp.Utils.defaults.transactionId = $element.data("transactionId").toString(); } if (typeof $element.data("avsStreet") !== "undefined") { hp.Utils.defaults.billingAddress.addressLine1 = $element.data("avsStreet").toString(); } if (typeof $element.data("avsZip") !== "undefined") { hp.Utils.defaults.billingAddress.postalCode = $element.data("avsZip").toString(); } if (typeof $element.data("paymentService") !== "undefined") { hp.Utils.defaults.paymentService = hp.Utils.setPaymentService($element.data("paymentService")); } if (typeof $element.data("entryType") !== "undefined") { hp.Utils.defaults.entryType = hp.Utils.setEntryType($element.data("entryType")); } if (typeof $element.data("paymentType") !== "undefined") { hp.Utils.defaults.paymentType = hp.Utils.setPaymentType($element.data("paymentType")); } if (typeof $element.data("promptForAvs") !== "undefined") { hp.Utils.defaults.promptForAvs = $element.data("promptForAvs").toString().toLowerCase() == "false" ? false : true; } if (typeof $element.data("allowAvsSkip") !== "undefined") { hp.Utils.defaults.allowAvsSkip = $element.data("allowAvsSkip").toString().toLowerCase() == "false" ? false : true; } if (typeof $element.data("allowHttpsSkip") !== "undefined") { hp.Utils.defaults.allowHttpsSkip = $element.data("allowHttpsSkip").toString().toLowerCase() == "false" ? false : true; } if (typeof $element.data("correlationId") !== "undefined") { hp.Utils.defaults.correlationId = $element.data("correlationId").toString(); } if (typeof $element.data("terminalId") !== "undefined") { hp.Utils.defaults.terminalId = $element.data("terminalId").toString(); } if (typeof $element.data("instrumentId") !== "undefined") { hp.Utils.defaults.instrumentId = $element.data("instrumentId").toString(); } if (typeof $element.data("baseUrl") !== "undefined") { hp.Utils.defaults.baseUrl = $element.data("baseUrl").toString(); } if (typeof $element.data("customerName") !== "undefined") { hp.Utils.defaults.customerName = $element.data("customerName").toString(); } if (typeof $element.data("defaultPhone") !== "undefined") { hp.Utils.defaults.defaultPhone = $element.data("defaultPhone").toString(); } if (typeof $element.data("errorLabel") !== "undefined") { hp.Utils.defaults.defaultErrorLabel = $element.data("errorLabel").toString(); } if (typeof $element.data("redirectLabel") !== "undefined") { hp.Utils.defaults.defaultRedirectLabel = $element.data("redirectLabel").toString(); } if (typeof $element.data("successLabel") !== "undefined") { hp.Utils.defaults.defaultSuccessLabel = $element.data("successLabel").toString(); } if (typeof $element.data("ignoreSubmission") !== "undefined") { hp.Utils.defaults.ignoreSubmission = $element.data("ignoreSubmission").toString().toLowerCase() === "true"; } if (typeof $element.data("paymentTypeOrder") !== "undefined") { hp.Utils.defaults.paymentTypeOrder = $.trim($element.data("paymentTypeOrder") .toString() .replace(" ", "")) .split(",") .map(function(item) { return +item; }); } if (typeof $element.data("amount") !== "undefined") { hp.Utils.setAmount($element.data("amount")); } if (typeof $element.data("antiForgeryToken") !== "undefined") { hp.Utils.defaults.antiForgeryToken = $element.data("antiForgeryToken").toString(); } else { hp.Utils.defaults.antiForgeryToken = hp.Utils.generateGuild(); } if (typeof $element.data("antiForgeryName") !== "undefined") { hp.Utils.defaults.antiForgeryName = $element.data("antiForgeryName").toString(); } $element.attr("data-ets-key", hp.Utils.generateGuild()); hp.Utils.setPaymentInstrument(); hp.Utils.signIn().then(function(){ hp.Utils.setupPluginInstances($element); }); }; $.extend(Plugin.prototype, { init: function() { var $element = $(this.element), name = "", type = hp.types.Adapter; if ($element.data("event") !== null && typeof $element.data("event") !== "undefined") { type = hp.types.Event; name = $element.data("event"); } if ($element.data("inventory") !== null && typeof $element.data("inventory") !== "undefined") { type = hp.types.Product; name = $element.data("inventory"); } // Get outer wrapper width and set css class for mobile purposes hp.Utils.setContainerClass($element); if (type === hp.types.Event) { name = $element.data("event"); } else if (type === hp.types.Product) { name = $element.data("inventory"); } else if (type === hp.types.Adapter) { intialize.call(this); return; } var email = $element.data("email"), bcc = $element.data("bcc"), clientId = $element.data("client"), showMemoField = typeof $element.data("memo") === "undefined" ? false : true, ga = $element.data("ga"), orderId = $element.data("order"), subject = $element.data("subject"); var setup = new hp.Setup(type, new hp.models.Options(clientId, email, bcc, showMemoField, ga, orderId, name, subject)); $element.find("[data-item]").each(function() { var item = new hp.models.Item($(this).data("item"), $(this).data("price")); setup.addItem(item); }); $element.empty(); setup.createForm(this.element, hp.Utils.defaults.baseUrl).then(function(iframe) { $element .width(iframe.width) .height(iframe.height) .css("margin", "0 auto"); }); } }); $.fn[pluginName] = function(options) { this.each(function() { if (!$.data(this, "plugin_" + pluginName)) { $.data(this, "plugin_" + pluginName, new Plugin(this, options)); } }); return this; }; })(jQuery, window, document);
(function() { var op; op = require('../../../tasks/package/operators'); module.exports = function(config) { return config.tasks["package"] = { dir: "" + config.root + "/packages", conf: "" + config.root + "/config/packages", tmp: "" + config.root + "/.tmp", operatorsMap: { 'annotate:class': op.annotateClass, 'annotate:file': op.annotateFile, 'compile': op.compile, 'create:directory': op.createDirectory, 'create:file': op.createFile, 'exports:package': op.exportsToPackage, 'header:license': op.headerLicense, 'join': op.join, 'path:change': op.pathChange, 'path:reset': op.pathReset, 'strip:requires': op.stripRequires, 'uglify': op.uglify } }; }; }).call(this);
import Route from '../../common/route'; import Model from '../model'; import View from './view'; import storage from '../storage'; export default Route.extend({ initialize(options) { this.container = options.container; }, fetch() { this.model = new Model(); return storage.findAll().then(collection => { this.collection = collection; }); }, render() { this.view = new View({ collection: this.collection, model: this.model }); this.container.show(this.view); } });
Clazz.declarePackage ("J.atomdata"); c$ = Clazz.decorateAsClass (function () { this.programInfo = null; this.fileName = null; this.modelName = null; this.modelIndex = 0; this.bsSelected = null; this.bsIgnored = null; this.bsMolecules = null; this.radiusData = null; this.firstAtomIndex = 0; this.firstModelIndex = 0; this.lastModelIndex = 0; this.hAtomRadius = 0; this.atomIndex = null; this.atomXyz = null; this.atomRadius = null; this.atomicNumber = null; this.atomMolecule = null; this.hAtoms = null; this.atomCount = 0; this.hydrogenAtomCount = 0; this.adpMode = 0; Clazz.instantialize (this, arguments); }, J.atomdata, "AtomData"); Clazz.makeConstructor (c$, function () { }); Clazz.defineStatics (c$, "MODE_FILL_COORDS", 1, "MODE_FILL_RADII", 2, "MODE_FILL_MOLECULES", 4, "MODE_GET_ATTACHED_HYDROGENS", 8, "MODE_FILL_MULTIMODEL", 16);
var TYPES = ['string', 'integer', 'decimal', 'boolean', 'composite', 'number', 'randexp', 'array', 'autoincrement'], fn = function(_forEach, _toArray, formats){ var startAt = fn.length, args = _toArray(arguments).slice(startAt, arguments.length); types = {}; _forEach(TYPES, function(type, i){ types[type] = args[i]; }); types.formats = formats; return types; } define([ 'lodash/collections/forEach', 'lodash/collections/toArray', 'lib/types/formats/formats', 'lib/types/string', 'lib/types/integer', 'lib/types/decimal', 'lib/types/boolean', 'lib/types/composite', 'lib/types/number', 'lib/types/randexp', 'lib/types/array', 'lib/types/autoincrement'], fn);
myPager.addTask('tasks', { openDir: undefined, parsed: undefined, init: function (pageId, pageContent, event, dom, scope) { var list = myTaskHelper.getDir(_globals.appActive.data.localPath+'/www/tasks'); return function () { helper.renderDirs( list, document.getElementById('editor.tasks.files'), '', true, ['tasks.open','tasks.showDir'], ['js'] ); require('codemirror/mode/javascript/javascript'); var CodeMirror = require('codemirror/lib/codemirror'); _globals.tabTasks.editor = CodeMirror.fromTextArea(document.getElementById('editor.tasks.content.editor'), { lineNumbers: true, theme: 'crisper', mode: 'javascript' }); _globals.tabTasks.editor.on('change', function (cm) { document.getElementById('editor.tasks.save').classList.remove('disable'); }); myTaskHelper.editorSwitchTab(event.target); }; }, showDir: function (pageId, pageContent, event, dom, scope) { if (!pageContent) { return false; } scope.openDir = pageContent; var list = myTaskHelper.getDir(_globals.appActive.data.localPath+'/www/tasks/'+pageContent); if (!event.target.nextSibling || !event.target.nextSibling.classList.contains('childNode')) { var child = document.createElement('ul'); child.className = 'childNode'; event.target.parentNode.insertBefore(child, event.target.nextSibling); } else { child = event.target.nextSibling } helper.renderDirs( list, child, pageContent+'/', true, ['tasks.open','tasks.showDir'], ['js'] ); myPager.events(); myTaskHelper.setActive('editor.tasks.files', 'active'); return false; }, open: function (pageId, pageContent, event, dom, scope) { if (!pageContent) { return false; } var data = myTaskHelper.getFile(_globals.appActive.data.localPath+'/www/tasks/'+pageContent); _globals.tabTasks.path = _globals.appActive.data.localPath+'/www/tasks/'+pageContent; myTaskHelper.setActive('editor.tasks.files', 'active'); document.getElementById('editor.tasks.save').classList.add('disable'); if (data) { _globals.tabTasks.editor.setValue(data+''); var esprima = require('esprima'); var escodegen = require('escodegen'); scope.parsed = esprima.parse(data+''); document.getElementById('editor.tasks.ui.name').value = helper.cutFirstLastChar(scope.parsed.body[0].expression.arguments[0].raw) || ''; var root = document.getElementById('editor.tasks.ui.list'); root.innerHTML = ''; var properties = scope.parsed.body[0].expression.arguments[1].properties; var length = properties.length; for (var i = 0; i < length; i++) { //console.log(properties[i]); var val = helper.getReturnStatment(clone(properties[i].value.body)); root.appendChild(helper.taskMakeChild( i, { name: [properties[i].key.name, function (e) { properties[e.target.i].key.name = e.target.value; _globals.tabTasks.editor.setValue(escodegen.generate(scope.parsed)+''); }], beforeDom: [val[0], function (e) { properties[e.target.i].value.body = esprima.parse('{'+e.target.value+'}'); _globals.tabTasks.editor.setValue(escodegen.generate(scope.parsed)+''); }], disableDom: [val[1][2], function (e) { }], afterDom: [val[1][0],function (e) { properties[e.target.i].value.body.body[e.target.a].argument.body = esprima.parse('{'+e.target.value+'}'); _globals.tabTasks.editor.setValue(escodegen.generate(scope.parsed)+''); }, val[1][1]], afterAnimation: [] } )); } } return false; }, newTask: function (pageId, pageContent, event, dom, scope) { var escodegen = require('escodegen'); var esprima = require('esprima'); var properties = scope.parsed.body[0].expression.arguments[1].properties; var length = properties.length; var node = esprima.parse('var obj = { "undefinied": function (pageId, pageContent, event, dom, scope) { return function () {}; } }') delete node.body[0].declarations[0].init.properties[0].key.raw; delete node.body[0].declarations[0].init.properties[0].key.value; node.body[0].declarations[0].init.properties[0].key.type = 'Identifier'; properties[length] = node.body[0].declarations[0].init.properties[0]; document.getElementById('editor.tasks.ui.list').appendChild(helper.taskMakeChild( length, { name: ['', function (e) { properties[e.target.i].key.name = e.target.value; _globals.tabTasks.editor.setValue(escodegen.generate(scope.parsed)+''); }], beforeDom: ['', function (e) { properties[e.target.i].value.body = esprima.parse('{'+e.target.value+'}'); _globals.tabTasks.editor.setValue(escodegen.generate(scope.parsed)+''); }], disableDom: [false, function (e) { if (e.target.checked) { } else { } }], afterDom: ['',function (e) { var node = esprima.parse('{ return function () {}; }'); console.log(node.body[0].body[0]); console.log(e.target.i, e.target.a); if (!e.target.a) { console.log(properties[e.target.i].value.body.body); console.log(properties[e.target.i].value.body.body[0]); console.log(properties[e.target.i].value.body.body[0].body); properties[e.target.i].value.body.body[0].body.push(node.body[0].body[0]); e.target.a = properties[e.target.i].value.body.body.length -1; } properties[e.target.i].value.body.body[0].body[e.target.a].argument.body = esprima.parse('{'+e.target.value+'}'); _globals.tabTasks.editor.setValue(escodegen.generate(scope.parsed)+''); }], afterAnimation: [] } )); }, newFile: function (pageId, pageContent, event, dom, scope) { var myDialog = new cDialog({ type: 'input', autoOpen: true, confirm: { text: 'Ok', handler: function (value, e) { if (!value) { return false; } if (scope.openDir) { value = scope.openDir+'/'+value; } myTaskHelper.saveFile(_globals.appActive.data.localPath+'/www/tasks/'+value+'.js', '', function () { var list = myTaskHelper.getDir(_globals.appActive.data.localPath+'/www/tasks'); helper.renderDirs( list, document.getElementById('editor.tasks.files'), '', true, ['tasks.open','tasks.showDir'], ['js'] ); myPager.events(); }); } }, abort: { text: 'Abort', handler: function (e) { //console.log('Abort! done'); return false; } } }); return false; }, save: function (pageId, pageContent, event, dom) { console.log(_globals.tabTasks.path); console.log(_globals.tabTasks.editor.getValue()); myTaskHelper.saveFile(_globals.tabTasks.path, _globals.tabTasks.editor.getValue(), function () { document.getElementById('editor.tasks.save').classList.add('disable'); }); } }); function clone(obj) { if (obj === null || typeof(obj) !== 'object' || 'isActiveClone' in obj) return obj; if (obj instanceof Date) var temp = new obj.constructor(); //or new Date(obj); else var temp = obj.constructor(); for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { obj['isActiveClone'] = null; temp[key] = clone(obj[key]); delete obj['isActiveClone']; } } return temp; }
var runs = require('./runs'); /* Returns a font CSS/Canvas string based on the settings in a run */ var getFontString = exports.getFontString = function(run) { var size = (run && run.size) || runs.defaultFormatting.size; if (run) { switch (run.script) { case 'super': case 'sub': size *= 0.8; break; } } return (run && run.italic ? 'italic ' : '') + (run && run.bold ? 'bold ' : '') + ' ' + size + 'pt ' + ((run && run.font) || runs.defaultFormatting.font); }; /* Applies the style of a run to the canvas context */ exports.applyRunStyle = function(ctx, run) { ctx.fillStyle = (run && run.color) || runs.defaultFormatting.color; ctx.font = getFontString(run); }; exports.prepareContext = function(ctx) { ctx.textAlign = 'left'; ctx.textBaseline = 'alphabetic'; }; /* Generates the value for a CSS style attribute */ exports.getRunStyle = function(run) { var parts = [ 'font: ', getFontString(run), '; color: ', ((run && run.color) || runs.defaultFormatting.color) ]; if (run) { switch (run.script) { case 'super': parts.push('; vertical-align: super'); break; case 'sub': parts.push('; vertical-align: sub'); break; } } return parts.join(''); }; var nbsp = exports.nbsp = String.fromCharCode(160); var enter = exports.enter = nbsp; // String.fromCharCode(9166); /* Returns width, height, ascent, descent in pixels for the specified text and font. The ascent and descent are measured from the baseline. Note that we add/remove all the DOM elements used for a measurement each time - this is not a significant part of the cost, and if we left the hidden measuring node in the DOM then it would affect the dimensions of the whole page. */ var measureText = exports.measureText = function(text, style) { var span, block, div; span = document.createElement('span'); block = document.createElement('div'); div = document.createElement('div'); block.style.display = 'inline-block'; block.style.width = '1px'; block.style.height = '0'; div.style.visibility = 'hidden'; div.style.position = 'absolute'; div.style.top = '0'; div.style.left = '0'; div.style.width = '500px'; div.style.height = '200px'; div.appendChild(span); div.appendChild(block); document.body.appendChild(div); try { span.setAttribute('style', style); span.innerHTML = ''; span.appendChild(document.createTextNode(text.replace(/\s/g, nbsp))); var result = {}; block.style.verticalAlign = 'baseline'; result.ascent = (block.offsetTop - span.offsetTop); block.style.verticalAlign = 'bottom'; result.height = (block.offsetTop - span.offsetTop); result.descent = result.height - result.ascent; result.width = span.offsetWidth; } finally { div.parentNode.removeChild(div); div = null; } return result; }; /* Create a function that works like measureText except it caches every result for every unique combination of (text, style) - that is, it memoizes measureText. So for example: var measure = cachedMeasureText(); Then you can repeatedly do lots of separate calls to measure, e.g.: var m = measure('Hello, world', 'font: 12pt Arial'); console.log(m.ascent, m.descent, m.width); A cache may grow without limit if the text varies a lot. However, during normal interactive editing the growth rate will be slow. If memory consumption becomes a problem, the cache can be occasionally discarded, although of course this will cause a slow down as the cache has to build up again (text measuring is by far the most costly operation we have to do). */ var createCachedMeasureText = exports.createCachedMeasureText = function() { var cache = {}; return function(text, style) { var key = style + '<>!&%' + text; var result = cache[key]; if (!result) { cache[key] = result = measureText(text, style); } return result; }; }; exports.cachedMeasureText = createCachedMeasureText(); exports.measure = function(str, formatting) { return exports.cachedMeasureText(str, exports.getRunStyle(formatting)); }; exports.draw = function(ctx, str, formatting, left, baseline, width, ascent, descent) { exports.prepareContext(ctx); exports.applyRunStyle(ctx, formatting); switch (formatting.script) { case 'super': baseline -= (ascent * (1/3)); break; case 'sub': baseline += (descent / 2); break; } ctx.fillText(str === '\n' ? exports.enter : str, left, baseline); if (formatting.underline) { ctx.fillRect(left, 1 + baseline, width, 1); } if (formatting.strikeout) { ctx.fillRect(left, 1 + baseline - (ascent/2), width, 1); } };