/* Minification failed. Returning unminified contents.
(2026,9583-9590): run-time error JS1019: Can't have 'break' outside of loop: break e
 */
// Copyright 2012-2016 Laserfiche. All rights reserved

﻿var currency_list=[{code:"AED",currency:"UAE Dirham",symbol:"د.إ",text:localize('CUR_AED')},{code:"AFN",currency:"Afghani",symbol:"؋",text:localize('CUR_AFN')},{code:"ALL",currency:"Lek",symbol:"Lek",text:localize('CUR_ALL')},{code:"AMD",currency:"Armenian Dram",symbol:"Դ",text:localize('CUR_AMD')},{code:"ANG",currency:"Netherlands Antillian Guilder",symbol:"ƒ",text:localize('CUR_ANG')},{code:"AOA",currency:"Kwanza, Angola",symbol:"Kz",text:localize('CUR_AOA')},{code:"ARS",currency:"Argentine Peso",symbol:"$",text:localize('CUR_ARS')},{code:"AUD",currency:"Australian Dollar",symbol:"$",text:localize('CUR_AUD')},{code:"AWG",currency:"Aruban Guilder",symbol:"Af.",text:localize('CUR_AWG')},{code:"AZN",currency:"Azerbaijan Manat",symbol:"ман",text:localize('CUR_AZN')},{code:"BAM",currency:"Conv. Marks, Bosnia and Herz.",symbol:"KM",text:localize('CUR_BAM')},{code:"BBD",currency:"Barbados Dollar",symbol:"$",text:localize('CUR_BBD')},{code:"BDT",currency:"Taka, Bangladesh",symbol:"Tk",text:localize('CUR_BDT')},{code:"BGN",currency:"Bulgarian Lev",symbol:"лв",text:localize('CUR_BGN')},{code:"BHD",currency:"Bahraini Dinar",symbol:"د.ب.",symbolInEdit:".د.ب",text:localize('CUR_BHD')},{code:"BIF",currency:"Burundi Franc",symbol:"FBu",text:localize('CUR_BIF')},{code:"BMD",currency:"Bermudian Dollar",symbol:"Bd$",text:localize('CUR_BMD')},{code:"BND",currency:"Brunei Dollar",symbol:"$",text:localize('CUR_BND')},{code:"BOB",currency:"Boliviano, Bolivia",symbol:"$b",text:localize('CUR_BOB')},{code:"BOV",currency:"Mvdol, Bolivia",symbol:"$b",text:localize('CUR_BOV')},{code:"BRL",currency:"Brazilian Real",symbol:"R$ ",text:localize('CUR_BRL')},{code:"BSD",currency:"Bahamian Dollar",symbol:"$",text:localize('CUR_BSD')},{code:"BTN",currency:"Ngultrum, Bhutan",symbol:"Nu.",text:localize('CUR_BTN')},{code:"BWP",currency:"Pula, Botswana",symbol:"P",text:localize('CUR_BWP')},{code:"BYR",currency:"Belarussian Ruble",symbol:"p.",text:localize('CUR_BYR')},{code:"BZD",currency:"Belize Dollar",symbol:"Bz$",text:localize('CUR_BZD')},{code:"CAD",currency:"Canadian Dollar",symbol:"$",text:localize('CUR_CAD')},{code:"CDF",currency:"Congolese Franc",symbol:"FC",text:localize('CUR_CDF')},{code:"CFA",currency:"West African CFA franc",symbol:"CFA",text:localize('CUR_CFA')},{code:"CHE",currency:"WIR Euro, Switzerland",symbol:" ",text:localize('CUR_CHE')},{code:"CHF",currency:"Swiss Franc",symbol:"CHF",text:localize('CUR_CHF')},{code:"CHW",currency:"WIR Franc, Switzerland",symbol:" ",text:localize('CUR_CHW')},{code:"CLF",currency:"Unidades de fomento, Chile",symbol:"UF",text:localize('CUR_CLF')},{code:"CLP",currency:"Chilean Peso",symbol:"$",text:localize('CUR_CLP')},{code:"CNH",currency:"Yuan",symbol:"¥",text:localize('CUR_CNH')},{code:"CNY",currency:"Yuan Renminbi",symbol:"¥",text:localize('CUR_CNY')},{code:"COP",currency:"Colombian Peso",symbol:"$",text:localize('CUR_COP')},{code:"COU",currency:"Unidad de Valor Real, Colombia",symbol:"$",text:localize('CUR_COU')},{code:"CRC",currency:"Costa Rican Colon",symbol:"₡",text:localize('CUR_CRC')},{code:"CUC",currency:"Peso Convertible, Cuba",symbol:"CUC$",text:localize('CUR_CUC')},{code:"CUP",currency:"Cuban Peso",symbol:"₱",text:localize('CUR_CUP')},{code:"CVE",currency:"Cape Verde Escudo",symbol:"$",text:localize('CUR_CVE')},{code:"CZK",currency:"Czech Koruna",symbol:"Kč",text:localize('CUR_CZK')},{code:"DJF",currency:"Djibouti Franc",symbol:"Fdj",text:localize('CUR_DJF')},{code:"DKK",currency:"Danish Krone",symbol:"kr",text:localize('CUR_DKK')},{code:"DOP",currency:"Dominican Peso",symbol:"RD$",text:localize('CUR_DOP')},{code:"DZD",currency:"Algerian Dinar",symbol:"د.ج",text:localize('CUR_DZD')},{code:"EEK",currency:"Kroon, Estonia",symbol:"kr",text:localize('CUR_EEK')},{code:"EGP",currency:"Egyptian pound",symbol:"£",text:localize('CUR_EGP')},{code:"ERN",currency:"Nakfa, Eritrea",symbol:"Nfk",text:localize('CUR_ERN')},{code:"ETB",currency:"Ethiopian Birr",symbol:"Br",text:localize('CUR_ETB')},{code:"EUR",currency:"Euro",symbol:"€",text:localize('CUR_EUR')},{code:"FJD",currency:"Fiji Dollar",symbol:"$",text:localize('CUR_FJD')},{code:"FKP",currency:"Falkland Islands Pound",symbol:"£",text:localize('CUR_FKP')},{code:"GBP",currency:"Pound Sterling",symbol:"£",text:localize('CUR_GBP')},{code:"GEL",currency:"Lari, Georgia",symbol:"£",text:localize('CUR_GEL')},{code:"GHS",currency:"Cedi, Ghana",symbol:"GH₵",text:localize('CUR_GHS')},{code:"GIP",currency:"Gibraltar Pound",symbol:"£",text:localize('CUR_GIP')},{code:"GMD",currency:"Dalasi, Gambia",symbol:"D",text:localize('CUR_GMD')},{code:"GNF",currency:"Guinea Franc",symbol:"FG",text:localize('CUR_GNF')},{code:"GTQ",currency:"Quetzal, Guatemala",symbol:"Q",text:localize('CUR_GTQ')},{code:"GYD",currency:"Guyana Dollar",symbol:"G$",text:localize('CUR_GYD')},{code:"HKD",currency:"Hong Kong Dollar",symbol:"$",text:localize('CUR_HKD')},{code:"HNL",currency:"Lempira, Honduras",symbol:"L",text:localize('CUR_HNL')},{code:"HRK",currency:"Croatian Kuna",symbol:"kn",text:localize('CUR_HRK')},{code:"HTG",currency:"Gourde, Haiti",symbol:"G",text:localize('CUR_HTG')},{code:"HUF",currency:"Forint, Hungary",symbol:"Ft",text:localize('CUR_HUF')},{code:"IDR",currency:"Rupiah, Indonesia",symbol:"Rp",text:localize('CUR_IDR')},{code:"ILS",currency:"New Israeli Shekel",symbol:"₪",text:localize('CUR_ILS')},{code:"INR",currency:"Indian Rupee",symbol:"र",text:localize('CUR_INR')},{code:"IQD",currency:"Iraqi Dinar",symbol:"ع.د",text:localize('CUR_IQD')},{code:"IRR",currency:"Iranian Rial",symbol:"﷼",text:localize('CUR_IRR')},{code:"ISK",currency:"Iceland Krona",symbol:"kr",text:localize('CUR_ISK')},{code:"JMD",currency:"Jamaican Dollar",symbol:"J$",text:localize('CUR_JMD')},{code:"JOD",currency:"Jordanian Dinar",symbol:"دينار",text:localize('CUR_JOD')},{code:"JPY",currency:"Japanese Yen",symbol:"¥",text:localize('CUR_JPY')},{code:"KES",currency:"Kenyan Shilling",symbol:"KSh",text:localize('CUR_KES')},{code:"KGS",currency:"Som, Kyrgyzstan",symbol:"лв",text:localize('CUR_KGS')},{code:"KHR",currency:"Riel, Cambodia",symbol:"៛",text:localize('CUR_KHR')},{code:"KMF",currency:"Comoro Franc",symbol:"CF",text:localize('CUR_KMF')},{code:"KPW",currency:"North Korean Won",symbol:"₩",text:localize('CUR_KPW')},{code:"KRW",currency:"Won, South Korea",symbol:"₩",text:localize('CUR_KRW')},{code:"KWD",currency:"Kuwait Dinar",symbol:"K.D.",text:localize('CUR_KWD')},{code:"KYD",currency:"Cayman Islands Dollar",symbol:"$",text:localize('CUR_KYD')},{code:"KZT",currency:"Tenge, Kazakhstan",symbol:"лв",text:localize('CUR_KZT')},{code:"LAK",currency:"Kip, Laos",symbol:"₭",text:localize('CUR_LAK')},{code:"LBP",currency:"Lebanon Pound",symbol:"£",text:localize('CUR_LBP')},{code:"LKR",currency:"Sri Lanka Rupee",symbol:"₨",text:localize('CUR_LKR')},{code:"LRD",currency:"Liberian Dollar",symbol:"$",text:localize('CUR_LRD')},{code:"LSL",currency:"Loti, Lesotho",symbol:"L",text:localize('CUR_LSL')},{code:"LTL",currency:"Lithuanian Litas",symbol:"Lt",text:localize('CUR_LTL')},{code:"LVL",currency:"Latvian Lats",symbol:"Ls",text:localize('CUR_LVL')},{code:"LYD",currency:"Libyan Dinar",symbol:"LD",text:localize('CUR_LYD')},{code:"MAD",currency:"Moroccan Dirham",symbol:"درهم",text:localize('CUR_MAD')},{code:"MDL",currency:"Moldovan Leu",symbol:"L",text:localize('CUR_MDL')},{code:"MGA",currency:"Malagasy Ariary",symbol:"Ar",text:localize('CUR_MGA')},{code:"MKD",currency:"Macedonian Denar",symbol:"ден",text:localize('CUR_MKD')},{code:"MMK",currency:"Kyat, Myanmar",symbol:"K",text:localize('CUR_MMK')},{code:"MNT",currency:"Mongolian Tugrik",symbol:"₮",text:localize('CUR_MNT')},{code:"MOP",currency:"Macanese Pataca",symbol:"MOP$",text:localize('CUR_MOP')},{code:"MRO",currency:"Mauritian Ouguiya",symbol:"UM",text:localize('CUR_MRO')},{code:"MUR",currency:"Mauritius Rupee",symbol:"Rs",text:localize('CUR_MUR')},{code:"MVR",currency:"Maldivian Rufiyaa",symbol:"Rf",text:localize('CUR_MVR')},{code:"MWK",currency:"Malawian Kwacha",symbol:"MK",text:localize('CUR_MWK')},{code:"MXN",currency:"Mexican Peso",symbol:"$",text:localize('CUR_MXN')},{code:"MXV",currency:"Mexican Unidad de Inversion",symbol:"UDI",text:localize('CUR_MXV')},{code:"MYR",currency:"Malaysian Ringgit",symbol:"RM",text:localize('CUR_MYR')},{code:"MZN",currency:"Mozambican Metical",symbol:"MT",text:localize('CUR_MZN')},{code:"NA",currency:"N/A",symbol:" ",text:localize('CUR_NA')},{code:"NAD",currency:"Namibia Dollar",symbol:"$",text:localize('CUR_NAD')},{code:"NGN",currency:"Naira, Nigeria",symbol:"₦",text:localize('CUR_NGN')},{code:"NIO",currency:"Córdoba, Nicaragua",symbol:"C$",text:localize('CUR_NIO')},{code:"NOK",currency:"Norwegian Krone",symbol:"kr",text:localize('CUR_NOK')},{code:"NPR",currency:"Nepalese Rupee",symbol:"₨",text:localize('CUR_NPR')},{code:"NZD",currency:"New Zealand Dollar",symbol:"$",text:localize('CUR_NZD')},{code:"OMR",currency:"Rial Omani, Oman",symbol:"ريال",text:localize('CUR_OMR')},{code:"PAB",currency:"Balboa, Panama",symbol:"B/",text:localize('CUR_PAB')},{code:"PEN",currency:"Nuevo Sol, Peru",symbol:"S/",text:localize('CUR_PEN')},{code:"PGK",currency:"Kina, Papua New Guinea",symbol:"K",text:localize('CUR_PGK')},{code:"PHP",currency:"Philippine Peso",symbol:"Php",text:localize('CUR_PHP')},{code:"PKR",currency:"Pakistan Rupee",symbol:"₨",text:localize('CUR_PKR')},{code:"PLN",currency:"Zloty, Poland",symbol:"zł",text:localize('CUR_PLN')},{code:"PYG",currency:"Guarani, Paraguay",symbol:"Gs",text:localize('CUR_PYG')},{code:"QAR",currency:"Qatar Rial",symbol:"﷼",text:localize('CUR_QAR')},{code:"RON",currency:"New Leu, Romania",symbol:"lei",text:localize('CUR_RON')},{code:"RSD",currency:"Serbian Dinar",symbol:"Дин.",text:localize('CUR_RSD')},{code:"RUB",currency:"Russian Ruble",symbol:"руб",text:localize('CUR_RUB')},{code:"RWF",currency:"Rwandan Franc ",symbol:"FRw",text:localize('CUR_RWF')},{code:"SAR",currency:"Saudi Riyal",symbol:"﷼",text:localize('CUR_SAR')},{code:"SBD",currency:"Solomon Islands Dollar",symbol:"SI$",text:localize('CUR_SBD')},{code:"SCR",currency:"Seychelles Rupee",symbol:"₨",text:localize('CUR_SCR')},{code:"SDG",currency:"Sudanese Pound",symbol:"£",text:localize('CUR_SDG')},{code:"SEK",currency:"Swedish Krona",symbol:"kr",text:localize('CUR_SEK')},{code:"SGD",currency:"Singapore Dollar",symbol:"$",text:localize('CUR_SGD')},{code:"SHP",currency:"Saint Helena Pound",symbol:"£",text:localize('CUR_SHP')},{code:"SLL",currency:"Leone, Sierra Leone",symbol:"Le",text:localize('CUR_SLL')},{code:"SOS",currency:"Somali Shilling",symbol:"S",text:localize('CUR_SOS')},{code:"SRD",currency:"Surinam Dollar",symbol:"$",text:localize('CUR_SRD')},{code:"STD",currency:"Dobra, São Tome and Principe",symbol:"Db",text:localize('CUR_STD')},{code:"SVC",currency:"El Salvador Colon",symbol:"$",text:localize('CUR_SVC')},{code:"SYP",currency:"Syrian Pound",symbol:"£",text:localize('CUR_SYP')},{code:"SZL",currency:"Lilangeni, Swaziland",symbol:"L",text:localize('CUR_SZL')},{code:"THB",currency:"Baht, Thailand",symbol:"฿",text:localize('CUR_THB')},{code:"TJS",currency:"Somoni, Tajikistan",symbol:"SM",text:localize('CUR_TJS')},{code:"TMT",currency:"Manat, Turkmenistan",symbol:"m",text:localize('CUR_TMT')},{code:"TND",currency:"Tunisian Dollar",symbol:"DT",text:localize('CUR_TND')},{code:"TOP",currency:"Pa'anga, Tonga",symbol:"DT",text:localize('CUR_TOP')},{code:"TRY",currency:"Turkish Lira",symbol:"TL",text:localize('CUR_TRY')},{code:"TTD",currency:"Trinidad and Tobago Dollar",symbol:"TT$",text:localize('CUR_TTD')},{code:"TWD",currency:"New Taiwan Dollar",symbol:"NT$",text:localize('CUR_TWD')},{code:"TVD",currency:"Tuvaluan Dollar",symbol:"$",text:localize('CUR_TVD')},{code:"TZS",currency:"Tanzanian Shilling ",symbol:"TSh",text:localize('CUR_TZS')},{code:"UAH",currency:"Hryvnia, Ukraine",symbol:"₴",text:localize('CUR_UAH')},{code:"UGX",currency:"Ugandan Shilling ",symbol:"Ush",text:localize('CUR_UGX')},{code:"USD",currency:"US Dollar",symbol:"$",text:localize('CUR_USD')},{code:"USN",currency:"US Dollar (next day)",symbol:"$",text:localize('CUR_USN')},{code:"USS",currency:"US Dollar (same day)",symbol:"$",text:localize('CUR_USS')},{code:"UYI",currency:"Peso en Unidades Indexadas (UY)",symbol:"$U",text:localize('CUR_UYI')},{code:"UYU",currency:"Peso, Uruguay",symbol:"$",text:localize('CUR_UYU')},{code:"UZS",currency:"Uzbekistan Sum",symbol:"лв",text:localize('CUR_UZS')},{code:"VEF",currency:"Bolivar, Venezuela",symbol:"Bs",text:localize('CUR_VEF')},{code:"VND",currency:"Dong, Vietnam",symbol:"₫",text:localize('CUR_VND')},{code:"VUV",currency:"Vatu, Vanuatu",symbol:"VT",text:localize('CUR_VUV')},{code:"WST",currency:"Tala, Samoa",symbol:"WS$",text:localize('CUR_WST')},{code:"XAF",currency:"CFA Franc BEAC",symbol:"FCFA",text:localize('CUR_XAF')},{code:"XAG",currency:"Silver",symbol:"Ag",text:localize('CUR_XAG')},{code:"XAU",currency:"Gold",symbol:"Au",text:localize('CUR_XAU')},{code:"XBA",currency:"European Composite Unit (EURCO)",symbol:" ",text:localize('CUR_XBA')},{code:"XBB",currency:"European Monetary Unit (E.M.U. XBB)",symbol:" ",text:localize('CUR_XBB')},{code:"XBC",currency:"European Unit of Account 9",symbol:" ",text:localize('CUR_XBC')},{code:"XBD",currency:"European Unit of Account 17",symbol:" ",text:localize('CUR_XBD')},{code:"XCD",currency:"East Caribbean Dollar",symbol:"EC$",text:localize('CUR_XCD')},{code:"XDR",currency:"I.M.F. SDR",symbol:" ",text:localize('CUR_XDR')},{code:"XFU",currency:"UIC Franc",symbol:" ",text:localize('CUR_XFU')},{code:"XOF",currency:"CFA Franc BCEAO",symbol:"CFA",text:localize('CUR_XOF')},{code:"XPD",currency:"Palladium",symbol:" ",text:localize('CUR_XPD')},{code:"XPF",currency:"CFP Franc",symbol:"F",text:localize('CUR_XPF')},{code:"XPT",currency:"Platinum",symbol:" ",text:localize('CUR_XPT')},{code:"XSU",currency:"SUCRE",symbol:" ",text:localize('CUR_XSU')},{code:"XUA",currency:"ABD Unit of Account",symbol:" ",text:localize('CUR_XUA')},{code:"YER",currency:"Yemeni Rial",symbol:"﷼",text:localize('CUR_YER')},{code:"ZAR",currency:"South African Rand",symbol:"R",text:localize('CUR_ZAR')},{code:"ZMK",currency:"Zambian Kwacha",symbol:"ZK",text:localize('CUR_ZMK')},{code:"ZWL",currency:"Zimbabwe Dollar",symbol:"Z$",text:localize('CUR_ZWL')}];;
/*
 * jQuery File Upload Plugin 5.41.0
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/MIT
 */

/* jshint nomen:false */
/* global define, window, document, location, Blob, FormData */

(function (factory) {
    'use strict';
    if (typeof define === 'function' && define.amd) {
        // Register as an anonymous AMD module:
        define([
            'jquery',
            'jquery.ui.widget'
        ], factory);
    } else {
        // Browser globals:
        factory(window.jQuery);
    }
}(function ($) {
    'use strict';

    // Detect file input support, based on
    // http://viljamis.com/blog/2012/file-upload-support-on-mobile/
    $.support.fileInput = !(new RegExp(
        // Handle devices which give false positives for the feature detection:
        '(Android (1\\.[0156]|2\\.[01]))' +
            '|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)' +
            '|(w(eb)?OSBrowser)|(webOS)' +
            '|(Kindle/(1\\.0|2\\.[05]|3\\.0))'
    ).test(window.navigator.userAgent) ||
        // Feature detection for all other devices:
        $('<input type="file">').prop('disabled'));

    // The FileReader API is not actually used, but works as feature detection,
    // as some Safari versions (5?) support XHR file uploads via the FormData API,
    // but not non-multipart XHR file uploads.
    // window.XMLHttpRequestUpload is not available on IE10, so we check for
    // window.ProgressEvent instead to detect XHR2 file upload capability:
    $.support.xhrFileUpload = !!(window.ProgressEvent && window.FileReader);
    $.support.xhrFormDataFileUpload = !!window.FormData;

    // Detect support for Blob slicing (required for chunked uploads):
    $.support.blobSlice = window.Blob && (Blob.prototype.slice ||
        Blob.prototype.webkitSlice || Blob.prototype.mozSlice);

    // The fileupload widget listens for change events on file input fields defined
    // via fileInput setting and paste or drop events of the given dropZone.
    // In addition to the default jQuery Widget methods, the fileupload widget
    // exposes the "add" and "send" methods, to add or directly send files using
    // the fileupload API.
    // By default, files added via file input selection, paste, drag & drop or
    // "add" method are uploaded immediately, but it is possible to override
    // the "add" callback option to queue file uploads.
    $.widget('blueimp.fileupload', {

        options: {
            // The drop target element(s), by the default the complete document.
            // Set to null to disable drag & drop support:
            dropZone: $(document),
            // The paste target element(s), by the default the complete document.
            // Set to null to disable paste support:
            pasteZone: $(document),
            // The file input field(s), that are listened to for change events.
            // If undefined, it is set to the file input fields inside
            // of the widget element on plugin initialization.
            // Set to null to disable the change listener.
            fileInput: undefined,
            // By default, the file input field is replaced with a clone after
            // each input field change event. This is required for iframe transport
            // queues and allows change events to be fired for the same file
            // selection, but can be disabled by setting the following option to false:
            replaceFileInput: true,
            // The parameter name for the file form data (the request argument name).
            // If undefined or empty, the name property of the file input field is
            // used, or "files[]" if the file input name property is also empty,
            // can be a string or an array of strings:
            paramName: undefined,
            // By default, each file of a selection is uploaded using an individual
            // request for XHR type uploads. Set to false to upload file
            // selections in one request each:
            singleFileUploads: true,
            // To limit the number of files uploaded with one XHR request,
            // set the following option to an integer greater than 0:
            limitMultiFileUploads: undefined,
            // The following option limits the number of files uploaded with one
            // XHR request to keep the request size under or equal to the defined
            // limit in bytes:
            limitMultiFileUploadSize: undefined,
            // Multipart file uploads add a number of bytes to each uploaded file,
            // therefore the following option adds an overhead for each file used
            // in the limitMultiFileUploadSize configuration:
            limitMultiFileUploadSizeOverhead: 512,
            // Set the following option to true to issue all file upload requests
            // in a sequential order:
            sequentialUploads: false,
            // To limit the number of concurrent uploads,
            // set the following option to an integer greater than 0:
            limitConcurrentUploads: undefined,
            // Set the following option to true to force iframe transport uploads:
            forceIframeTransport: false,
            // Set the following option to the location of a redirect url on the
            // origin server, for cross-domain iframe transport uploads:
            redirect: undefined,
            // The parameter name for the redirect url, sent as part of the form
            // data and set to 'redirect' if this option is empty:
            redirectParamName: undefined,
            // Set the following option to the location of a postMessage window,
            // to enable postMessage transport uploads:
            postMessage: undefined,
            // By default, XHR file uploads are sent as multipart/form-data.
            // The iframe transport is always using multipart/form-data.
            // Set to false to enable non-multipart XHR uploads:
            multipart: true,
            // To upload large files in smaller chunks, set the following option
            // to a preferred maximum chunk size. If set to 0, null or undefined,
            // or the browser does not support the required Blob API, files will
            // be uploaded as a whole.
            maxChunkSize: undefined,
            // When a non-multipart upload or a chunked multipart upload has been
            // aborted, this option can be used to resume the upload by setting
            // it to the size of the already uploaded bytes. This option is most
            // useful when modifying the options object inside of the "add" or
            // "send" callbacks, as the options are cloned for each file upload.
            uploadedBytes: undefined,
            // By default, failed (abort or error) file uploads are removed from the
            // global progress calculation. Set the following option to false to
            // prevent recalculating the global progress data:
            recalculateProgress: true,
            // Interval in milliseconds to calculate and trigger progress events:
            progressInterval: 100,
            // Interval in milliseconds to calculate progress bitrate:
            bitrateInterval: 500,
            // By default, uploads are started automatically when adding files:
            autoUpload: true,

            // Error and info messages:
            messages: {
                uploadedBytes: 'Uploaded bytes exceed file size'
            },

            // Translation function, gets the message key to be translated
            // and an object with context specific data as arguments:
            i18n: function (message, context) {
                message = this.messages[message] || message.toString();
                if (context) {
                    $.each(context, function (key, value) {
                        message = message.replace('{' + key + '}', value);
                    });
                }
                return message;
            },

            // Additional form data to be sent along with the file uploads can be set
            // using this option, which accepts an array of objects with name and
            // value properties, a function returning such an array, a FormData
            // object (for XHR file uploads), or a simple object.
            // The form of the first fileInput is given as parameter to the function:
            formData: function (form) {
                return form.serializeArray();
            },

            // The add callback is invoked as soon as files are added to the fileupload
            // widget (via file input selection, drag & drop, paste or add API call).
            // If the singleFileUploads option is enabled, this callback will be
            // called once for each file in the selection for XHR file uploads, else
            // once for each file selection.
            //
            // The upload starts when the submit method is invoked on the data parameter.
            // The data object contains a files property holding the added files
            // and allows you to override plugin options as well as define ajax settings.
            //
            // Listeners for this callback can also be bound the following way:
            // .bind('fileuploadadd', func);
            //
            // data.submit() returns a Promise object and allows to attach additional
            // handlers using jQuery's Deferred callbacks:
            // data.submit().done(func).fail(func).always(func);
            add: function (e, data) {
                if (e.isDefaultPrevented()) {
                    return false;
                }
                if (data.autoUpload || (data.autoUpload !== false &&
                        $(this).fileupload('option', 'autoUpload'))) {
                    data.process().done(function () {
                        data.submit();
                    });
                }
            },

            // Other callbacks:

            // Callback for the submit event of each file upload:
            // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);

            // Callback for the start of each file upload request:
            // send: function (e, data) {}, // .bind('fileuploadsend', func);

            // Callback for successful uploads:
            // done: function (e, data) {}, // .bind('fileuploaddone', func);

            // Callback for failed (abort or error) uploads:
            // fail: function (e, data) {}, // .bind('fileuploadfail', func);

            // Callback for completed (success, abort or error) requests:
            // always: function (e, data) {}, // .bind('fileuploadalways', func);

            // Callback for upload progress events:
            // progress: function (e, data) {}, // .bind('fileuploadprogress', func);

            // Callback for global upload progress events:
            // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);

            // Callback for uploads start, equivalent to the global ajaxStart event:
            // start: function (e) {}, // .bind('fileuploadstart', func);

            // Callback for uploads stop, equivalent to the global ajaxStop event:
            // stop: function (e) {}, // .bind('fileuploadstop', func);

            // Callback for change events of the fileInput(s):
            // change: function (e, data) {}, // .bind('fileuploadchange', func);

            // Callback for paste events to the pasteZone(s):
            // paste: function (e, data) {}, // .bind('fileuploadpaste', func);

            // Callback for drop events of the dropZone(s):
            // drop: function (e, data) {}, // .bind('fileuploaddrop', func);

            // Callback for dragover events of the dropZone(s):
            // dragover: function (e) {}, // .bind('fileuploaddragover', func);

            // Callback for the start of each chunk upload request:
            // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func);

            // Callback for successful chunk uploads:
            // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func);

            // Callback for failed (abort or error) chunk uploads:
            // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func);

            // Callback for completed (success, abort or error) chunk upload requests:
            // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func);

            // The plugin options are used as settings object for the ajax calls.
            // The following are jQuery ajax settings required for the file uploads:
            processData: false,
            contentType: false,
            cache: false
        },

        // A list of options that require reinitializing event listeners and/or
        // special initialization code:
        _specialOptions: [
            'fileInput',
            'dropZone',
            'pasteZone',
            'multipart',
            'forceIframeTransport'
        ],

        _blobSlice: $.support.blobSlice && function () {
            var slice = this.slice || this.webkitSlice || this.mozSlice;
            return slice.apply(this, arguments);
        },

        _BitrateTimer: function () {
            this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime());
            this.loaded = 0;
            this.bitrate = 0;
            this.getBitrate = function (now, loaded, interval) {
                var timeDiff = now - this.timestamp;
                if (!this.bitrate || !interval || timeDiff > interval) {
                    this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8;
                    this.loaded = loaded;
                    this.timestamp = now;
                }
                return this.bitrate;
            };
        },

        _isXHRUpload: function (options) {
            return !options.forceIframeTransport &&
                ((!options.multipart && $.support.xhrFileUpload) ||
                $.support.xhrFormDataFileUpload);
        },

        _getFormData: function (options) {
            var formData;
            if ($.type(options.formData) === 'function') {
                return options.formData(options.form);
            }
            if ($.isArray(options.formData)) {
                return options.formData;
            }
            if ($.type(options.formData) === 'object') {
                formData = [];
                $.each(options.formData, function (name, value) {
                    formData.push({name: name, value: value});
                });
                return formData;
            }
            return [];
        },

        _getTotal: function (files) {
            var total = 0;
            $.each(files, function (index, file) {
                total += file.size || 1;
            });
            return total;
        },

        _initProgressObject: function (obj) {
            var progress = {
                loaded: 0,
                total: 0,
                bitrate: 0
            };
            if (obj._progress) {
                $.extend(obj._progress, progress);
            } else {
                obj._progress = progress;
            }
        },

        _initResponseObject: function (obj) {
            var prop;
            if (obj._response) {
                for (prop in obj._response) {
                    if (obj._response.hasOwnProperty(prop)) {
                        delete obj._response[prop];
                    }
                }
            } else {
                obj._response = {};
            }
        },

        _onProgress: function (e, data) {
            if (e.lengthComputable) {
                var now = ((Date.now) ? Date.now() : (new Date()).getTime()),
                    loaded;
                if (data._time && data.progressInterval &&
                        (now - data._time < data.progressInterval) &&
                        e.loaded !== e.total) {
                    return;
                }
                data._time = now;
                loaded = Math.floor(
                    e.loaded / e.total * (data.chunkSize || data._progress.total)
                ) + (data.uploadedBytes || 0);
                // Add the difference from the previously loaded state
                // to the global loaded counter:
                this._progress.loaded += (loaded - data._progress.loaded);
                this._progress.bitrate = this._bitrateTimer.getBitrate(
                    now,
                    this._progress.loaded,
                    data.bitrateInterval
                );
                data._progress.loaded = data.loaded = loaded;
                data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate(
                    now,
                    loaded,
                    data.bitrateInterval
                );
                // Trigger a custom progress event with a total data property set
                // to the file size(s) of the current upload and a loaded data
                // property calculated accordingly:
                this._trigger(
                    'progress',
                    $.Event('progress', {delegatedEvent: e}),
                    data
                );
                // Trigger a global progress event for all current file uploads,
                // including ajax calls queued for sequential file uploads:
                this._trigger(
                    'progressall',
                    $.Event('progressall', {delegatedEvent: e}),
                    this._progress
                );
            }
        },

        _initProgressListener: function (options) {
            var that = this,
                xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr();
            // Accesss to the native XHR object is required to add event listeners
            // for the upload progress event:
            if (xhr.upload) {
                $(xhr.upload).bind('progress', function (e) {
                    var oe = e.originalEvent;
                    // Make sure the progress event properties get copied over:
                    e.lengthComputable = oe.lengthComputable;
                    e.loaded = oe.loaded;
                    e.total = oe.total;
                    that._onProgress(e, options);
                });
                options.xhr = function () {
                    return xhr;
                };
            }
        },

        _isInstanceOf: function (type, obj) {
            // Cross-frame instanceof check
            return Object.prototype.toString.call(obj) === '[object ' + type + ']';
        },

        _initXHRData: function (options) {
            var that = this,
                formData,
                file = options.files[0],
                // Ignore non-multipart setting if not supported:
                multipart = options.multipart || !$.support.xhrFileUpload,
                paramName = $.type(options.paramName) === 'array' ?
                    options.paramName[0] : options.paramName;
            options.headers = $.extend({}, options.headers);
            if (options.contentRange) {
                options.headers['Content-Range'] = options.contentRange;
            }
            if (!multipart || options.blob || !this._isInstanceOf('File', file)) {
                options.headers['Content-Disposition'] = 'attachment; filename="' +
                    encodeURI(file.name) + '"';
            }
            if (!multipart) {
                options.contentType = file.type || 'application/octet-stream';
                options.data = options.blob || file;
            } else if ($.support.xhrFormDataFileUpload) {
                if (options.postMessage) {
                    // window.postMessage does not allow sending FormData
                    // objects, so we just add the File/Blob objects to
                    // the formData array and let the postMessage window
                    // create the FormData object out of this array:
                    formData = this._getFormData(options);
                    if (options.blob) {
                        formData.push({
                            name: paramName,
                            value: options.blob
                        });
                    } else {
                        $.each(options.files, function (index, file) {
                            formData.push({
                                name: ($.type(options.paramName) === 'array' &&
                                    options.paramName[index]) || paramName,
                                value: file
                            });
                        });
                    }
                } else {
                    if (that._isInstanceOf('FormData', options.formData)) {
                        formData = options.formData;
                    } else {
                        formData = new FormData();
                        $.each(this._getFormData(options), function (index, field) {
                            formData.append(field.name, field.value);
                        });
                    }
                    if (options.blob) {
                        formData.append(paramName, options.blob, file.name);
                    } else {
                        $.each(options.files, function (index, file) {
                            // This check allows the tests to run with
                            // dummy objects:
                            if (that._isInstanceOf('File', file) ||
                                    that._isInstanceOf('Blob', file)) {
                                formData.append(
                                    ($.type(options.paramName) === 'array' &&
                                        options.paramName[index]) || paramName,
                                    file,
                                    file.uploadName || file.name
                                );
                            }
                        });
                    }
                }
                options.data = formData;
            }
            // Blob reference is not needed anymore, free memory:
            options.blob = null;
        },

        _initIframeSettings: function (options) {
            var targetHost = $('<a></a>').prop('href', options.url).prop('host');
            // Setting the dataType to iframe enables the iframe transport:
            options.dataType = 'iframe ' + (options.dataType || '');
            // The iframe transport accepts a serialized array as form data:
            options.formData = this._getFormData(options);
            // Add redirect url to form data on cross-domain uploads:
            if (options.redirect && targetHost && targetHost !== location.host) {
                options.formData.push({
                    name: options.redirectParamName || 'redirect',
                    value: options.redirect
                });
            }
        },

        _initDataSettings: function (options) {
            if (this._isXHRUpload(options)) {
                if (!this._chunkedUpload(options, true)) {
                    if (!options.data) {
                        this._initXHRData(options);
                    }
                    this._initProgressListener(options);
                }
                if (options.postMessage) {
                    // Setting the dataType to postmessage enables the
                    // postMessage transport:
                    options.dataType = 'postmessage ' + (options.dataType || '');
                }
            } else {
                this._initIframeSettings(options);
            }
        },

        _getParamName: function (options) {
            var fileInput = $(options.fileInput),
                paramName = options.paramName;
            if (!paramName) {
                paramName = [];
                fileInput.each(function () {
                    var input = $(this),
                        name = input.prop('name') || 'files[]',
                        i = (input.prop('files') || [1]).length;
                    while (i) {
                        paramName.push(name);
                        i -= 1;
                    }
                });
                if (!paramName.length) {
                    paramName = [fileInput.prop('name') || 'files[]'];
                }
            } else if (!$.isArray(paramName)) {
                paramName = [paramName];
            }
            return paramName;
        },

        _initFormSettings: function (options) {
            // Retrieve missing options from the input field and the
            // associated form, if available:
            if (!options.form || !options.form.length) {
                options.form = $(options.fileInput.prop('form'));
                // If the given file input doesn't have an associated form,
                // use the default widget file input's form:
                if (!options.form.length) {
                    options.form = $(this.options.fileInput.prop('form'));
                }
            }
            options.paramName = this._getParamName(options);
            if (!options.url) {
                options.url = options.form.prop('action') || location.href;
            }
            // The HTTP request method must be "POST" or "PUT":
            options.type = (options.type ||
                ($.type(options.form.prop('method')) === 'string' &&
                    options.form.prop('method')) || ''
                ).toUpperCase();
            if (options.type !== 'POST' && options.type !== 'PUT' &&
                    options.type !== 'PATCH') {
                options.type = 'POST';
            }
            if (!options.formAcceptCharset) {
                options.formAcceptCharset = options.form.attr('accept-charset');
            }
        },

        _getAJAXSettings: function (data) {
            var options = $.extend({}, this.options, data);
            this._initFormSettings(options);
            this._initDataSettings(options);
            return options;
        },

        // jQuery 1.6 doesn't provide .state(),
        // while jQuery 1.8+ removed .isRejected() and .isResolved():
        _getDeferredState: function (deferred) {
            if (deferred.state) {
                return deferred.state();
            }
            if (deferred.isResolved()) {
                return 'resolved';
            }
            if (deferred.isRejected()) {
                return 'rejected';
            }
            return 'pending';
        },

        // Maps jqXHR callbacks to the equivalent
        // methods of the given Promise object:
        _enhancePromise: function (promise) {
            promise.success = promise.done;
            promise.error = promise.fail;
            promise.complete = promise.always;
            return promise;
        },

        // Creates and returns a Promise object enhanced with
        // the jqXHR methods abort, success, error and complete:
        _getXHRPromise: function (resolveOrReject, context, args) {
            var dfd = $.Deferred(),
                promise = dfd.promise();
            context = context || this.options.context || promise;
            if (resolveOrReject === true) {
                dfd.resolveWith(context, args);
            } else if (resolveOrReject === false) {
                dfd.rejectWith(context, args);
            }
            promise.abort = dfd.promise;
            return this._enhancePromise(promise);
        },

        // Adds convenience methods to the data callback argument:
        _addConvenienceMethods: function (e, data) {
            var that = this,
                getPromise = function (args) {
                    return $.Deferred().resolveWith(that, args).promise();
                };
            data.process = function (resolveFunc, rejectFunc) {
                if (resolveFunc || rejectFunc) {
                    data._processQueue = this._processQueue =
                        (this._processQueue || getPromise([this])).pipe(
                            function () {
                                if (data.errorThrown) {
                                    return $.Deferred()
                                        .rejectWith(that, [data]).promise();
                                }
                                return getPromise(arguments);
                            }
                        ).pipe(resolveFunc, rejectFunc);
                }
                return this._processQueue || getPromise([this]);
            };
            data.submit = function () {
                if (this.state() !== 'pending') {
                    data.jqXHR = this.jqXHR =
                        (that._trigger(
                            'submit',
                            $.Event('submit', {delegatedEvent: e}),
                            this
                        ) !== false) && that._onSend(e, this);
                }
                return this.jqXHR || that._getXHRPromise();
            };
            data.abort = function () {
                if (this.jqXHR) {
                    return this.jqXHR.abort();
                }
                this.errorThrown = 'abort';
                that._trigger('fail', null, this);
                return that._getXHRPromise(false);
            };
            data.state = function () {
                if (this.jqXHR) {
                    return that._getDeferredState(this.jqXHR);
                }
                if (this._processQueue) {
                    return that._getDeferredState(this._processQueue);
                }
            };
            data.processing = function () {
                return !this.jqXHR && this._processQueue && that
                    ._getDeferredState(this._processQueue) === 'pending';
            };
            data.progress = function () {
                return this._progress;
            };
            data.response = function () {
                return this._response;
            };
        },

        // Parses the Range header from the server response
        // and returns the uploaded bytes:
        _getUploadedBytes: function (jqXHR) {
            var range = jqXHR.getResponseHeader('Range'),
                parts = range && range.split('-'),
                upperBytesPos = parts && parts.length > 1 &&
                    parseInt(parts[1], 10);
            return upperBytesPos && upperBytesPos + 1;
        },

        // Uploads a file in multiple, sequential requests
        // by splitting the file up in multiple blob chunks.
        // If the second parameter is true, only tests if the file
        // should be uploaded in chunks, but does not invoke any
        // upload requests:
        _chunkedUpload: function (options, testOnly) {
            options.uploadedBytes = options.uploadedBytes || 0;
            var that = this,
                file = options.files[0],
                fs = file.size,
                ub = options.uploadedBytes,
                mcs = options.maxChunkSize || fs,
                slice = this._blobSlice,
                dfd = $.Deferred(),
                promise = dfd.promise(),
                jqXHR,
                upload;
            if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) ||
                    options.data) {
                return false;
            }
            if (testOnly) {
                return true;
            }
            if (ub >= fs) {
                file.error = options.i18n('uploadedBytes');
                return this._getXHRPromise(
                    false,
                    options.context,
                    [null, 'error', file.error]
                );
            }
            // The chunk upload method:
            upload = function () {
                // Clone the options object for each chunk upload:
                var o = $.extend({}, options),
                    currentLoaded = o._progress.loaded;
                o.blob = slice.call(
                    file,
                    ub,
                    ub + mcs,
                    file.type
                );
                // Store the current chunk size, as the blob itself
                // will be dereferenced after data processing:
                o.chunkSize = o.blob.size;
                // Expose the chunk bytes position range:
                o.contentRange = 'bytes ' + ub + '-' +
                    (ub + o.chunkSize - 1) + '/' + fs;
                // Process the upload data (the blob and potential form data):
                that._initXHRData(o);
                // Add progress listeners for this chunk upload:
                that._initProgressListener(o);
                jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) ||
                        that._getXHRPromise(false, o.context))
                    .done(function (result, textStatus, jqXHR) {
                        ub = that._getUploadedBytes(jqXHR) ||
                            (ub + o.chunkSize);
                        // Create a progress event if no final progress event
                        // with loaded equaling total has been triggered
                        // for this chunk:
                        if (currentLoaded + o.chunkSize - o._progress.loaded) {
                            that._onProgress($.Event('progress', {
                                lengthComputable: true,
                                loaded: ub - o.uploadedBytes,
                                total: ub - o.uploadedBytes
                            }), o);
                        }
                        options.uploadedBytes = o.uploadedBytes = ub;
                        o.result = result;
                        o.textStatus = textStatus;
                        o.jqXHR = jqXHR;
                        that._trigger('chunkdone', null, o);
                        that._trigger('chunkalways', null, o);
                        if (ub < fs) {
                            // File upload not yet complete,
                            // continue with the next chunk:
                            upload();
                        } else {
                            dfd.resolveWith(
                                o.context,
                                [result, textStatus, jqXHR]
                            );
                        }
                    })
                    .fail(function (jqXHR, textStatus, errorThrown) {
                        o.jqXHR = jqXHR;
                        o.textStatus = textStatus;
                        o.errorThrown = errorThrown;
                        that._trigger('chunkfail', null, o);
                        that._trigger('chunkalways', null, o);
                        dfd.rejectWith(
                            o.context,
                            [jqXHR, textStatus, errorThrown]
                        );
                    });
            };
            this._enhancePromise(promise);
            promise.abort = function () {
                return jqXHR.abort();
            };
            upload();
            return promise;
        },

        _beforeSend: function (e, data) {
            if (this._active === 0) {
                // the start callback is triggered when an upload starts
                // and no other uploads are currently running,
                // equivalent to the global ajaxStart event:
                this._trigger('start');
                // Set timer for global bitrate progress calculation:
                this._bitrateTimer = new this._BitrateTimer();
                // Reset the global progress values:
                this._progress.loaded = this._progress.total = 0;
                this._progress.bitrate = 0;
            }
            // Make sure the container objects for the .response() and
            // .progress() methods on the data object are available
            // and reset to their initial state:
            this._initResponseObject(data);
            this._initProgressObject(data);
            data._progress.loaded = data.loaded = data.uploadedBytes || 0;
            data._progress.total = data.total = this._getTotal(data.files) || 1;
            data._progress.bitrate = data.bitrate = 0;
            this._active += 1;
            // Initialize the global progress values:
            this._progress.loaded += data.loaded;
            this._progress.total += data.total;
        },

        _onDone: function (result, textStatus, jqXHR, options) {
            var total = options._progress.total,
                response = options._response;
            if (options._progress.loaded < total) {
                // Create a progress event if no final progress event
                // with loaded equaling total has been triggered:
                this._onProgress($.Event('progress', {
                    lengthComputable: true,
                    loaded: total,
                    total: total
                }), options);
            }
            response.result = options.result = result;
            response.textStatus = options.textStatus = textStatus;
            response.jqXHR = options.jqXHR = jqXHR;
            this._trigger('done', null, options);
        },

        _onFail: function (jqXHR, textStatus, errorThrown, options) {
            var response = options._response;
            if (options.recalculateProgress) {
                // Remove the failed (error or abort) file upload from
                // the global progress calculation:
                this._progress.loaded -= options._progress.loaded;
                this._progress.total -= options._progress.total;
            }
            response.jqXHR = options.jqXHR = jqXHR;
            response.textStatus = options.textStatus = textStatus;
            response.errorThrown = options.errorThrown = errorThrown;
            this._trigger('fail', null, options);
        },

        _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) {
            // jqXHRorResult, textStatus and jqXHRorError are added to the
            // options object via done and fail callbacks
            this._trigger('always', null, options);
        },

        _onSend: function (e, data) {
            if (!data.submit) {
                this._addConvenienceMethods(e, data);
            }
            var that = this,
                jqXHR,
                aborted,
                slot,
                pipe,
                options = that._getAJAXSettings(data),
                send = function () {
                    that._sending += 1;
                    // Set timer for bitrate progress calculation:
                    options._bitrateTimer = new that._BitrateTimer();
                    jqXHR = jqXHR || (
                        ((aborted || that._trigger(
                            'send',
                            $.Event('send', {delegatedEvent: e}),
                            options
                        ) === false) &&
                        that._getXHRPromise(false, options.context, aborted)) ||
                        that._chunkedUpload(options) || $.ajax(options)
                    ).done(function (result, textStatus, jqXHR) {
                        that._onDone(result, textStatus, jqXHR, options);
                    }).fail(function (jqXHR, textStatus, errorThrown) {
                        that._onFail(jqXHR, textStatus, errorThrown, options);
                    }).always(function (jqXHRorResult, textStatus, jqXHRorError) {
                        that._onAlways(
                            jqXHRorResult,
                            textStatus,
                            jqXHRorError,
                            options
                        );
                        that._sending -= 1;
                        that._active -= 1;
                        if (options.limitConcurrentUploads &&
                                options.limitConcurrentUploads > that._sending) {
                            // Start the next queued upload,
                            // that has not been aborted:
                            var nextSlot = that._slots.shift();
                            while (nextSlot) {
                                if (that._getDeferredState(nextSlot) === 'pending') {
                                    nextSlot.resolve();
                                    break;
                                }
                                nextSlot = that._slots.shift();
                            }
                        }
                        if (that._active === 0) {
                            // The stop callback is triggered when all uploads have
                            // been completed, equivalent to the global ajaxStop event:
                            that._trigger('stop');
                        }
                    });
                    return jqXHR;
                };
            this._beforeSend(e, options);
            if (this.options.sequentialUploads ||
                    (this.options.limitConcurrentUploads &&
                    this.options.limitConcurrentUploads <= this._sending)) {
                if (this.options.limitConcurrentUploads > 1) {
                    slot = $.Deferred();
                    this._slots.push(slot);
                    pipe = slot.pipe(send);
                } else {
                    this._sequence = this._sequence.pipe(send, send);
                    pipe = this._sequence;
                }
                // Return the piped Promise object, enhanced with an abort method,
                // which is delegated to the jqXHR object of the current upload,
                // and jqXHR callbacks mapped to the equivalent Promise methods:
                pipe.abort = function () {
                    aborted = [undefined, 'abort', 'abort'];
                    if (!jqXHR) {
                        if (slot) {
                            slot.rejectWith(options.context, aborted);
                        }
                        return send();
                    }
                    return jqXHR.abort();
                };
                return this._enhancePromise(pipe);
            }
            return send();
        },

        _onAdd: function (e, data) {
            var that = this,
                result = true,
                options = $.extend({}, this.options, data),
                files = data.files,
                filesLength = files.length,
                limit = options.limitMultiFileUploads,
                limitSize = options.limitMultiFileUploadSize,
                overhead = options.limitMultiFileUploadSizeOverhead,
                batchSize = 0,
                paramName = this._getParamName(options),
                paramNameSet,
                paramNameSlice,
                fileSet,
                i,
                j = 0;
            if (limitSize && (!filesLength || files[0].size === undefined)) {
                limitSize = undefined;
            }
            if (!(options.singleFileUploads || limit || limitSize) ||
                    !this._isXHRUpload(options)) {
                fileSet = [files];
                paramNameSet = [paramName];
            } else if (!(options.singleFileUploads || limitSize) && limit) {
                fileSet = [];
                paramNameSet = [];
                for (i = 0; i < filesLength; i += limit) {
                    fileSet.push(files.slice(i, i + limit));
                    paramNameSlice = paramName.slice(i, i + limit);
                    if (!paramNameSlice.length) {
                        paramNameSlice = paramName;
                    }
                    paramNameSet.push(paramNameSlice);
                }
            } else if (!options.singleFileUploads && limitSize) {
                fileSet = [];
                paramNameSet = [];
                for (i = 0; i < filesLength; i = i + 1) {
                    batchSize += files[i].size + overhead;
                    if (i + 1 === filesLength ||
                            ((batchSize + files[i + 1].size + overhead) > limitSize) ||
                            (limit && i + 1 - j >= limit)) {
                        fileSet.push(files.slice(j, i + 1));
                        paramNameSlice = paramName.slice(j, i + 1);
                        if (!paramNameSlice.length) {
                            paramNameSlice = paramName;
                        }
                        paramNameSet.push(paramNameSlice);
                        j = i + 1;
                        batchSize = 0;
                    }
                }
            } else {
                paramNameSet = paramName;
            }
            data.originalFiles = files;
            $.each(fileSet || files, function (index, element) {
                var newData = $.extend({}, data);
                newData.files = fileSet ? element : [element];
                newData.paramName = paramNameSet[index];
                that._initResponseObject(newData);
                that._initProgressObject(newData);
                that._addConvenienceMethods(e, newData);
                result = that._trigger(
                    'add',
                    $.Event('add', {delegatedEvent: e}),
                    newData
                );
                return result;
            });
            return result;
        },

        _replaceFileInput: function (data) {
            var input = data.fileInput,
                inputClone = input.clone(true);
            // Add a reference for the new cloned file input to the data argument:
            data.fileInputClone = inputClone;
            $('<form></form>').append(inputClone)[0].reset();
            // Detaching allows to insert the fileInput on another form
            // without loosing the file input value:
            input.after(inputClone).detach();
            // Avoid memory leaks with the detached file input:
            $.cleanData(input.unbind('remove'));
            // Replace the original file input element in the fileInput
            // elements set with the clone, which has been copied including
            // event handlers:
            this.options.fileInput = this.options.fileInput.map(function (i, el) {
                if (el === input[0]) {
                    return inputClone[0];
                }
                return el;
            });
            // If the widget has been initialized on the file input itself,
            // override this.element with the file input clone:
            if (input[0] === this.element[0]) {
                this.element = inputClone;
            }
        },

        _handleFileTreeEntry: function (entry, path) {
            var that = this,
                dfd = $.Deferred(),
                errorHandler = function (e) {
                    if (e && !e.entry) {
                        e.entry = entry;
                    }
                    // Since $.when returns immediately if one
                    // Deferred is rejected, we use resolve instead.
                    // This allows valid files and invalid items
                    // to be returned together in one set:
                    dfd.resolve([e]);
                },
                successHandler = function (entries) {
                    that._handleFileTreeEntries(
                        entries,
                        path + entry.name + '/'
                    ).done(function (files) {
                        dfd.resolve(files);
                    }).fail(errorHandler);
                },
                readEntries = function () {
                    dirReader.readEntries(function (results) {
                        if (!results.length) {
                            successHandler(entries);
                        } else {
                            entries = entries.concat(results);
                            readEntries();
                        }
                    }, errorHandler);
                },
                dirReader, entries = [];
            path = path || '';
            if (entry.isFile) {
                if (entry._file) {
                    // Workaround for Chrome bug #149735
                    entry._file.relativePath = path;
                    dfd.resolve(entry._file);
                } else {
                    entry.file(function (file) {
                        file.relativePath = path;
                        dfd.resolve(file);
                    }, errorHandler);
                }
            } else if (entry.isDirectory) {
                dirReader = entry.createReader();
                readEntries();
            } else {
                // Return an empy list for file system items
                // other than files or directories:
                dfd.resolve([]);
            }
            return dfd.promise();
        },

        _handleFileTreeEntries: function (entries, path) {
            var that = this;
            return $.when.apply(
                $,
                $.map(entries, function (entry) {
                    return that._handleFileTreeEntry(entry, path);
                })
            ).pipe(function () {
                return Array.prototype.concat.apply(
                    [],
                    arguments
                );
            });
        },

        _getDroppedFiles: function (dataTransfer) {
            dataTransfer = dataTransfer || {};
            var items = dataTransfer.items;
            if (items && items.length && (items[0].webkitGetAsEntry ||
                    items[0].getAsEntry)) {
                return this._handleFileTreeEntries(
                    $.map(items, function (item) {
                        var entry;
                        if (item.webkitGetAsEntry) {
                            entry = item.webkitGetAsEntry();
                            if (entry) {
                                // Workaround for Chrome bug #149735:
                                entry._file = item.getAsFile();
                            }
                            return entry;
                        }
                        return item.getAsEntry();
                    })
                );
            }
            return $.Deferred().resolve(
                $.makeArray(dataTransfer.files)
            ).promise();
        },

        _getSingleFileInputFiles: function (fileInput) {
            fileInput = $(fileInput);
            var entries = fileInput.prop('webkitEntries') ||
                    fileInput.prop('entries'),
                files,
                value;
            if (entries && entries.length) {
                return this._handleFileTreeEntries(entries);
            }
            files = $.makeArray(fileInput.prop('files'));
            if (!files.length) {
                value = fileInput.prop('value');
                if (!value) {
                    return $.Deferred().resolve([]).promise();
                }
                // If the files property is not available, the browser does not
                // support the File API and we add a pseudo File object with
                // the input value as name with path information removed:
                files = [{name: value.replace(/^.*\\/, '')}];
            } else if (files[0].name === undefined && files[0].fileName) {
                // File normalization for Safari 4 and Firefox 3:
                $.each(files, function (index, file) {
                    file.name = file.fileName;
                    file.size = file.fileSize;
                });
            }
            return $.Deferred().resolve(files).promise();
        },

        _getFileInputFiles: function (fileInput) {
            if (!(fileInput instanceof $) || fileInput.length === 1) {
                return this._getSingleFileInputFiles(fileInput);
            }
            return $.when.apply(
                $,
                $.map(fileInput, this._getSingleFileInputFiles)
            ).pipe(function () {
                return Array.prototype.concat.apply(
                    [],
                    arguments
                );
            });
        },

        _onChange: function (e) {
            var that = this,
                data = {
                    fileInput: $(e.target),
                    form: $(e.target.form)
                };
            this._getFileInputFiles(data.fileInput).always(function (files) {
                data.files = files;
                if (that.options.replaceFileInput) {
                    that._replaceFileInput(data);
                }
                if (that._trigger(
                        'change',
                        $.Event('change', {delegatedEvent: e}),
                        data
                    ) !== false) {
                    that._onAdd(e, data);
                }
            });
        },

        _onPaste: function (e) {
            var items = e.originalEvent && e.originalEvent.clipboardData &&
                    e.originalEvent.clipboardData.items,
                data = {files: []};
            if (items && items.length) {
                $.each(items, function (index, item) {
                    var file = item.getAsFile && item.getAsFile();
                    if (file) {
                        data.files.push(file);
                    }
                });
                if (this._trigger(
                        'paste',
                        $.Event('paste', {delegatedEvent: e}),
                        data
                    ) !== false) {
                    this._onAdd(e, data);
                }
            }
        },

        _onDrop: function (e) {
            e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
            var that = this,
                dataTransfer = e.dataTransfer,
                data = {};
            if (dataTransfer && dataTransfer.files && dataTransfer.files.length) {
                e.preventDefault();
                this._getDroppedFiles(dataTransfer).always(function (files) {
                    data.files = files;
                    if (that._trigger(
                            'drop',
                            $.Event('drop', {delegatedEvent: e}),
                            data
                        ) !== false) {
                        that._onAdd(e, data);
                    }
                });
            }
        },

        _onDragOver: function (e) {
            e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer;
            var dataTransfer = e.dataTransfer;
            if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1 &&
                    this._trigger(
                        'dragover',
                        $.Event('dragover', {delegatedEvent: e})
                    ) !== false) {
                e.preventDefault();
                dataTransfer.dropEffect = 'copy';
            }
        },

        _initEventHandlers: function () {
            if (this._isXHRUpload(this.options)) {
                this._on(this.options.dropZone, {
                    dragover: this._onDragOver,
                    drop: this._onDrop
                });
                this._on(this.options.pasteZone, {
                    paste: this._onPaste
                });
            }
            if ($.support.fileInput) {
                this._on(this.options.fileInput, {
                    change: this._onChange
                });
            }
        },

        _destroyEventHandlers: function () {
            this._off(this.options.dropZone, 'dragover drop');
            this._off(this.options.pasteZone, 'paste');
            this._off(this.options.fileInput, 'change');
        },

        _setOption: function (key, value) {
            var reinit = $.inArray(key, this._specialOptions) !== -1;
            if (reinit) {
                this._destroyEventHandlers();
            }
            this._super(key, value);
            if (reinit) {
                this._initSpecialOptions();
                this._initEventHandlers();
            }
        },

        _initSpecialOptions: function () {
            var options = this.options;
            if (options.fileInput === undefined) {
                options.fileInput = this.element.is('input[type="file"]') ?
                        this.element : this.element.find('input[type="file"]');
            } else if (!(options.fileInput instanceof $)) {
                options.fileInput = $(options.fileInput);
            }
            if (!(options.dropZone instanceof $)) {
                options.dropZone = $(options.dropZone);
            }
            if (!(options.pasteZone instanceof $)) {
                options.pasteZone = $(options.pasteZone);
            }
        },

        _getRegExp: function (str) {
            var parts = str.split('/'),
                modifiers = parts.pop();
            parts.shift();
            return new RegExp(parts.join('/'), modifiers);
        },

        _isRegExpOption: function (key, value) {
            return key !== 'url' && $.type(value) === 'string' &&
                /^\/.*\/[igm]{0,3}$/.test(value);
        },

        _initDataAttributes: function () {
            var that = this,
                options = this.options,
                clone = $(this.element[0].cloneNode(false));
            // Initialize options set via HTML5 data-attributes:
            $.each(
                clone.data(),
                function (key, value) {
                    var dataAttributeName = 'data-' +
                        // Convert camelCase to hyphen-ated key:
                        key.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
                    if (clone.attr(dataAttributeName)) {
                        if (that._isRegExpOption(key, value)) {
                            value = that._getRegExp(value);
                        }
                        options[key] = value;
                    }
                }
            );
        },

        _create: function () {
            this._initDataAttributes();
            this._initSpecialOptions();
            this._slots = [];
            this._sequence = this._getXHRPromise(true);
            this._sending = this._active = 0;
            this._initProgressObject(this);
            this._initEventHandlers();
        },

        // This method is exposed to the widget API and allows to query
        // the number of active uploads:
        active: function () {
            return this._active;
        },

        // This method is exposed to the widget API and allows to query
        // the widget upload progress.
        // It returns an object with loaded, total and bitrate properties
        // for the running uploads:
        progress: function () {
            return this._progress;
        },

        // This method is exposed to the widget API and allows adding files
        // using the fileupload API. The data parameter accepts an object which
        // must have a files property and can contain additional options:
        // .fileupload('add', {files: filesList});
        add: function (data) {
            var that = this;
            if (!data || this.options.disabled) {
                return;
            }
            if (data.fileInput && !data.files) {
                this._getFileInputFiles(data.fileInput).always(function (files) {
                    data.files = files;
                    that._onAdd(null, data);
                });
            } else {
                data.files = $.makeArray(data.files);
                this._onAdd(null, data);
            }
        },

        // This method is exposed to the widget API and allows sending files
        // using the fileupload API. The data parameter accepts an object which
        // must have a files or fileInput property and can contain additional options:
        // .fileupload('send', {files: filesList});
        // The method returns a Promise object for the file upload call.
        send: function (data) {
            if (data && !this.options.disabled) {
                if (data.fileInput && !data.files) {
                    var that = this,
                        dfd = $.Deferred(),
                        promise = dfd.promise(),
                        jqXHR,
                        aborted;
                    promise.abort = function () {
                        aborted = true;
                        if (jqXHR) {
                            return jqXHR.abort();
                        }
                        dfd.reject(null, 'abort', 'abort');
                        return promise;
                    };
                    this._getFileInputFiles(data.fileInput).always(
                        function (files) {
                            if (aborted) {
                                return;
                            }
                            if (!files.length) {
                                dfd.reject();
                                return;
                            }
                            data.files = files;
                            jqXHR = that._onSend(null, data);
                            jqXHR.then(
                                function (result, textStatus, jqXHR) {
                                    dfd.resolve(result, textStatus, jqXHR);
                                },
                                function (jqXHR, textStatus, errorThrown) {
                                    dfd.reject(jqXHR, textStatus, errorThrown);
                                }
                            );
                        }
                    );
                    return this._enhancePromise(promise);
                }
                data.files = $.makeArray(data.files);
                if (data.files.length) {
                    return this._onSend(null, data);
                }
            }
            return this._getXHRPromise(false, data && data.context);
        }

    });

}));
;
/*!
 * SWFUpload: http://www.swfupload.org, http://swfupload.googlecode.com
 *
 * mmSWFUpload 1.0: Flash upload dialog - http://profandesign.se/swfupload/,  http://www.vinterwebb.se/
 *
 * SWFUpload is (c) 2006-2007 Lars Huring, Olov Nilz�n and Mammon Media and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 * SWFUpload 2 is (c) 2007-2008 Jake Roberts and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
; var SWFUpload; if (SWFUpload == undefined) { SWFUpload = function (a) { this.initSWFUpload(a) } } SWFUpload.prototype.initSWFUpload = function (b) { try { this.customSettings = {}; this.settings = b; this.eventQueue = []; this.movieName = "SWFUpload_" + SWFUpload.movieCount++; this.movieElement = null; SWFUpload.instances[this.movieName] = this; this.initSettings(); this.loadFlash(); this.displayDebugInfo() } catch (a) { delete SWFUpload.instances[this.movieName]; throw a } }; SWFUpload.instances = {}; SWFUpload.movieCount = 0; SWFUpload.version = "2.2.0 2009-03-25"; SWFUpload.QUEUE_ERROR = { QUEUE_LIMIT_EXCEEDED: -100, FILE_EXCEEDS_SIZE_LIMIT: -110, ZERO_BYTE_FILE: -120, INVALID_FILETYPE: -130 }; SWFUpload.UPLOAD_ERROR = { HTTP_ERROR: -200, MISSING_UPLOAD_URL: -210, IO_ERROR: -220, SECURITY_ERROR: -230, UPLOAD_LIMIT_EXCEEDED: -240, UPLOAD_FAILED: -250, SPECIFIED_FILE_ID_NOT_FOUND: -260, FILE_VALIDATION_FAILED: -270, FILE_CANCELLED: -280, UPLOAD_STOPPED: -290 }; SWFUpload.FILE_STATUS = { QUEUED: -1, IN_PROGRESS: -2, ERROR: -3, COMPLETE: -4, CANCELLED: -5 }; SWFUpload.BUTTON_ACTION = { SELECT_FILE: -100, SELECT_FILES: -110, START_UPLOAD: -120 }; SWFUpload.CURSOR = { ARROW: -1, HAND: -2 }; SWFUpload.WINDOW_MODE = { WINDOW: "window", TRANSPARENT: "transparent", OPAQUE: "opaque" }; SWFUpload.completeURL = function (a) { if (typeof (a) !== "string" || a.match(/^https?:\/\//i) || a.match(/^\//)) { return a } var c = window.location.protocol + "//" + window.location.hostname + (window.location.port ? ":" + window.location.port : ""); var b = window.location.pathname.lastIndexOf("/"); if (b <= 0) { path = "/" } else { path = window.location.pathname.substr(0, b) + "/" } return path + a }; SWFUpload.prototype.initSettings = function () { this.ensureDefault = function (b, a) { this.settings[b] = (this.settings[b] == undefined) ? a : this.settings[b] }; this.ensureDefault("upload_url", ""); this.ensureDefault("preserve_relative_urls", false); this.ensureDefault("file_post_name", "Filedata"); this.ensureDefault("post_params", {}); this.ensureDefault("use_query_string", false); this.ensureDefault("requeue_on_error", false); this.ensureDefault("http_success", []); this.ensureDefault("assume_success_timeout", 0); this.ensureDefault("file_types", "*.*"); this.ensureDefault("file_types_description", "All Files"); this.ensureDefault("file_size_limit", 0); this.ensureDefault("file_upload_limit", 0); this.ensureDefault("file_queue_limit", 0); this.ensureDefault("flash_url", "swfupload.swf"); this.ensureDefault("prevent_swf_caching", true); this.ensureDefault("button_image_url", ""); this.ensureDefault("button_width", 1); this.ensureDefault("button_height", 1); this.ensureDefault("button_text", ""); this.ensureDefault("button_text_style", "color: #000000; font-size: 16pt;"); this.ensureDefault("button_text_top_padding", 0); this.ensureDefault("button_text_left_padding", 0); this.ensureDefault("button_action", SWFUpload.BUTTON_ACTION.SELECT_FILES); this.ensureDefault("button_disabled", false); this.ensureDefault("button_placeholder_id", ""); this.ensureDefault("button_placeholder", null); this.ensureDefault("button_cursor", SWFUpload.CURSOR.ARROW); this.ensureDefault("button_window_mode", SWFUpload.WINDOW_MODE.WINDOW); this.ensureDefault("debug", false); this.settings.debug_enabled = this.settings.debug; this.settings.return_upload_start_handler = this.returnUploadStart; this.ensureDefault("swfupload_loaded_handler", null); this.ensureDefault("file_dialog_start_handler", null); this.ensureDefault("file_queued_handler", null); this.ensureDefault("file_queue_error_handler", null); this.ensureDefault("file_dialog_complete_handler", null); this.ensureDefault("upload_start_handler", null); this.ensureDefault("upload_progress_handler", null); this.ensureDefault("upload_error_handler", null); this.ensureDefault("upload_success_handler", null); this.ensureDefault("upload_complete_handler", null); this.ensureDefault("debug_handler", this.debugMessage); this.ensureDefault("custom_settings", {}); this.customSettings = this.settings.custom_settings; if (!!this.settings.prevent_swf_caching) { this.settings.flash_url = this.settings.flash_url + (this.settings.flash_url.indexOf("?") < 0 ? "?" : "&") + "preventswfcaching=" + new Date().getTime() } if (!this.settings.preserve_relative_urls) { this.settings.upload_url = SWFUpload.completeURL(this.settings.upload_url); this.settings.button_image_url = SWFUpload.completeURL(this.settings.button_image_url) } delete this.ensureDefault }; SWFUpload.prototype.loadFlash = function () { var a, b; if (document.getElementById(this.movieName) !== null) { throw "ID " + this.movieName + " is already in use. The Flash Object could not be added" } a = document.getElementById(this.settings.button_placeholder_id) || this.settings.button_placeholder; if (a == undefined) { throw "Could not find the placeholder element: " + this.settings.button_placeholder_id } b = document.createElement("div"); b.innerHTML = this.getFlashHTML(); a.parentNode.replaceChild(b.firstChild, a); if (window[this.movieName] == undefined) { window[this.movieName] = this.getMovieElement() } }; SWFUpload.prototype.getFlashHTML = function () { return ['<object id="', this.movieName, '" type="application/x-shockwave-flash" data="', this.settings.flash_url, '" width="', this.settings.button_width, '" height="', this.settings.button_height, '" class="swfupload">', '<param name="wmode" value="', this.settings.button_window_mode, '" />', '<param name="movie" value="', this.settings.flash_url, '" />', '<param name="quality" value="high" />', '<param name="menu" value="false" />', '<param name="allowScriptAccess" value="always" />', '<param name="flashvars" value="' + this.getFlashVars() + '" />', "</object>"].join("") }; SWFUpload.prototype.getFlashVars = function () { var b = this.buildParamString(); var a = this.settings.http_success.join(","); return ["movieName=", encodeURIComponent(this.movieName), "&amp;uploadURL=", encodeURIComponent(this.settings.upload_url), "&amp;useQueryString=", encodeURIComponent(this.settings.use_query_string), "&amp;requeueOnError=", encodeURIComponent(this.settings.requeue_on_error), "&amp;httpSuccess=", encodeURIComponent(a), "&amp;assumeSuccessTimeout=", encodeURIComponent(this.settings.assume_success_timeout), "&amp;params=", encodeURIComponent(b), "&amp;filePostName=", encodeURIComponent(this.settings.file_post_name), "&amp;fileTypes=", encodeURIComponent(this.settings.file_types), "&amp;fileTypesDescription=", encodeURIComponent(this.settings.file_types_description), "&amp;fileSizeLimit=", encodeURIComponent(this.settings.file_size_limit), "&amp;fileUploadLimit=", encodeURIComponent(this.settings.file_upload_limit), "&amp;fileQueueLimit=", encodeURIComponent(this.settings.file_queue_limit), "&amp;debugEnabled=", encodeURIComponent(this.settings.debug_enabled), "&amp;buttonImageURL=", encodeURIComponent(this.settings.button_image_url), "&amp;buttonWidth=", encodeURIComponent(this.settings.button_width), "&amp;buttonHeight=", encodeURIComponent(this.settings.button_height), "&amp;buttonText=", encodeURIComponent(this.settings.button_text), "&amp;buttonTextTopPadding=", encodeURIComponent(this.settings.button_text_top_padding), "&amp;buttonTextLeftPadding=", encodeURIComponent(this.settings.button_text_left_padding), "&amp;buttonTextStyle=", encodeURIComponent(this.settings.button_text_style), "&amp;buttonAction=", encodeURIComponent(this.settings.button_action), "&amp;buttonDisabled=", encodeURIComponent(this.settings.button_disabled), "&amp;buttonCursor=", encodeURIComponent(this.settings.button_cursor)].join("") }; SWFUpload.prototype.getMovieElement = function () { if (this.movieElement == undefined) { this.movieElement = document.getElementById(this.movieName) } if (this.movieElement === null) { throw "Could not find Flash element" } return this.movieElement }; SWFUpload.prototype.buildParamString = function () { var c = this.settings.post_params; var b = []; if (typeof (c) === "object") { for (var a in c) { if (c.hasOwnProperty(a)) { b.push(encodeURIComponent(a.toString()) + "=" + encodeURIComponent(c[a].toString())) } } } return b.join("&amp;") }; SWFUpload.prototype.destroy = function () { try { this.cancelUpload(null, false); var a = null; a = this.getMovieElement(); if (a && typeof (a.CallFunction) === "unknown") { for (var c in a) { try { if (typeof (a[c]) === "function") { a[c] = null } } catch (e) { } } try { a.parentNode.removeChild(a) } catch (b) { } } window[this.movieName] = null; SWFUpload.instances[this.movieName] = null; delete SWFUpload.instances[this.movieName]; this.movieElement = null; this.settings = null; this.customSettings = null; this.eventQueue = null; this.movieName = null; return true } catch (d) { return false } }; SWFUpload.prototype.displayDebugInfo = function () { this.debug(["---SWFUpload Instance Info---\n", "Version: ", SWFUpload.version, "\n", "Movie Name: ", this.movieName, "\n", "Settings:\n", "\t", "upload_url:               ", this.settings.upload_url, "\n", "\t", "flash_url:                ", this.settings.flash_url, "\n", "\t", "use_query_string:         ", this.settings.use_query_string.toString(), "\n", "\t", "requeue_on_error:         ", this.settings.requeue_on_error.toString(), "\n", "\t", "http_success:             ", this.settings.http_success.join(", "), "\n", "\t", "assume_success_timeout:   ", this.settings.assume_success_timeout, "\n", "\t", "file_post_name:           ", this.settings.file_post_name, "\n", "\t", "post_params:              ", this.settings.post_params.toString(), "\n", "\t", "file_types:               ", this.settings.file_types, "\n", "\t", "file_types_description:   ", this.settings.file_types_description, "\n", "\t", "file_size_limit:          ", this.settings.file_size_limit, "\n", "\t", "file_upload_limit:        ", this.settings.file_upload_limit, "\n", "\t", "file_queue_limit:         ", this.settings.file_queue_limit, "\n", "\t", "debug:                    ", this.settings.debug.toString(), "\n", "\t", "prevent_swf_caching:      ", this.settings.prevent_swf_caching.toString(), "\n", "\t", "button_placeholder_id:    ", this.settings.button_placeholder_id.toString(), "\n", "\t", "button_placeholder:       ", (this.settings.button_placeholder ? "Set" : "Not Set"), "\n", "\t", "button_image_url:         ", this.settings.button_image_url.toString(), "\n", "\t", "button_width:             ", this.settings.button_width.toString(), "\n", "\t", "button_height:            ", this.settings.button_height.toString(), "\n", "\t", "button_text:              ", this.settings.button_text.toString(), "\n", "\t", "button_text_style:        ", this.settings.button_text_style.toString(), "\n", "\t", "button_text_top_padding:  ", this.settings.button_text_top_padding.toString(), "\n", "\t", "button_text_left_padding: ", this.settings.button_text_left_padding.toString(), "\n", "\t", "button_action:            ", this.settings.button_action.toString(), "\n", "\t", "button_disabled:          ", this.settings.button_disabled.toString(), "\n", "\t", "custom_settings:          ", this.settings.custom_settings.toString(), "\n", "Event Handlers:\n", "\t", "swfupload_loaded_handler assigned:  ", (typeof this.settings.swfupload_loaded_handler === "function").toString(), "\n", "\t", "file_dialog_start_handler assigned: ", (typeof this.settings.file_dialog_start_handler === "function").toString(), "\n", "\t", "file_queued_handler assigned:       ", (typeof this.settings.file_queued_handler === "function").toString(), "\n", "\t", "file_queue_error_handler assigned:  ", (typeof this.settings.file_queue_error_handler === "function").toString(), "\n", "\t", "upload_start_handler assigned:      ", (typeof this.settings.upload_start_handler === "function").toString(), "\n", "\t", "upload_progress_handler assigned:   ", (typeof this.settings.upload_progress_handler === "function").toString(), "\n", "\t", "upload_error_handler assigned:      ", (typeof this.settings.upload_error_handler === "function").toString(), "\n", "\t", "upload_success_handler assigned:    ", (typeof this.settings.upload_success_handler === "function").toString(), "\n", "\t", "upload_complete_handler assigned:   ", (typeof this.settings.upload_complete_handler === "function").toString(), "\n", "\t", "debug_handler assigned:             ", (typeof this.settings.debug_handler === "function").toString(), "\n"].join("")) }; SWFUpload.prototype.addSetting = function (b, c, a) { if (c == undefined) { return (this.settings[b] = a) } else { return (this.settings[b] = c) } }; SWFUpload.prototype.getSetting = function (a) { if (this.settings[a] != undefined) { return this.settings[a] } return "" }; SWFUpload.prototype.callFlash = function (functionName, argumentArray) { argumentArray = argumentArray || []; var movieElement = this.getMovieElement(); var returnValue, returnString; try { returnString = movieElement.CallFunction('<invoke name="' + functionName + '" returntype="javascript">' + __flash__argumentsToXML(argumentArray, 0) + "</invoke>"); returnValue = eval(returnString) } catch (ex) { throw "Call to " + functionName + " failed" } if (returnValue != undefined && typeof returnValue.post === "object") { returnValue = this.unescapeFilePostParams(returnValue) } return returnValue }; SWFUpload.prototype.selectFile = function () { this.callFlash("SelectFile") }; SWFUpload.prototype.selectFiles = function () { this.callFlash("SelectFiles") }; SWFUpload.prototype.startUpload = function (a) { this.callFlash("StartUpload", [a]) }; SWFUpload.prototype.cancelUpload = function (a, b) { if (b !== false) { b = true } this.callFlash("CancelUpload", [a, b]) }; SWFUpload.prototype.stopUpload = function () { this.callFlash("StopUpload") }; SWFUpload.prototype.getStats = function () { return this.callFlash("GetStats") }; SWFUpload.prototype.setStats = function (a) { this.callFlash("SetStats", [a]) }; SWFUpload.prototype.getFile = function (a) { if (typeof (a) === "number") { return this.callFlash("GetFileByIndex", [a]) } else { return this.callFlash("GetFile", [a]) } }; SWFUpload.prototype.addFileParam = function (a, b, c) { return this.callFlash("AddFileParam", [a, b, c]) }; SWFUpload.prototype.removeFileParam = function (a, b) { this.callFlash("RemoveFileParam", [a, b]) }; SWFUpload.prototype.setUploadURL = function (a) { this.settings.upload_url = a.toString(); this.callFlash("SetUploadURL", [a]) }; SWFUpload.prototype.setPostParams = function (a) { this.settings.post_params = a; this.callFlash("SetPostParams", [a]) }; SWFUpload.prototype.addPostParam = function (a, b) { this.settings.post_params[a] = b; this.callFlash("SetPostParams", [this.settings.post_params]) }; SWFUpload.prototype.removePostParam = function (a) { delete this.settings.post_params[a]; this.callFlash("SetPostParams", [this.settings.post_params]) }; SWFUpload.prototype.setFileTypes = function (a, b) { this.settings.file_types = a; this.settings.file_types_description = b; this.callFlash("SetFileTypes", [a, b]) }; SWFUpload.prototype.setFileSizeLimit = function (a) { this.settings.file_size_limit = a; this.callFlash("SetFileSizeLimit", [a]) }; SWFUpload.prototype.setFileUploadLimit = function (a) { this.settings.file_upload_limit = a; this.callFlash("SetFileUploadLimit", [a]) }; SWFUpload.prototype.setFileQueueLimit = function (a) { this.settings.file_queue_limit = a; this.callFlash("SetFileQueueLimit", [a]) }; SWFUpload.prototype.setFilePostName = function (a) { this.settings.file_post_name = a; this.callFlash("SetFilePostName", [a]) }; SWFUpload.prototype.setUseQueryString = function (a) { this.settings.use_query_string = a; this.callFlash("SetUseQueryString", [a]) }; SWFUpload.prototype.setRequeueOnError = function (a) { this.settings.requeue_on_error = a; this.callFlash("SetRequeueOnError", [a]) }; SWFUpload.prototype.setHTTPSuccess = function (a) { if (typeof a === "string") { a = a.replace(" ", "").split(",") } this.settings.http_success = a; this.callFlash("SetHTTPSuccess", [a]) }; SWFUpload.prototype.setAssumeSuccessTimeout = function (a) { this.settings.assume_success_timeout = a; this.callFlash("SetAssumeSuccessTimeout", [a]) }; SWFUpload.prototype.setDebugEnabled = function (a) { this.settings.debug_enabled = a; this.callFlash("SetDebugEnabled", [a]) }; SWFUpload.prototype.setButtonImageURL = function (a) { if (a == undefined) { a = "" } this.settings.button_image_url = a; this.callFlash("SetButtonImageURL", [a]) }; SWFUpload.prototype.setButtonDimensions = function (c, a) { this.settings.button_width = c; this.settings.button_height = a; var b = this.getMovieElement(); if (b != undefined) { b.style.width = c + "px"; b.style.height = a + "px" } this.callFlash("SetButtonDimensions", [c, a]) }; SWFUpload.prototype.setButtonText = function (a) { this.settings.button_text = a; this.callFlash("SetButtonText", [a]) }; SWFUpload.prototype.setButtonTextPadding = function (b, a) { this.settings.button_text_top_padding = a; this.settings.button_text_left_padding = b; this.callFlash("SetButtonTextPadding", [b, a]) }; SWFUpload.prototype.setButtonTextStyle = function (a) { this.settings.button_text_style = a; this.callFlash("SetButtonTextStyle", [a]) }; SWFUpload.prototype.setButtonDisabled = function (a) { this.settings.button_disabled = a; this.callFlash("SetButtonDisabled", [a]) }; SWFUpload.prototype.setButtonAction = function (a) { this.settings.button_action = a; this.callFlash("SetButtonAction", [a]) }; SWFUpload.prototype.setButtonCursor = function (a) { this.settings.button_cursor = a; this.callFlash("SetButtonCursor", [a]) }; SWFUpload.prototype.queueEvent = function (b, c) { if (c == undefined) { c = [] } else { if (!(c instanceof Array)) { c = [c] } } var a = this; if (typeof this.settings[b] === "function") { this.eventQueue.push(function () { this.settings[b].apply(this, c) }); setTimeout(function () { a.executeNextEvent() }, 0) } else { if (this.settings[b] !== null) { throw "Event handler " + b + " is unknown or is not a function" } } }; SWFUpload.prototype.executeNextEvent = function () { var a = this.eventQueue ? this.eventQueue.shift() : null; if (typeof (a) === "function") { a.apply(this) } }; SWFUpload.prototype.unescapeFilePostParams = function (c) { var e = /[$]([0-9a-f]{4})/i; var f = {}; var d; if (c != undefined) { for (var a in c.post) { if (c.post.hasOwnProperty(a)) { d = a; var b; while ((b = e.exec(d)) !== null) { d = d.replace(b[0], String.fromCharCode(parseInt("0x" + b[1], 16))) } f[d] = c.post[a] } } c.post = f } return c }; SWFUpload.prototype.testExternalInterface = function () { try { return this.callFlash("TestExternalInterface") } catch (a) { return false } }; SWFUpload.prototype.flashReady = function () { var a = this.getMovieElement(); if (!a) { this.debug("Flash called back ready but the flash movie can't be found."); return } this.cleanUp(a); this.queueEvent("swfupload_loaded_handler") }; SWFUpload.prototype.cleanUp = function (a) { try { if (this.movieElement && typeof (a.CallFunction) === "unknown") { this.debug("Removing Flash functions hooks (this should only run in IE and should prevent memory leaks)"); for (var c in a) { try { if (typeof (a[c]) === "function" && c[0] <= "Z") { a[c] = null } } catch (b) { } } } } catch (d) { } window.__flash__removeCallback = function (e, f) { try { if (e) { e[f] = null } } catch (g) { } } }; SWFUpload.prototype.fileDialogStart = function () { this.queueEvent("file_dialog_start_handler") }; SWFUpload.prototype.fileQueued = function (a) { a = this.unescapeFilePostParams(a); this.queueEvent("file_queued_handler", a) }; SWFUpload.prototype.fileQueueError = function (a, c, b) { a = this.unescapeFilePostParams(a); this.queueEvent("file_queue_error_handler", [a, c, b]) }; SWFUpload.prototype.fileDialogComplete = function (b, c, a) { this.queueEvent("file_dialog_complete_handler", [b, c, a]) }; SWFUpload.prototype.uploadStart = function (a) { a = this.unescapeFilePostParams(a); this.queueEvent("return_upload_start_handler", a) }; SWFUpload.prototype.returnUploadStart = function (a) { var b; if (typeof this.settings.upload_start_handler === "function") { a = this.unescapeFilePostParams(a); b = this.settings.upload_start_handler.call(this, a) } else { if (this.settings.upload_start_handler != undefined) { throw "upload_start_handler must be a function" } } if (b === undefined) { b = true } b = !!b; this.callFlash("ReturnUploadStart", [b]) }; SWFUpload.prototype.uploadProgress = function (a, c, b) { a = this.unescapeFilePostParams(a); this.queueEvent("upload_progress_handler", [a, c, b]) }; SWFUpload.prototype.uploadError = function (a, c, b) { a = this.unescapeFilePostParams(a); this.queueEvent("upload_error_handler", [a, c, b]) }; SWFUpload.prototype.uploadSuccess = function (b, a, c) { b = this.unescapeFilePostParams(b); this.queueEvent("upload_success_handler", [b, a, c]) }; SWFUpload.prototype.uploadComplete = function (a) { a = this.unescapeFilePostParams(a); this.queueEvent("upload_complete_handler", a) }; SWFUpload.prototype.debug = function (a) { this.queueEvent("debug_handler", a) }; SWFUpload.prototype.debugMessage = function (c) { if (this.settings.debug) { var a, d = []; if (typeof c === "object" && typeof c.name === "string" && typeof c.message === "string") { for (var b in c) { if (c.hasOwnProperty(b)) { d.push(b + ": " + c[b]) } } a = d.join("\n") || ""; d = a.split("\n"); a = "EXCEPTION: " + d.join("\nEXCEPTION: "); SWFUpload.Console.writeLine(a) } else { SWFUpload.Console.writeLine(c) } } }; SWFUpload.Console = {}; SWFUpload.Console.writeLine = function (d) { var b, a; try { b = document.getElementById("SWFUpload_Console"); if (!b) { a = document.createElement("form"); document.getElementsByTagName("body")[0].appendChild(a); b = document.createElement("textarea"); b.id = "SWFUpload_Console"; b.style.fontFamily = "monospace"; b.setAttribute("wrap", "off"); b.wrap = "off"; b.style.overflow = "auto"; b.style.width = "700px"; b.style.height = "350px"; b.style.margin = "5px"; a.appendChild(b) } b.value += d + "\n"; b.scrollTop = b.scrollHeight - b.clientHeight } catch (c) { alert("Exception: " + c.name + " Message: " + c.message) } }; var SWFUpload; if (typeof (SWFUpload) === "function") { SWFUpload.queue = {}; SWFUpload.prototype.initSettings = (function (a) { return function () { if (typeof (a) === "function") { a.call(this) } this.queueSettings = {}; this.queueSettings.queue_cancelled_flag = false; this.queueSettings.queue_upload_count = 0; this.queueSettings.user_upload_complete_handler = this.settings.upload_complete_handler; this.queueSettings.user_upload_start_handler = this.settings.upload_start_handler; this.settings.upload_complete_handler = SWFUpload.queue.uploadCompleteHandler; this.settings.upload_start_handler = SWFUpload.queue.uploadStartHandler; this.settings.queue_complete_handler = this.settings.queue_complete_handler || null } })(SWFUpload.prototype.initSettings); SWFUpload.prototype.startUpload = function (a) { this.queueSettings.queue_cancelled_flag = false; this.callFlash("StartUpload", [a]) }; SWFUpload.prototype.cancelQueue = function () { this.queueSettings.queue_cancelled_flag = true; this.stopUpload(); var a = this.getStats(); while (a.files_queued > 0) { this.cancelUpload(); a = this.getStats() } }; SWFUpload.queue.uploadStartHandler = function (a) { var b; if (typeof (this.queueSettings.user_upload_start_handler) === "function") { b = this.queueSettings.user_upload_start_handler.call(this, a) } b = (b === false) ? false : true; this.queueSettings.queue_cancelled_flag = !b; return b }; SWFUpload.queue.uploadCompleteHandler = function (b) { var c = this.queueSettings.user_upload_complete_handler; var d; if (b.filestatus === SWFUpload.FILE_STATUS.COMPLETE) { this.queueSettings.queue_upload_count++ } if (typeof (c) === "function") { d = (c.call(this, b) === false) ? false : true } else { if (b.filestatus === SWFUpload.FILE_STATUS.QUEUED) { d = false } else { d = true } } if (d) { var a = this.getStats(); if (a.files_queued > 0 && this.queueSettings.queue_cancelled_flag === false) { this.startUpload() } else { if (this.queueSettings.queue_cancelled_flag === false) { this.queueEvent("queue_complete_handler", [this.queueSettings.queue_upload_count]); this.queueSettings.queue_upload_count = 0 } else { this.queueSettings.queue_cancelled_flag = false; this.queueSettings.queue_upload_count = 0 } } } } } function FileProgress(c, a) { this.fileProgressID = c.id; this.opacity = 100; this.height = 0; this.fileProgressWrapper = document.getElementById(this.fileProgressID); if (!this.fileProgressWrapper) { this.fileProgressWrapper = document.createElement("div"); this.fileProgressWrapper.className = "progressWrapper"; this.fileProgressWrapper.id = this.fileProgressID; this.fileProgressElement = document.createElement("div"); this.fileProgressElement.className = "progressContainer"; var f = document.createElement("a"); f.className = "progressCancel"; f.href = "#"; f.style.visibility = "hidden"; f.appendChild(document.createTextNode(" ")); var b = document.createElement("div"); b.className = "progressName"; b.appendChild(document.createTextNode(c.name)); var e = document.createElement("div"); e.className = "progressBarInProgress"; var d = document.createElement("div"); d.className = "progressBarStatus"; d.innerHTML = "&nbsp;"; this.fileProgressElement.appendChild(f); this.fileProgressElement.appendChild(b); this.fileProgressElement.appendChild(d); this.fileProgressElement.appendChild(e); this.fileProgressWrapper.appendChild(this.fileProgressElement); document.getElementById(a).appendChild(this.fileProgressWrapper) } else { this.fileProgressElement = this.fileProgressWrapper.firstChild; this.reset() } this.height = this.fileProgressWrapper.offsetHeight; this.setTimer(null) } FileProgress.prototype.setTimer = function (a) { this.fileProgressElement.FP_TIMER = a }; FileProgress.prototype.getTimer = function (a) { return this.fileProgressElement.FP_TIMER || null }; FileProgress.prototype.reset = function () { this.fileProgressElement.className = "progressContainer"; this.fileProgressElement.childNodes[2].innerHTML = "&nbsp;"; this.fileProgressElement.childNodes[2].className = "progressBarStatus"; this.fileProgressElement.childNodes[3].className = "progressBarInProgress"; this.fileProgressElement.childNodes[3].style.width = "0%"; this.appear() }; FileProgress.prototype.setProgress = function (a) { this.fileProgressElement.className = "progressContainer green"; this.fileProgressElement.childNodes[3].className = "progressBarInProgress"; this.fileProgressElement.childNodes[3].style.width = a + "%"; this.appear() }; FileProgress.prototype.setComplete = function () { this.fileProgressElement.className = "progressContainer blue"; this.fileProgressElement.childNodes[3].className = "progressBarComplete"; this.fileProgressElement.childNodes[3].style.width = ""; var a = this; this.setTimer(setTimeout(function () { a.disappear() }, 10000)) }; FileProgress.prototype.setError = function () { this.fileProgressElement.className = "progressContainer red"; this.fileProgressElement.childNodes[3].className = "progressBarError"; this.fileProgressElement.childNodes[3].style.width = ""; var a = this; this.setTimer(setTimeout(function () { a.disappear() }, 5000)) }; FileProgress.prototype.setCancelled = function () { this.fileProgressElement.className = "progressContainer"; this.fileProgressElement.childNodes[3].className = "progressBarError"; this.fileProgressElement.childNodes[3].style.width = ""; var a = this; this.setTimer(setTimeout(function () { a.disappear() }, 2000)) }; FileProgress.prototype.setStatus = function (a) { this.fileProgressElement.childNodes[2].innerHTML = a }; FileProgress.prototype.toggleCancel = function (b, c) { this.fileProgressElement.childNodes[0].style.visibility = b ? "visible" : "hidden"; if (c) { var a = this.fileProgressID; this.fileProgressElement.childNodes[0].onclick = function () { c.cancelUpload(a); return false } } }; FileProgress.prototype.appear = function () { if (this.getTimer() !== null) { clearTimeout(this.getTimer()); this.setTimer(null) } if (this.fileProgressWrapper.filters) { try { this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = 100 } catch (a) { this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=100)" } } else { this.fileProgressWrapper.style.opacity = 1 } this.fileProgressWrapper.style.height = ""; this.height = this.fileProgressWrapper.offsetHeight; this.opacity = 100; this.fileProgressWrapper.style.display = "" }; FileProgress.prototype.disappear = function () { if (jQuery) { $(this.fileProgressWrapper).fadeOut() } else { var f = 15; var c = 4; var b = 80; if (this.opacity > 0) { this.opacity -= f; if (this.opacity < 0) { this.opacity = 0 } if (this.fileProgressWrapper.filters) { try { this.fileProgressWrapper.filters.item("DXImageTransform.Microsoft.Alpha").opacity = this.opacity } catch (d) { this.fileProgressWrapper.style.filter = "progid:DXImageTransform.Microsoft.Alpha(opacity=" + this.opacity + ")" } } else { this.fileProgressWrapper.style.opacity = this.opacity / 100 } } if (this.height > 0) { this.height -= c; if (this.height < 0) { this.height = 0 } this.fileProgressWrapper.style.height = this.height + "px" } if (this.height > 0 || this.opacity > 0) { var a = this; this.setTimer(setTimeout(function () { a.disappear() }, b)) } else { this.fileProgressWrapper.style.display = "none"; this.setTimer(null) } } }; function cancelQueue(a) { document.getElementById(a.customSettings.cancelButtonId).disabled = true; a.stopUpload(); var b; do { b = a.getStats(); a.cancelUpload() } while (b.files_queued !== 0) } function fileDialogStart() { } function fileQueued(c) { if (this.customSettings.preview) { var d = $("#upload-row").html(); this.customSettings.target.siblings(".files").append($(d).find("a").attr({ title: c.name }).text(c.name).end().find("span").formatFileSize(c).end()); this.customSettings.target.get(0).removeAttribute("required"); return } try { $("input[type=submit]").addClass("btn-disabled"); var a = new FileProgress(c, this.customSettings.progressTarget); a.setStatus("Pending..."); a.toggleCancel(true, this) } catch (b) { this.debug(b) } } function fileQueueComplete() { LF.uploads["upload" + this.customSettings.target.attr("id").substr(5)].setButtonDisabled(false); $("input[type=submit]").removeClass("btn-disabled") } function fileQueueError(c, e, d) { try { if (e === SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED) { alert("You have attempted to queue too many files.\n" + (d === 0 ? "You have reached the upload limit." : "You may select " + (d > 1 ? "up to " + d + " files." : "one file."))); return } var a = new FileProgress(c, this.customSettings.progressTarget); a.setError(); a.toggleCancel(false); switch (e) { case SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT: a.setStatus(localize("STR_IS_LARGER_THAN").replace("{0}", "").replace("{1}", parseInt(this.settings.file_size_limit) / 1024)); this.debug("Error Code: File too big, File name: " + c.name + ", File size: " + c.size + ", Message: " + d); break; case SWFUpload.QUEUE_ERROR.ZERO_BYTE_FILE: a.setStatus(localize("STR_FILE_SIZE_INVALID")); this.debug("Error Code: Zero byte file, File name: " + c.name + ", File size: " + c.size + ", Message: " + d); break; case SWFUpload.QUEUE_ERROR.INVALID_FILETYPE: a.setStatus(localize("STR_FILE_TYPE_NOT_SUPPORTED").replace("{0}", "")); this.debug("Error Code: Invalid File Type, File name: " + c.name + ", File size: " + c.size + ", Message: " + d); break; case SWFUpload.QUEUE_ERROR.QUEUE_LIMIT_EXCEEDED: alert("You have selected too many files.  " + (d > 1 ? "You may only add " + d + " more files" : "You cannot add any more files.")); break; default: if (c !== null) { a.setStatus("Unhandled Error") } this.debug("Error Code: " + e + ", File name: " + c.name + ", File size: " + c.size + ", Message: " + d); break } } catch (b) { this.debug(b) } } function fileDialogComplete(a, b) { if (this.getStats().files_queued > 0 && this.customSettings.cancelButtonId) { document.getElementById(this.customSettings.cancelButtonId).disabled = false } if (this.customSettings.preview) { return } this.startUpload() } function uploadProgress(c, f, e) { try { var d = Math.ceil((f / e) * 100); var a = new FileProgress(c, this.customSettings.progressTarget); a.setProgress(d); a.setStatus(localize("STR_UPLOADING")) } catch (b) { this.debug(b) } } function uploadSuccess(d, b) { try { var a = new FileProgress(d, this.customSettings.progressTarget); a.setComplete(); a.setStatus(localize("STR_COMPLETE")); a.toggleCancel(false); this.customSettings.target.siblings(".files").append(b); this.customSettings.target.get(0).removeAttribute("required") } catch (c) { this.debug(c) } } function uploadError(c, e, d) { try { var a = new FileProgress(c, this.customSettings.progressTarget); a.setError(); a.toggleCancel(false); switch (e) { case SWFUpload.UPLOAD_ERROR.HTTP_ERROR: a.setStatus("Upload Error: " + d); this.debug("Error Code: HTTP Error, File name: " + c.name + ", Message: " + d); break; case SWFUpload.UPLOAD_ERROR.MISSING_UPLOAD_URL: a.setStatus("Configuration Error"); this.debug("Error Code: No backend file, File name: " + c.name + ", Message: " + d); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_FAILED: a.setStatus("Upload Failed."); this.debug("Error Code: Upload Failed, File name: " + c.name + ", File size: " + c.size + ", Message: " + d); break; case SWFUpload.UPLOAD_ERROR.IO_ERROR: a.setStatus("Server (IO) Error"); this.debug("Error Code: IO Error, File name: " + c.name + ", Message: " + d); break; case SWFUpload.UPLOAD_ERROR.SECURITY_ERROR: a.setStatus("Security Error"); this.debug("Error Code: Security Error, File name: " + c.name + ", Message: " + d); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_LIMIT_EXCEEDED: a.setStatus("Upload limit exceeded."); this.debug("Error Code: Upload Limit Exceeded, File name: " + c.name + ", File size: " + c.size + ", Message: " + d); break; case SWFUpload.UPLOAD_ERROR.SPECIFIED_FILE_ID_NOT_FOUND: a.setStatus("File not found."); this.debug("Error Code: The file was not found, File name: " + c.name + ", File size: " + c.size + ", Message: " + d); break; case SWFUpload.UPLOAD_ERROR.FILE_VALIDATION_FAILED: a.setStatus("Failed Validation.  Upload skipped."); this.debug("Error Code: File Validation Failed, File name: " + c.name + ", File size: " + c.size + ", Message: " + d); break; case SWFUpload.UPLOAD_ERROR.FILE_CANCELLED: if (this.getStats().files_queued === 0 && this.customSettings.cancelButtonId) { document.getElementById(this.customSettings.cancelButtonId).disabled = true } a.setStatus(localize("STR_CANCELED")); a.setCancelled(); break; case SWFUpload.UPLOAD_ERROR.UPLOAD_STOPPED: a.setStatus(localize("STR_STOPPED")); break; default: a.setStatus(localize("ERR_COL").replace("{0}", e)); this.debug("Error Code: " + e + ", File name: " + c.name + ", File size: " + c.size + ", Message: " + d); break } } catch (b) { this.debug(b) } };;
/*!
// Copyright (c) 2008 Andris Valums, http://valums.com
// Licensed under the MIT license (http://valums.com/mit-license/)
// Thanks to Loic Fontaine, Mark Feldman, Andras Popovics, Faisal for contribution

Changelog:
Version 0.6 - Fixed bugs:
	1. Disabling button while uploading resulted in empty upload
	2. Submitting empty file input in Chrome, when user clicked cancel
 */
(function(c){if(!c){return}c.ajax_upload=function(e,d){e=c(e);if(e.size()!=1){console.error("You passed ",e.size()," elements to ajax_upload at once");return false}return new a(e,d)};var b=function(){var d=0;return function(){return d++}}();var a=function(e,d){this.button=e;this.wrapper=null;this.form=null;this.input=null;this.iframe=null;this.disabled=false;this.submitting=false;this.settings={action:"upload.php",name:"userfile",data:{},onSubmit:function(f,g){},onComplete:function(g,f){},onSuccess:function(f){},onAlways:function(){},onError:function(g,f){}};c.extend(this.settings,d);this.create_wrapper();this.create_input();this.create_iframe()};a.prototype={set_data:function(d){this.settings.data=d},disable:function(){this.disabled=true;if(!this.submitting){this.input.attr("disabled",true)}},enable:function(){this.disabled=false;this.input.attr("disabled",false)},create_wrapper:function(){var e=this.button,g;var f=e.attr("style");g=this.wrapper=c('<div style="'+f+'"></div>').insertAfter(e).append(e);setTimeout(function(){g.css({position:"relative",display:"inline",overflow:"hidden"})},1);var d=this;g.mousemove(function(h){if(!d.input){return}d.input.css({top:h.pageY-g.offset().top-5+"px",left:h.pageX-g.offset().left-170+"px"})})},create_input:function(){var d=this;this.input=c("<input title="+localize("STR_BTN_UPLOAD")+' type="file"/>').attr("name",this.settings.name).attr("required",d.button.attr("required")).css({position:"absolute",cursor:"pointer",margin:0,padding:0,width:"220px",height:"10px",opacity:0}).change(function(f){if(c(this).val()==""){return}d.submitting=true;d.submit();d.submitting=false}).appendTo(this.wrapper).hover(function(){d.button.addClass("hover")},function(){d.button.removeClass("hover")});if(this.disabled){this.input.attr("disabled",true)}},create_iframe:function(){var d="iframe_au"+b();this.iframe=c('<iframe src="javascript:false;" name="'+d+'"></iframe>').css("display","none").appendTo("body")},submit:function(){var d=this,g=this.settings;var e=this.file_from_path(this.input.val());if(g.onSubmit.call(this,e,this.get_ext(e))===false){if(d.disabled){this.input.attr("disabled",true)}return}this.create_form();this.input.appendTo(this.form);this.form.submit();this.input.remove();this.input=null;this.form.remove();this.form=null;this.submitting=false;this.create_input();var f=this.iframe;f.on("load",function(){var h=f.contents().find("body").html();g.onComplete.call(d,e,h);if(h=="success"){g.onSuccess.call(d,e)}else{g.onError.call(d,e,h)}g.onAlways.call(d);setTimeout(function(){f.remove()},1)});this.postingIframe=this.iframe;this.create_iframe()},create_form:function(){this.form=c('<form method="post" enctype="multipart/form-data"></form>').appendTo("body").attr({action:this.settings.action,target:this.iframe.attr("name")});for(var d in this.settings.data){c('<input type="hidden" />').appendTo(this.form).attr({name:d,value:this.settings.data[d]})}},file_from_path:function(e){var d=e.lastIndexOf("\\");if(d!==-1){return e.slice(d+1)}return e},get_ext:function(e){var d=e.lastIndexOf(".");if(d!==-1){return e.slice(d+1)}return""},make_parent_opaque:function(){this.button.add(this.button.parents()).each(function(){var d=c(this).css("backgroundColor");var e=c(this).css("backgroundImage");if(d!="transparent"||e!="none"){c(this).css("opacity",1);return false}})}}})(jQuery);;
// Copyright 2012-2016 Laserfiche. All rights reserved

﻿
var ie10=!!navigator.userAgent.match(/MSIE 10/);var html5Upload=window.File&&window.FileList&&window.FileReader&&window.FormData&&!ie10;LF.uploads={};var minFileDropWidth=5;var mbToBytes=1048576;var ie7=!!navigator.userAgent.match(/MSIE 7/);var flashUpload=LF.getFlashVersion().split(',').shift()>8&&!ie7&&!ie10;$(document).off('drop dragover dragenter dragleave');$.fn.newfileupload=html5Upload?function(config){if(!config.target.attr('readonly')){$('<div class="file-drop-area"><span>'+localize('STR_DROP_FILE')+'</span></div>').insertBefore(config.target);if(config.target.type!="file"){var pos=config.target.position();var isRTL=$('html').is('[dir="rtl"]');var allowedExts=(config.fieldData.fileExtension.length)?'.'+config.fieldData.fileExtension.replace(/ /g,'').replace(/,/g,',.'):'*';var item=$('<input type="file" accept='+allowedExts+'>').insertBefore(config.target).css("position","absolute").css(isRTL?"right":"left",isRTL?pos.right:pos.left).css("top",pos.top).css("opacity","0").css("height","26px").attr("title",config.target.val()||localize('STR_UPLOAD')).css('width',minFileDropWidth);$.each(config.target.prop("attributes"),function(){if(this.name!='type'&&this.name!='value')
item.attr(this.name,this.value);});config.target.attr("id",config.target.attr("id")+"_old");config.target.click(function(){item.trigger("click");});config.target=item;}}
config.target.siblings('img').remove();var jqxhrs=[];var targetField=config.target.parent();var maxFileSz=config.fieldData.fileMaxSize?config.fieldData.fileMaxSize:250;var zoneEnter=0;config.target.prev().fileupload({index:0,maxFileSize:maxFileSz,maxNumberOfFiles:config.fieldData.maxfiles?config.fieldData.maxfiles:5,url:'',fileInput:targetField,dropZone:targetField,replaceFileInput:false,sequentialUploads:true,done:function(e,data){console.log("done");config.target.siblings('[pi='+(data.index-1)+']').remove();config.target.siblings('.files').append(data.response().result);config.target.attr('required',null).addClass('hasFiles');$(config.target).trigger('updatevalidation');jqxhrs.shift();},add:function(e,data){var file=data.files[0];if(!isFileValid(file,config,maxFileSz)){changeSubmitBtnState(false);return;}
if(!_.isNull(config.uploadData.availableFileNum)){config.uploadData.availableFileNum=config.uploadData.availableFileNum-1;if(config.uploadData.availableFileNum<0){var uploadButtons=$(e.target.parentElement).find('.fileuploader');$("#"+jQuerySelectorEscape("exceedUploadLimit"+uploadButtons[0].id)).show();}}
if(config.preview){previewAction(file,config);return;}
changeSubmitBtnState(true);jqxhrs.push(data.submit());},drop:function(e,data){console.log("inner drop");config.target.siblings('.files').find('.error').remove();$('.fileuploader').show().siblings('.file-drop-area').hide();if(e.originalEvent.delegatedEvent.dataTransfer.files.length==0){$('<tr class="error"><td>'+localize('STR_FILE_TYPE_NOT_SUPPORTED').replace('{0}','folder')+'</td></tr>').appendTo(config.target.siblings('.files'));return false;}
var files=data.files;if(!files.length)
return;config.target.siblings('.files').find('.error').remove();zoneEnter=0;e.stopPropagation();},submit:function(e,data){console.log("submit");var deleted=$("input[name=attachmentToRemove]").length?$("input[name=attachmentToRemove]").val():'';data.url=LF.Url.contentRoot+'Handlers/FileUploadHandler.ashx?field='+config.target.attr('id').substr(5)
+(deleted===''?'':'&deleted='+deleted)+'&org='+config.target.attr('org')+'&uqid='
+$("input[name=uqid]").val();},change:function(e,data){console.log("change");config.target.siblings('.files').find('.error').remove();config.target.val(null);},stop:function(e){console.log("stopped");changeSubmitBtnState(false);config.target.prev().fileupload('option',{index:0});config.uploadData.availableFileNum=_.isNull(config.fieldData.length)?config.fieldData.length:(config.fieldData.length-$(this).parent().find('table tr a').length);var uploadButtons=$(e.target.parentElement).find('.fileuploader');config.uploadData.availableFileNum<0?$("#"+jQuerySelectorEscape("exceedUploadLimit"+uploadButtons[0].id)).show():$("#"+jQuerySelectorEscape("exceedUploadLimit"+uploadButtons[0].id)).hide();if($(config.target).is('.required')){var v=$(config.target).attr('required');$(config.target).attr('required',!v).attr('required',!!v);$(config.target).trigger('updatevalidation');}},progress:function(e,data){var progress=data.progress().loaded/data.progress().total*100;var prog=config.target.siblings('div[pi='+(data.index-1)+']');prog.progressbar('value',progress);config.target.siblings('span[pi='+(data.index-1)+']').formatFileSize(data.files[0],progress);if(progress>95){$('[pi='+(data.index-1)+'].stop-upload').remove();setTimeout(function(){try{prog.progressbar("destroy");}
catch(e){}
var sizeTxt=prog.removeClass('upload-progress').addClass('uploaded-processing').next().next();sizeTxt.text(sizeTxt.text().split('/')[0]);},1100);}},send:function(e,data){var progress=$('<div class="upload-progress" pi="'+data.index+'" />').progressbar();$('<span>'+data.files[0].name+'</span>').appendTo(progress);progress.appendTo(config.target.parent());$('<span class="upload-status" pi="'+data.index+'"></span>').formatFileSize(data.files[0],0).insertAfter(progress);$('<label class="stop-upload" pi="'+data.index+'">'+localize('STR_BTN_CANCEL')+'</label>').insertAfter(progress);$('[pi='+data.index+'].stop-upload').one('click',function(){if(jqxhrs.length){$('[pi='+(data.index-1)+']').remove();jqxhrs.shift().abort();}
else{console.log("error! jqxhr proc does not exist for this upload");}});config.target.prev().fileupload('option',{index:data.index+1})
data.index++;},fail:function(e,data){if(data.errorThrown=='abort'){console.log("aborted: "+data.files[0].name);}}});function checkIfFileNotEmpty(e){return e.originalEvent.dataTransfer.files&&(e.originalEvent.dataTransfer.files.length>0)&&e.originalEvent.dataTransfer.files[0].size>0;}
function checkIfFileTypeIsWebKitSupported(e){return e.originalEvent.dataTransfer.items&&e.originalEvent.dataTransfer.items.length;}
function checkIfFileTypeIsDirFromWebKit(e){return e.originalEvent.dataTransfer.items[0].webkitGetAsEntry().isDirectory;}
function isFileAFolder(e){if(checkIfFileTypeIsWebKitSupported(e)){if(checkIfFileTypeIsDirFromWebKit(e)){return true;}}
else if(!checkIfFileNotEmpty(e)){return true;}
return false;}
$(document).on('drop',function(e){console.log("outerdrop");e.preventDefault();if(isFileAFolder(e)){$(e.target).parent().siblings('.files').find('.error').remove();$('<tr class="error"><td>'+localize('STR_FILE_TYPE_NOT_SUPPORTED').replace('{0}','folder')+'</td></tr>').appendTo($(e.target).parent().siblings('.files'));}
$('.fileuploader').show().siblings('.file-drop-area').hide();zoneEnter=0;e.stopImmediatePropagation();return false;});$(document).off('dragleave').on('dragleave',function(e){if(--zoneEnter==0){$('.fileuploader').show().siblings('.file-drop-area').hide();}
return false;});$(document).off('dragenter').on('dragenter',function(e){if(zoneEnter<2){zoneEnter++;}
$('.fileuploader:not([disabled]').hide().siblings('.file-drop-area').show();return false;});$(document).off('dragover').on('dragover',function(e){return false;});}:(flashUpload?function(config){config.target.siblings('.flash-container, .flash').show();var extArray=config.fieldData.fileExtension.toLowerCase().replace(/ /g,'').split(",");var t='*.*';if(extArray.length>0&&extArray[0]!=='')
t='*.'+extArray.join(';*.');if(config.target[0].type!="file"){var pos=config.target.position();config.target.siblings('.flash-container').css("top",pos.top);var $hiddenElement=config.target.clone().css({position:'absolute',top:-1000,left:-1000}).appendTo('html');var btnWidth=$hiddenElement.outerWidth();$hiddenElement.remove();var item=$('<input type="file">').insertBefore(config.target).css("position","absolute").css("left",pos.left).css("top",pos.top).css("opacity","0").css("height","26px").css('width',Math.max(minFileDropWidth,btnWidth)).attr("title",config.target.val()||localize('STR_UPLOAD'));$.each(config.target.prop("attributes"),function(){if(this.name!='type'&&this.name!='value')
item.attr(this.name,this.value);});config.target.attr("id",config.target.attr("id")+"_old");config.target=item;}
function uploadStart(file){try{changeSubmitBtnState(true);var deleted=$("input[name=attachmentToRemove]").length?$("input[name=attachmentToRemove]").val():'';LF.uploads['upload'+this.customSettings.target.attr('id').substr(5)].setUploadURL(LF.Url.contentRoot+'Handlers/FileUploadHandler.ashx?field='+this.customSettings.target.attr('id').substr(5)
+(deleted===''?'':'&deleted='+deleted)+'&org='+this.customSettings.target.attr('org')+'&uqid='+$("input[name=uqid]").val()).setButtonDisabled(true);var progress=new FileProgress(file,this.customSettings.progressTarget);progress.setStatus(localize('STR_UPLOADING'));progress.toggleCancel(true,this);}
catch(ex){}
return true;}
function uploadComplete(file){try{if(this.getStats().files_queued===0&&this.customSettings.cancelButtonId){document.getElementById(this.customSettings.cancelButtonId).disabled=true;}else{this.startUpload();}}catch(ex){this.debug(ex);}
changeSubmitBtnState(false);if(file.filestatus==SWFUpload.FILE_STATUS.COMPLETE)
this.customSettings.target.attr('required',null).addClass('hasFiles');$(config.target).trigger('updatevalidation');}
var upload=new SWFUpload({file_size_limit:String(config.fieldData.fileMaxSize*1024),file_types:t,file_upload_limit:"100",file_queue_limit:"0",file_dialog_start_handler:fileDialogStart,file_queued_handler:fileQueued,file_queue_error_handler:fileQueueError,queue_complete_handler:fileQueueComplete,file_dialog_complete_handler:fileDialogComplete,upload_start_handler:uploadStart,upload_progress_handler:uploadProgress,upload_error_handler:uploadError,upload_success_handler:uploadSuccess,upload_complete_handler:uploadComplete,button_placeholder_id:"uploadButton"+config.target.attr('id').substr(5),button_width:Math.max(minFileDropWidth,config.target.outerWidth()+40),button_height:config.target.outerHeight()+2,button_window_mode:SWFUpload.WINDOW_MODE.TRANSPARENT,button_cursor:SWFUpload.CURSOR.HAND,flash_url:LF.Url.contentRoot+"lib/swfupload/swfupload.swf",custom_settings:{progressTarget:"uploadProgress"+config.target.attr('id').substr(5),target:config.target,preview:config.preview},debug:false});LF.uploads["upload"+config.target.attr('id').substr(5)]=upload;}:function(config){$.ajax_upload(config.target,{name:'file',data:{fileMaxSize:config.fieldData.fileMaxSize},onSubmit:function(file,ext){function resetForm(uploadObj){uploadObj.input.remove();uploadObj.input=null;uploadObj.create_input();}
var that=this;var extArray=config.fieldData.fileExtension.toLowerCase().replace(/ /g,'').split(",");if(config.fieldData.fileExtension!==''&&$.inArray(ext.toLowerCase(),extArray)===-1){$('<tr class="error"><td>'+localize('STR_FILE_TYPE_NOT_SUPPORTED').replace('{0}',ext)+'</td></tr>').appendTo(config.target.parent().siblings('.files').find('.error').remove().end());resetForm(this);return false;}
if(config.preview){var template=$('#upload-row').html();config.target.parent().siblings('.files').find('.error').remove().end().append($(template).find('a').attr({title:file}).text(file).end());resetForm(this);return false;}
this.disable();changeSubmitBtnState(true);var deleted=$("input[name=attachmentToRemove]").length?$("input[name=attachmentToRemove]").val():'';this.settings.action=LF.Url.contentRoot+'Handlers/FileUploadHandler.ashx?field='+config.target.attr('id').substr(5)
+(deleted===''?'':'&deleted='+deleted)+'&org='+config.target.attr('org')+'&uqid='+$("input[name=uqid]").val();var cancel=$('<label class="stop-upload">'+localize('STR_BTN_CANCEL')+'</label>').one('click',function(){that.postingIframe.off('load').prop('src','javascript'.concat(':false;')).remove();that.settings.onAlways.call(that);});config.target.parent().siblings('img').show().after(cancel);},onComplete:function(file,response){var retContent;if($(response).is('a'))
retContent=$('<tr><td>'+response);else
retContent=$($("<div/>").html($(response).html()).text());config.target.parent().siblings('.files').find('.error').remove().end().append(retContent);if($(response).find('.error').length==0&&$(response).html().search('href')!=-1){var fileUploader=config.target.parent().find('.fileuploader');if(fileUploader.hasClass('required'))
fileUploader.parent().find('input').attr('required',false).addClass('hasFiles');}},onAlways:function(){this.enable();changeSubmitBtnState(false);config.target.parent().siblings('img').hide().next().remove();config.target.next('input').attr('multiple','');}});var shadowInput=config.target.closest('div').css('width','238px;').end().next('input');shadowInput.attr('multiple','').addClass('shadow-fileuploader');var fileUploader=config.target.parent().find('.fileuploader');if(fileUploader.hasClass('required'))
shadowInput.attr('required',true);});$.fn.formatFileSize=function(file,pct){var size=file.size;pct=pct/100;if(size<1024)
this.text("1KB");else if(size<1048576)
this.text((pct?Math.round(size*pct*100/1024)/100+"KB/":"")+Math.round(size*100/1024)/100+"KB");else if(size<1048576000)
this.text((pct?Math.round(size*pct*100/1048576)/100+"MB/":"")+Math.round(size*100/1048576)/100+"MB");else
this.text((pct?Math.round(size*pct*100/1048576000)/100+"GB/":"")+Math.round(size*100/1048576000)/100+"GB");return this;};previewAction=function(file,config){var template=$('#upload-row').html();config.target.siblings('.files').append($(template).find('a').attr({title:file.name}).first().text(file.name).end().end().find('div').first().formatFileSize(file).end().end());config.target.attr('required',null);}
isFileValid=function(file,config,maxFileSz){var extArray=config.fieldData.fileExtension.toLowerCase().replace(/ /g,'').split(",");var ext=(file.name.lastIndexOf('.')!=-1)?file.name.substr(file.name.lastIndexOf('.')+1).toLowerCase():'folder';if((file.name.lastIndexOf('.')==-1)||(config.fieldData.fileExtension!==''&&$.inArray(ext,extArray)===-1)){$('<tr class="error"><td>'+localize('STR_FILE_TYPE_NOT_SUPPORTED').replace('{0}',ext)+'</td></tr>').appendTo(config.target.siblings('.files'));return false;}
if(file.size===0){$('<tr class="error"><td>'+localize('STR_FILE_SIZE_INVALID')+'</td></tr>').appendTo(config.target.siblings('.files'));return false;}
if(file.size>maxFileSz*mbToBytes){var err_msg=localize('STR_IS_LARGER_THAN').replace('{0}',file.name+' ').replace('{1}',maxFileSz);$(String.format('<tr class="error" title="{0}"><td>{0}</td></tr>',err_msg)).appendTo(config.target.siblings('.files'));return false;}
return true;}
changeSubmitBtnState=function(disable){if(disable&&!$(this).is(":disabled")){$('.action-btn').addClass('btn-disabled').attr('disabled','disabled');}
else{$('.action-btn.btn-disabled').removeClass('btn-disabled').attr('disabled',null);}};
// Copyright 2012-2016 Laserfiche. All rights reserved

﻿
LF.LFForms={readyTime:null,validatedVal:"",saveFlag:false,validateReCaptcha:"",recaptchaState:"ready",};(function($){var geolocation={geo:{latitude:0,longitude:0},init:function(targets,isSubmittingForm,btn){isSubmittingForm=typeof(isSubmittingForm!=="undefined")?isSubmittingForm:false;function successGeo(position){var laPrecision=position.coords.latitude.toString().replace("-","").replace(".","").length;var loPrecision=position.coords.longitude.toString().replace("-","").replace(".","").length;geolocation.geo.latitude=(laPrecision>15)?position.coords.latitude.toPrecision(15):position.coords.latitude;geolocation.geo.longitude=(loPrecision>15)?position.coords.longitude.toPrecision(15):position.coords.longitude;_.forEach(targets,function(target){$(target).closest(".form-q").removeClass("hidden");var currentGeo=$(target).find('.geo-current-value');var displayGeo=$(target).find('.geo-display-value');currentGeo.attr('latitude',geolocation.geo.latitude).attr('longitude',geolocation.geo.longitude).text(geolocation.geo.latitude+", "+geolocation.geo.longitude);displayGeo.text(geolocation.geo.latitude+", "+geolocation.geo.longitude);$(target).find("input[geo-title='latitude']:not('.geo-lookup')").val(geolocation.geo.latitude).trigger('updatevalidation').trigger('lookup');$(target).find("input[geo-title='longitude']:not('.geo-lookup')").val(geolocation.geo.longitude).trigger('updatevalidation').trigger('lookup');if($('.geo-current:hidden',target).length>0&&$('.geo-submission',target).length==0&&$('.geo-lookup',target).length==0){$('.geo-current',target).css('display','inline-block');$('.geo-current-rtn',target).show();$('.geo-default, .geo-specify, .geo-specify-rtn',target).hide();}});if(isSubmittingForm&&typeof btn!="undefined"){if($(btn).attr('type')=="submit"){$(btn).trigger('click');}
else{$('#form1').submit();}}}
function failGeo(error){var currentGeo=targets.find('.geo-current-value');switch(error.code){case error.PERMISSION_DENIED:currentGeo.text(localize('STR_GEOLOCATION_DECLINED'));break;}
_.forEach(targets,function(target){$(target).find("input[geo-title='latitude']:not('.geo-lookup')").val('').trigger('updatevalidation').trigger('lookup');$(target).find("input[geo-title='longitude']:not('.geo-lookup')").val('').trigger('updatevalidation').trigger('lookup');if($('.geo-current:hidden',target).length>0&&$('.geo-submission',target).length==0&&$('.geo-lookup',target).length==0){$('.geo-current',target).css('display','inline-block');$('.geo-current-rtn',target).show();$('.geo-default, .geo-specify, .geo-specify-rtn',target).hide();}});if(isSubmittingForm&&typeof btn!="undefined"){if($(btn).attr('type')=="submit"){$(btn).trigger('click');}
else{$('#form1').submit();}}}
$(targets).find("input[geo-title='latitude']:not('.geo-lookup')").val('');$(targets).find("input[geo-title='longitude']:not('.geo-lookup')").val('');if(navigator&&navigator.geolocation){if(targets.length>0){navigator.geolocation.getCurrentPosition(successGeo,failGeo);}}
else{$.webshims.polyfill();setTimeout(function(){if(navigator&&navigator.geolocation){if(targets.length>0)
navigator.geolocation.getCurrentPosition(successGeo,failGeo);}
else{alert(localize('STR_GEOLOCATION_NOT_SUPPORTED'));if(isSubmittingForm&&typeof btn!="undefined"){if($(btn).attr('type')=="submit"){$(btn).trigger('click');}
else{$('#form1').submit();}}}},1000);}},address:function(address){var address='500 Yale Avenue North, Seattle, WA 98109';$.ajax({url:'http://geocoding.geo.census.gov/geocoder/locations/onelineaddress?address='+address+'&benchmark=Public_AR_Current&format=jsonp',dataType:'jsonp',success:function(response){console.log(response);},error:function(error){alert("opps");}});}}
$.addFieldLogic=function(jsonForm,newcol){"use strict";var rules=jsonForm.ruleList;var fields=jsonForm.fields;if(!(rules===null||rules===""))
FormEngine.addRulesToFields(rules,fields);if(newcol){$(newcol).find('input[type=checkbox].group-required').trigger('refreshCustomValidityRules');}
$(document).trigger('jquery-uiReady.initinputui');};var jsonMap={};var uploadFieldMap={};$.reInitializeDateField=function(element){$(element).datepicker("destroy");var q=$(element).closest('li,td[data-col]').data('qfield');var dateFormat=q.format||LF.datepicker.defaultSetting.dateFormat;var altval=$(element).attr("altval");var fm=$(element).attr("momentpattern");if(altval=="today"){$(element).attr("value",moment().locale("en-us").format(fm));}
var min=!$(element).attr('min')?"1900":$(element).attr('min');var max=!$(element).attr('max')?"2200":$(element).attr('max');if(min.indexOf('-')===-1)
min=min+"-01-01";if(max.indexOf('-')===-1)
max=max+"-12-31";var a=$.datepicker.parseDate("yy-mm-dd",min);var b=$.datepicker.parseDate("yy-mm-dd",max);var minY=min.split('-')[0];var maxY=max.split('-')[0];var isReadonly=q.isReadonly||$(element).is('[readonly]')||$(element).is('[backend-readonly]');var options=$.extend({},LF.datepicker.defaultSetting,{buttonText:localize('STR_DATE_SELECTION'),isRTL:false,dateFormat:dateFormat,buttonImage:LF.Url.contentRoot+'img/calendar.png?v=10.1',minDate:a,maxDate:b,yearRange:minY+'Y:'+maxY+'Y',constrainInput:false});$(element).datepicker(options);$('img.ui-datepicker-trigger').off();var minDate=$(element).datepicker("option","minDate").getDate();minDate=minDate>9?minDate.toString():'0'+minDate.toString();var maxDate=$(element).datepicker("option","maxDate").getDate();maxDate=maxDate>9?maxDate.toString():'0'+maxDate.toString();var minMonth=$(element).datepicker("option","minDate").getMonth()+1;minMonth=minMonth>9?minMonth.toString():'0'+minMonth.toString();var maxMonth=$(element).datepicker("option","maxDate").getMonth()+1;maxMonth=maxMonth>9?maxMonth.toString():'0'+maxMonth.toString();var minYear=$(element).datepicker("option","minDate").getFullYear();var maxYear=$(element).datepicker("option","maxDate").getFullYear();var minD=minYear.toString()+"-"+minMonth+"-"+minDate;var maxD=maxYear.toString()+"-"+maxMonth+"-"+maxDate;$(element).attr('min',minD);$(element).attr('max',maxD);$(element).siblings("img").toggle(!isReadonly);var dateField=$(element).closest(".cf-field");if(altval=="today"&&$(element).attr("vo")=="d"&&$(dateField).find(".date-submission").length>0){$(dateField).find(".date-submission").show();$(dateField).find(".calendar").hide();}
else{$(dateField).find(".date-submission").hide();$(dateField).find(".calender").show();}
if(isReadonly){$(element).datepicker("destroy");}};$.repeatInitialize=function(parent,table,newItem,multiInsert){if(jsonForm!==undefined&&jsonForm.fields!==undefined){for(var i=0;i<jsonForm.fields.length;i++)
jsonMap[jsonForm.fields[i].fieldId]=jsonForm.fields[i];var fixqFieldItems=null;if(newItem){fixqFieldItems=newItem.find("li[id^=q],td[data-col^=q]");}
else{fixqFieldItems=$("li[id^=q],td[data-col^=q]");}
fixqFieldItems.each(function(){var id=parseInt(($(this).attr("id")||$(this).attr("data-col")).toString().substring(1),10);$(this).data('qfield',jsonMap[id]);});}
var target=parent===undefined?$('.calendar'):newItem.find('.calendar');target.each(function(){$.reInitializeDateField(this);});if(!multiInsert){$.addFieldLogic(jsonForm,newItem||parent);}
$('span.margin-end').each(function(){currency=_.find(currency_list,{'code':($(this).next().attr('currencyformat')||'USD')})
$(this).text(currency['symbol']);});LF.tooltip(".cf-tooltip");if(newItem&&newItem.find('.cf-geolocation').length){var currentGen=newItem.find(".cf-geolocation input[vo='d'][default-val='current_location']");if(currentGen.length>0){var geoField=currentGen.closest('.cf-geolocation');if($(geoField).find('.geo-submission:hidden').length>0){$(geoField).find('.geo-submission').show();$(geoField).find('.geo-display, .geo-specify').hide();}
geolocation.init($(geoField).not(':has(.geo-submission)'),false);}
var geoFields=newItem.find('.cf-geolocation');_.forEach(geoFields,function(geo){var latitude=$(".geo-specify input[geo-title='latitude']",geo).first().val();var longitude=$(".geo-specify input[geo-title='longitude']",geo).first().val();if((latitude&&latitude!="current_location")&&$(".geo-specify:hidden",geo).length>0&&$(".geo-submission",geo).length==0){$(geo).find('.geo-specify').css('display','inline-block');$(geo).find('.geo-specify-rtn').show();$(geo).find('.geo-default, .geo-current, .geo-current-rtn').hide();}});}};$.InitializeForm=function(jsonForm){"use strict";fixMaxLength($('input[name^=Field][maxlength],textarea[name^=Field][maxlength]'));$(".cf-form").on("click focus",".form-q input, .form-q select, .form-q textarea",FormEngine.highlightOn);$.repeatInitialize();if($('body').hasClass('webkit')){document.getElementById("form1").reset();}
$('.fileuploader:not([readonly]):not([backend-readonly])').each(function(){var config={};var uploadFieldId=$(this).attr('id');config.target=$(this);config.fieldId=uploadFieldId.match(/\d+/);config.fieldData=jsonMap[config.fieldId];uploadFieldMap[uploadFieldId]=_.isNull(config.fieldData.length)?{availableFileNum:config.fieldData.length}:{availableFileNum:config.fieldData.length-$(this).parent().find('table tr a').length};config.uploadData=uploadFieldMap[uploadFieldId];if(!_.isNull(config.fieldData.length)&&config.uploadData.availableFileNum<0){$("#"+jQuerySelectorEscape("exceedUploadLimit"+config.fieldId.input)).show();}
config.preview=$('#preview-notice').length;config.uqid=$('[name=uqid]').val();if($('table.files a',config.target.parent()).length>0)
config.target.attr('required',null).addClass('hasFiles');$(this).newfileupload(config);});setReadOnlyFields($('body'))
function setReadOnlyFields(root){root.find('[backend-readonly]').on('keydown',function(event){if(event.keyCode==9||(event.ctrlKey&&(event.keyCode==67||event.keyCode==65))){return;}
event.preventDefault();}).on('paste',function(event){event.preventDefault();}).on('click',function(event){event.preventDefault();}).on('cut',function(event){event.preventDefault();}).on('mousedown',function(event){if(!$(this).is('input:text')&&!$(this).is('textarea')){if($.browser.webkit||$.browser.msie){event.preventDefault();}else{this.blur();window.focus();}}}).on('contextmenu',function(event){if($(this).is('[readonly]')){return;}
event.preventDefault();});}
function insertedinit(uiitem){uiitem.find('.form-focused').removeClass('form-focused').end();uiitem.find('.singleline').each(function(){if($(this).attr('id')){$(this).attr('list','datalist'+$(this).attr('id').match(/\d+/));}}).end().find('datalist').remove();uiitem.find('.fileuploader:not([readonly]):not([backend-readonly])').each(function(){var config={};var uploadFieldId=$(this).attr('id');config.target=$(this);config.fieldId=uploadFieldId.match(/\d+/);config.fieldData=jsonMap[config.fieldId];config.preview=$('#preview-notice').length;config.uqid=$('[name=uqid]').val();uploadFieldMap[uploadFieldId]={availableFileNum:config.fieldData.length};config.uploadData=uploadFieldMap[uploadFieldId];$(this).newfileupload(config);});var rid=$("[name^=Field]",uiitem).closest('li').attr('id');if(rid){if(typeof FormEngine.ruleNbrs[rid.match(/\d+/)]!=="undefined"){$("[name^=Field]",uiitem).bind('change keyup input lookup',rulesHandler);}}
if($.AutoFitForm){$.AutoFitForm(uiitem);}}
$(".cf-table tbody").repeatable({items:'>tr',renumber:true,inserted:function(e,ui){insertedinit(ui.item);}});$(".cf-collection").repeatable({items:'.form-q>ul',renumber:true,inserted:function(e,ui){insertedinit(ui.item);}});$(document).on('focusin','.hasDatepicker',function(){if(!$('#ui-datepicker-div').is(':visible')){$.reInitializeDateField(this);}
$(this).datepicker('show');if($('html').is('[dir="rtl"]')){$('#ui-datepicker-div').position({my:"right top",at:"right bottom",of:$(this)});}});$(document).on('click','img.ui-datepicker-trigger',function(){var $dateP=$(this).siblings();$.reInitializeDateField($dateP.filter('.hasDatepicker'));if($('html').is('[dir="rtl"]')){$('#ui-datepicker-div').position({my:"right top",at:"right bottom",of:$dateP});}
if(!$('#ui-datepicker-div').is(':visible')){$dateP.datepicker('show');}else{$dateP.datepicker('hide');}});$(document).on('click','.Sign_Sig',function(){if($(this).is('[readonly]')||$(this).is('[backend-readonly]')||$(this).is(":disabled")){return;}
Signature.curSignatureField=$(this).closest(".cf-field:has(.Dataurl_Sig)");Signature.curSignatureFieldId=$('input.Dataurl_Sig',Signature.curSignatureField).attr('id');Signature.currentSig.isInPerson=Signature.curSignatureField.find('.Dataurl_Sig').hasClass('inPerson');if(Signature.currentSig.isInPerson){Signature.positionModal(this);}else{Signature.getSignatureThumbnail(this);}});$(window).on('resize',function(){var sigDialog=$('#form-signature-dlg');if(sigDialog.is(':visible')&&sigDialog.hasClass('in')){Signature.positionModal(Signature.curSignatureField);}});function renumberTableRows(tbody,section){var r=tbody.attr("repeatrowlabel")||localize('STR_DEFAULT_ROWLABEL');var columnsToUpdate=null;var startpos=0;if(!section){columnsToUpdate=tbody.find(".col0").slice(0);}
else{columnsToUpdate=section.find(".col0");startpos=section.index();}
columnsToUpdate.each(function(i){var pos=i+startpos;var findnum=/{n+}/g;var m=r.match(findnum);if(m)
{var deleteBtn=$(this).children();$(this).text(r.replace(findnum,(pos.toString().length<(m[0].length-2))?(Array(m[0].length-1).join("0")+(pos+1)).slice(-(m[0].length-2)):(pos+1)));$(this).append(deleteBtn);}});};function fixMaxLength(elements){elements.each(function(i,ele){var m=$(ele).attr('maxlength');if(m){$(ele).val($(ele).val().substring(0,m));}});}
$.addtableRow=function(addbtn,pos,multiInsert){var tbody=$("#"+addbtn.data("target")).find("tbody:first");var newSection=tbody.repeatable("add",{"btn":addbtn,"index":pos});newSection.find('.prepopulate').each(function(){LF.lookup.prePopulate(addbtn);});renumberTableRows(tbody,newSection);var newestFields=newSection.find("[id^=Field]");fixMaxLength(newestFields);var listRootFields={};newestFields.each(function(){if($(this).hasClass("number")){var numberFieldAttr=$(this).attr('decimal-disabled');if(typeof numberFieldAttr!==typeof undefined&&numberFieldAttr!==false){LF.number.setNumberFieldTriggers($(this));}
else if($(this).hasClass("currency")){LF.number.setCurrencyFieldTriggers($(this));}
if(!multiInsert){$(this).trigger('updateNumberFormat');}}
var fieldId=$(this).attr("id").replace("Field","");LF.formula.setTriggerCollectionField(fieldId);if(!multiInsert){LF.formula.updateCollectionFormulas(fieldId,false,$(this));}
var fieldWithoutRow=fieldId.replace(/\([^)]*\)/,"");if(fieldWithoutRow!=fieldId){listRootFields[fieldWithoutRow]="";}});LF.formula.setErrorRemoval(newestFields);$.repeatInitialize(tbody.parent(),true,newSection,multiInsert);if(!multiInsert){$.checkAddDeleteBtnDisplayed(tbody.closest('li'));}
$(newSection).fillLookupFields(null,true);newestFields.each(function(){$(this).trigger('refreshCustomValidityRules');});setReadOnlyFields(newSection);return listRootFields;}
$('.cf-table-add-row').click(function(){$.addtableRow($(this),$(this).siblings('table').find('tr').length);});var MAX_ROWS=10000;$.setTableColRowCount=function(li,sel,newCount,isTable,howManyRowsUserInput){var opt=jQuery.parseJSON(li.data('qfield').subLabel);var rep=li.find(sel);if(opt.repeatableRowsType==0){$.checkAddDeleteBtnDisplayed(li);return li.find(sel);}
if(opt.repeatableRowsType==2){li.data('qfield').rangeMax=opt.rowMaxAdd!=undefined?(opt.rowMaxAdd+newCount-howManyRowsUserInput):MAX_ROWS;li.data('qfield').rangeMin=(opt.rowMinAdd+newCount-howManyRowsUserInput);}
var curCount=rep.length;if(newCount<li.data('qfield').rangeMin){newCount=li.data('qfield').rangeMin;}
else if(li.data('qfield').rangeMax!=null&&newCount>li.data('qfield').rangeMax){newCount=li.data('qfield').rangeMax;}
if(newCount<curCount){var t=_.take(rep,curCount-howManyRowsUserInput);if(opt.repeatableRowsType==2){_.each(_.last(t,curCount-newCount),function(k,n){if(isTable){delTableRow($(k));}
else{$(k).parent().find('.cf-collection-delete').trigger('click');}});}}
else{for(var i=0;i<(newCount-curCount);i++){if(rep.length!=newCount){if(isTable){$.addtableRow(li.find('.cf-table-add-row'),curCount+i,true);}
else{$.addCollection(li.find('.cf-collection-append'),curCount+i,true);}}}}
cleanUpTableCollection(li);return li.find(sel);}
$.clearEmptyRowCol=function(rep,isTable,fromNum,minSize,opt){if(opt&&opt.repeatableRowsType==1){var curCount=rep.length;rep.each(function(k,n){if(k>(fromNum-1)&&curCount>minSize){var emptyRow=true;$(n).find(isTable?'td[data-col]':'li').each(function(o,i){if(!$.isEmptyCell(i)){emptyRow=false;return false;}});if(emptyRow){if(isTable){delTableRow($(n));}
else{$(n).parent().find('.cf-collection-delete').trigger('click');}
curCount--;}}});}}
$.isEmptyCell=function(ele){var df=$(ele).data('qfield');var foundData=false;switch(df.type){case"doc":foundData=$(ele).find('.files td a, .files td span').length;break;case"geolocation":if($(ele).find('.geo-current').is(':visible')){foundData=true;break;}
case"address":$(ele).find('input').each(function(i,o){if($(o).val()){foundData=true;return false;}});break;case"radio":case"checkbox":foundData=$(ele).find("input:checked").length;break;default:foundData=$(ele).find("input,textarea,select").val();}
return!foundData;}
function delTableRow(ele){var tbody=ele.closest('tbody');addAttachRepsToRemove(ele.closest('tr'),true);var fieldsBeingRemoved=ele.closest('tr').siblings('tr').first().find("[id^=Field]");var triggerIdsToUpdate=new Array();fieldsBeingRemoved.each(function(){var num=$(this).attr("id").replace("Field","");triggerIdsToUpdate.push(num.substring(0,num.indexOf("(")));});ele.closest('tr').remove();tbody.repeatable("del",{"btn":ele});renumberTableRows(tbody);for(var i=0;i<triggerIdsToUpdate.length;i++){LF.formula.updateCollectionFormulas(triggerIdsToUpdate[i],true);}
$.checkAddDeleteBtnDisplayed(tbody.closest('li'));}
$('.cf-table').on('click','.form-del-field',function(){findNextItemToFocus($(this),true);delTableRow($(this));});function findNextItemToFocus(curele,istable){if($("input").length>500){return;}
var tabables=$(":tabbable");var curIndex=tabables.index(curele);var next=1;var ele=tabables.eq(curIndex+next);while(ele.closest(istable?'tr':'ul').is(istable?$(curele).closest('tr'):$(curele).siblings('ul'))){ele=tabables.eq(curIndex+(++next));}
ele.focus();}
$.addCollection=function(addbtn,pos,multiInsert){var col=$("#"+addbtn.data("target")).find(".cf-collection");var newSection=col.repeatable("add",{"btn":addbtn,"index":pos});newSection.find('.prepopulate').each(function(){LF.lookup.prePopulate(addbtn);});var listRootFields={};var newestFields=col.children().last().find("[id^=Field]");newestFields.each(function(){fixMaxLength($(this));if($(this).hasClass("number")){var numberFieldAttr=$(this).attr('decimal-disabled');if(typeof numberFieldAttr!==typeof undefined&&numberFieldAttr!==false){LF.number.setNumberFieldTriggers($(this));}
else if($(this).hasClass("currency")){LF.number.setCurrencyFieldTriggers($(this));}
if(!multiInsert){$(this).trigger('updateNumberFormat');}}
var fieldId=$(this).attr('id').replace("Field","");LF.formula.setTriggerCollectionField(fieldId);if(!multiInsert){LF.formula.updateCollectionFormulas(fieldId);}
var fieldWithoutRow=fieldId.replace(/\([^)]*\)/,"");if(fieldWithoutRow!=fieldId){listRootFields[fieldWithoutRow]="";}});LF.formula.setErrorRemoval(newestFields);$.repeatInitialize(col.parent(),false,newSection,multiInsert);if(!multiInsert){$.checkAddDeleteBtnDisplayed(col.closest('li'));}
$(newSection).fillLookupFields(null,true);var newestFields=newSection.find("[id^=Field]");newestFields.each(function(){$(this).trigger('refreshCustomValidityRules');});setReadOnlyFields(col);return listRootFields;}
$('.cf-collection-append').click(function(){$.addCollection($(this));});function cleanUpTableCollection(colitem){$.checkAddDeleteBtnDisplayed(colitem);}
function addAttachRepsToRemove(repeatitem,table){var rep=repeatitem.find('.files input[type=hidden]');if(rep.length){var delData=$('#form1 input[name=attachmentToRemove]');if(!delData.length)
delData=$('<input type="hidden" name="attachmentToRemove" value="" />').appendTo('#form1');rep.each(function(){var val=delData.val();if(val!=='')val+=',';delData.val(val+$(this).val());});}}
$('.cf-collection').on('click','.cf-collection-delete',function(){findNextItemToFocus($(this),false);addAttachRepsToRemove($(this).closest('.form-q'),false);var col=$(this).closest('.cf-collection');var triggerFields=col.children().last().find("[id^=Field]");var triggerFieldIds=_.reduce(triggerFields,function(idArray,field){idArray.push($(field).attr("id").replace("Field",""));return idArray;},[]);$(this).closest('.form-q').remove();col.repeatable("del",{"btn":$(this)});$.checkAddDeleteBtnDisplayed(col.closest('li'));_.forEach(triggerFieldIds,LF.formula.updateCollectionFormulas);});$.checkAddDeleteBtnDisplayed=function(li){var vbrc,elements;var addele=li.find('.cf-table-add-row,.cf-collection-append');var isTable=li.attr('attrtype')=='table';var internEles;if($("input[name=IsLocked]").val()==="True"){addele.hide();li.find('.cf-collection-delete,.form-del-field').each(function(){$(this).hide();});return;}
var section=li.closest('.cf-section-block');var readonlySection=false;if(section){readonlySection=section.attr('readonlySection')=='true';}
if(isTable){vbrc=li.find('tbody').attr('backendRowCount');elements=li.find('.cf-table').children('tbody').children('tr').length;internEles=li.find('tbody tr').first().find('td[data-col]');}
else{vbrc=li.find('.cf-collection').attr('backendRowCount');elements=li.find('.cf-collection .rpx').length;internEles=li.find('div.form-q').first().find('li');}
var brc=jQuery.parseJSON(vbrc||'{}');var mbrc=_.max(_.values(brc));if(mbrc===-Infinity){mbrc=0;}
li.find('.propCount').val(elements);var qf=li.data('qfield');var opt=jQuery.parseJSON(qf.subLabel);if(readonlySection){addele.hide();}
else if(opt.repeatableRowsType==1&&(qf.rangeMax==null||elements<parseInt(qf.rangeMax))){addele.show();}
else if(opt.repeatableRowsType==2&&(elements<(opt.rowMaxAdd!=undefined?(mbrc+opt.rowMaxAdd):MAX_ROWS))){addele.show();}
else{addele.hide();}
var childqfields=$.getChildrenQfields(internEles);li.find('.cf-collection-delete,.form-del-field').each(function(i,ele){if($(ele).closest('tr,.form-q').index()<mbrc){if(opt.repeatableRowsType==2){if(_.filter(childqfields,function(n){return n.isPreviousDataPreserved==true||n.isReadonly==true;}).length>0||readonlySection){$(this).hide();return true;}}}
if(opt.repeatableRowsType==1){$(ele).toggle((qf.rangeMin==null||elements>parseInt(qf.rangeMin))&&!readonlySection);}
else if(opt.repeatableRowsType==2){$(ele).toggle((opt.rowMinAdd==null||elements>parseInt(opt.rowMinAdd+mbrc))&&!readonlySection);}});}
$.getChildrenQfields=function(internEles){var dataItems=[];_.each(internEles,function(e){dataItems.push($(e).data('qfield'));});return dataItems;}
$(document).on('click','.file-del',function(){if(confirm(localize("STR_DELETING_FILE").replace("{0}",$(this).closest('tr').find('a').attr('title')))){var fieldId=$($(this).closest('table').parent().find('input').filter(':first')).attr('id');if(!_.isNull(uploadFieldMap[fieldId].availableFileNum)){uploadFieldMap[fieldId].availableFileNum=uploadFieldMap[fieldId].availableFileNum+1;if(uploadFieldMap[fieldId].availableFileNum>=0){$("#"+jQuerySelectorEscape("exceedUploadLimit"+fieldId)).hide();}else{$("#"+jQuerySelectorEscape("exceedUploadLimit"+fieldId)).show();}}
var delData=$('#form1 input[name=attachmentToRemove]');if(!delData.length)
delData=$('<input type="hidden" name="attachmentToRemove" value="" />').appendTo('#form1');var val=delData.val();if(val!=='')val+=',';delData.val(val+$(this).attr('aid'));var button=$(this).removeClass('file-del').closest('.cf-field ').find('.fileuploader');if(button&&button.is('.required')&&button.closest('.cf-field ').find('.file-del').length===0)
button.parent().find('input').attr('required',true).removeClass('hasFiles');$(this).closest('tr').remove();}});$(document).on('input keyup','.otherchoice[id^=Field]',function(){var otherchoiceval=$(this).val();if(otherchoiceval.length!==0){var item=$(this).parent().find('input[type=checkbox],input[type=radio]');if(item.prop('checked')===false){item.click();}}});var fixReadonlyTextArea=function(parent){var sel=parent?parent.parent().find('.cf-field textarea[readonly],.cf-field textarea[backend-readonly]'):$('.cf-field textarea[readonly],.cf-field textarea[backend-readonly]');sel.each(function(){if($(this).is(":visible")){this.style.height='';if(this.scrollHeight<$(this).innerHeight())
return;else
$(this).innerHeight(this.scrollHeight+6+'px');}});}
setTimeout(function(){fixReadonlyTextArea();},0);$(document).on('click',".cf-section-block>.collapsible",function(){$(this).next().slideToggle();$(this).toggleClass("collapsed");fixReadonlyTextArea($(this));});$('.collapsible').on('keyup',function(e){if(e.which==32)
$(this).click();});$('.collapsed').next().hide();$(document).on('keypress','input:not(.action-btn)',function(e){return(e.keyCode||e.which||e.charCode||0)!==13;});if($.browser.msie&&parseInt($.browser.version,10)===7)
$('button[value="__SaveDraft"]').removeAttr('name');try{var isInIframe=(window.location!=window.parent.location&&window.parent.location.pathname.indexOf("design/scripts")>-1)?true:false;if(isInIframe&&typeof isPreviewMode!='undefined'&&isPreviewMode==true){var submitBtn=$('.action-btn.Submit');if(submitBtn.length!=0){submitBtn.prop('disabled',true);}}}
catch(err){}
LFDraft.init();LFSubmit.init();if($('body').find(".cf-field:has(.Dataurl_Sig)").length){$(".cf-field:has(.Dataurl_Sig)").each(function(){Signature.curSignatureField=$(this);var curField=Signature.curSignatureField;var hiddenDataurl=curField.find('.Dataurl_Sig');var signBtn=curField.find('.Sign_Sig');if(signBtn.is('[readonly]')||signBtn.is('[backend-readonly]')){Signature.readonlyPreview(curField,hiddenDataurl.val());}else if(hiddenDataurl.hasClass('draft')&&hiddenDataurl.val()){Signature.bootstrapPreview(curField,hiddenDataurl.val());}else if(hiddenDataurl.hasClass('draft')){}else{Signature.clearSignatureField(curField);}})
if(typeof isPrintMode=='undefined'||isPrintMode!==true)
Signature.init();}
if($('body').find(".cf-field:has(.cf-geolocation)").length){var approvalGen=$('.cf-geolocation').find("input[vo='d'][default-val='current_location']");if(approvalGen.length>0){var geoField=approvalGen.closest('.cf-geolocation');if($(geoField).find('.geo-submission:hidden').length>0){$(geoField).find('.geo-submission').show();$(geoField).find('.geo-display, .geo-specify').hide();}
geolocation.init($(geoField).not(':has(.geo-submission)'),false);}
_.forEach($(".cf-geolocation"),function(geoField){var latitude=$(".geo-specify input[geo-title='latitude']",geoField).first().val();var longitude=$(".geo-specify input[geo-title='longitude']",geoField).first().val();if($(".geo-default",geoField).length>0&&!latitude&&$(".geo-specify input[readonly][geo-title='latitude']",geoField).length>0&&!longitude&&$(".geo-specify input[readonly][geo-title='longitude']",geoField).length>0){$("a.geo-current-btn",geoField).addClass("disabled");$("a.geo-specify-btn",geoField).addClass("disabled");}
if(((latitude&&latitude!="current_location")||(longitude&&longitude!="current_location"))&&$(".geo-specify:hidden",geoField).length>0&&$(".geo-submission",geoField).length==0&&$(".geo-display",geoField).length==0){$(geoField).find('.geo-specify').css('display','inline-block');$(geoField).find('.geo-specify-rtn').show();$(geoField).find('.geo-default, .geo-current, .geo-current-rtn').hide();if($(".geo-specify input[readonly][geo-title='latitude']",geoField).length>0){$(geoField).find('.geo-specify-rtn').hide();$(geoField).find('.geo-default-btn').hide();}}
if($(".geo-display",geoField).length>0){if(latitude||longitude)$(geoField).find('.geo-display-value').attr('latitude',latitude).attr('longitude',longitude).text(latitude+", "+longitude);else $(geoField).find('.geo-display-value').text("");}});$(document).ready(function(){_.forEach($(".cf-geolocation"),function(geoField){if($(".ab-help",geoField).length>0){var labelTextHeight=$(".ab-help",geoField).first().outerHeight();$(".geo-default-btn",geoField).css("top",8+labelTextHeight+"px");}});});$(document).on('click',".geo-current-btn",function(e){if($(this).hasClass("disabled"))return;var Geolocation=$(this).closest(".cf-geolocation");Geolocation.find('.geo-lookup').removeClass('geo-lookup');geolocation.init(Geolocation,false);});$(document).on('click',".geo-specify-btn",function(e){if($(this).hasClass("disabled"))return;var Geolocation=$(this).closest(".cf-geolocation");Geolocation.find('.geo-specify').css('display','inline-block');Geolocation.find('.geo-specify-rtn').show();Geolocation.find('.geo-default').hide();});$(document).on('click','.geo-current-rtn a',function(){if($(this).hasClass("disabled"))return;var Geolocation=$(this).closest(".cf-geolocation");$(Geolocation).find(".geo-specify input[geo-title='latitude']").val('').trigger('updatevalidation').trigger("lookup");$(Geolocation).find(".geo-specify input[geo-title='longitude']").val('').trigger('updatevalidation').trigger("lookup");Geolocation.find('.geo-specify').css('display','inline-block');Geolocation.find('.geo-specify-rtn').show();Geolocation.find('.geo-current, .geo-current-rtn').hide();});$(document).on('click','.geo-specify-rtn a',function(){if($(this).hasClass("disabled"))return;var Geolocation=$(this).closest(".cf-geolocation");Geolocation.find('.geo-lookup').removeClass('geo-lookup');geolocation.init(Geolocation,false);});$(document).on('click','.geo-default-btn',function(){if($(this).hasClass("disabled"))return;var Geolocation=$(this).closest(".cf-geolocation");$(Geolocation).find('.geo-current-value').attr('latitude','').attr('longitude','').text('');$(Geolocation).find(".geo-specify input[geo-title='latitude']").val('').trigger('updatevalidation').trigger("lookup");$(Geolocation).find(".geo-specify input[geo-title='longitude']").val('').trigger('updatevalidation').trigger("lookup");Geolocation.find('.geo-current, .geo-current-rtn, .geo-specify, .geo-specify-rtn').hide();Geolocation.find('.geo-default').show();});}
if($("input[name=IsLocked]").val()!=="True"){_.each($('[backendrowcount]'),function(ele){$.checkAddDeleteBtnDisplayed($(ele).closest('li'));});}};var autoFitted=null;$.AutoFitForm=function(loc){loc.find('textarea[readonly]:visible, textarea[backend-readonly]:visible').each(function(){if(!autoFitted){var currentScrollY=window.pageYOffset;if($('body').height()>screen.height)
$('body').height($('body').height()+1000);autoFitted=setTimeout(function(){window.scrollTo(0,currentScrollY);autoFitted=null;$('body').height('');},15);}
this.style.height='';if(this.scrollHeight<$(this).innerHeight())
return;else
$(this).innerHeight(this.scrollHeight+6+'px');});};var FormEngine={ruleNbrs:[],highlightOn:function(){$(".form-focused").removeClass('form-focused');if($(this).closest('input').attr('readonly')!=="readonly")
$(this).closest(".cf-repeat,.form-q,.cf-table tr").addClass('form-focused');},evalRuleSet:function(rules,fields,ruleNbrs,context,listChanged){var self=this;var rn=ruleNbrs;for(var i=0,maxi=rn.length;i<maxi;i++){var rule=_.clone(rules[rn[i]]);rule.context=context;if(_.find(listChanged,function(i){return _.isEqual(i,rule);})){continue;}
if(listChanged){listChanged.push(rule);}
$.each(eval(rule.targetFieldId)||[],function(t,target){var $el=null;if(context&&context.length){if(context.closest('.cf-collection').size()!==0){$el=context.parent().closest('ul').find('#q'+target.T);}
else{$el=context.parent().closest('.cf-table-block').find('#q'+target.T);}}
if(!$el){$el=$(jQuery.grep($('.form-q,.cf-section-block'),function(item){return $(item).attr('id')=='q'+target.T;}));}
$el.add('[id^=q'+target.T+'_]',context);var isTableColumn=$el.parent().is("tr");var match=RulesEngine.evalRule(rule,fields,context);var fieldVisibilityStateFlipped=false;if(match===(target.A==="show")){if(isTableColumn){if(context&&context.length){var curTableEle=context.closest("tr").find("td:nth-child("+($el.index()+1)+")");var inputele=curTableEle.find("input,textarea,select");_.each(inputele,function(ie){if(!inputele.attr("backend-disabled")){$(ie).attr("disabled",null);}});if(curTableEle.find('.cf-field').attr("rule-hidden")){curTableEle.find('.cf-field').show().attr("rule-hidden",null);}
var dateelement=curTableEle.find('.calendar');if(dateelement.length>0){$.reInitializeDateField($(dateelement));}
if(curTableEle.find(".cf-geolocation").length>0&&curTableEle.find(".geo-current").length>0){curTableEle.find("a.geo-current-btn, a.geo-specify-btn, .geo-current-rtn a, .geo-specify-rtn a, .geo-default-btn").removeClass("disabled");}}
else{LF.validator.flipHiddenState($el.closest(".cf-table").find("td:nth-child("+($el.index()+1)+")"),false,null);LF.validator.flipHiddenState($el.closest(".cf-table").find("th:nth-child("+($el.index()+1)+")"),false,null);}}
else{LF.validator.flipHiddenState($el,false,null);fieldVisibilityStateFlipped=true;}}
else{if(isTableColumn){if(context){var curTableEle=context.closest("tr").find("td:nth-child("+($el.index()+1)+")");curTableEle.find("input,textarea,select").attr("disabled","disabled");curTableEle.find(".cf-field").attr('rule-hidden',true).hide();var dateelement=curTableEle.find('.calendar');if(dateelement.length>0){$.reInitializeDateField($(dateelement));}
if(curTableEle.find(".cf-geolocation").length>0){curTableEle.find("a.geo-current-btn, a.geo-specify-btn, .geo-current-rtn a, .geo-specify-rtn a, .geo-default-btn").addClass("disabled");}}
else{LF.validator.flipHiddenState($el.closest(".cf-table").find("td:nth-child("+($el.index()+1)+")"),true,null);LF.validator.flipHiddenState($el.closest(".cf-table").find("th:nth-child("+($el.index()+1)+")"),true,null);}}
else{LF.validator.flipHiddenState($el,true,null);fieldVisibilityStateFlipped=true;}}
if(self.ruleNbrs[target.T]){if($el.closest('.cf-table').size()===0&&$el.closest('.cf-collection').size()===0){self.evalRuleSet(rules,fields,self.ruleNbrs[target.T],null,listChanged);}
else if($el.closest('.cf-collection').size()!==0){$el.each(function(n){self.evalRuleSet(rules,fields,self.ruleNbrs[target.T],$($el[n]),listChanged);});}
else{$el.each(function(n){var index=$($el[n]).index();$($el[n]).closest(".cf-table").find("tbody > tr").each(function(r){self.evalRuleSet(rules,fields,self.ruleNbrs[target.T],$(this).find("td").eq(index).find("input,select"),listChanged);});});}}
if(fieldVisibilityStateFlipped){var memberId=null;_.forEach(fields,function(field){if(field.fieldId==target.T||(field.memberId&&field.memberId==memberId)){if(field.type=="table"){memberId=field.memberId;}
else{return false;}}
else if(memberId){if(self.ruleNbrs[field.fieldId]){$el.find('[id^="Field'+field.fieldId+'("]').each(function(){self.evalRuleSet(rules,fields,self.ruleNbrs[field.fieldId],$(this),listChanged);});}}});}})}},addRulesToFields:function(rules,fields){"use strict";var self=this;self.rules=rules;self.fields=fields;var fOnKeyup=function(){var triggerEle=$(this).attr('geo-title')?'.geo-q':'.form-q';var id=$(this).closest(triggerEle).attr('id').match(/\d+/);var listChanged=[];self.evalRuleSet(rules,fields,self.ruleNbrs[id],null,listChanged);};var fOnKeyupRepeatable=function(){var listChanged=[];if($(this).closest('.cf-table').size()!==0){if($(this).attr('geo-title')){var id=$(this).closest('.geo-q').attr('id').match(/\d+/);}
else{var id=$(this).closest('td').data('col').match(/\d+/);}
self.evalRuleSet(rules,fields,self.ruleNbrs[id],$(this),listChanged);}
else{var triggerEle=$(this).attr('geo-title')?'.geo-q':'li';var id=$(this).closest(triggerEle).attr('id').match(/\d+/);self.evalRuleSet(rules,fields,self.ruleNbrs[id],$(this).closest('.form-q'),listChanged);}};var fOnKeyupOther=function(){var listChanged=[];var id=$(this).closest('.form-q').attr('id').match(/\d+/);self.evalRuleSet(rules,fields,self.ruleNbrs[id],null,listChanged);};var listChanged=[];for(var i=0,maxi=rules.length;i<maxi;i++){var rule=rules[i];var criteria=rule.criteria;if(criteria&&criteria.length>0){for(var j=0,max=criteria.length;j<max;j++){var itemid=criteria[j].referenceFieldId;var criteriaEl=$("#q"+itemid+",[id^=q"+itemid+"_]");if(criteriaEl.size()===0){continue;}
if(self.ruleNbrs[itemid]==null)
self.ruleNbrs[itemid]=[];var event=$("[name=Field"+itemid+"]:not(.bfOnKeyup)").bind(($.browser.mozilla||window.chrome)?'input change lookup':'change keyup lookup',fOnKeyup).addClass('bfOnKeyup');$("[name^=Field"+itemid+"\\(]:not(.bfOnKeyupRepeatable)").bind('lookup change keyup input',fOnKeyupRepeatable).addClass('bfOnKeyupRepeatable');$("#Field"+itemid+"_other_value[type=text]:not(.bfOnKeyupOther)").bind('keyup input',fOnKeyupOther).addClass('bfOnKeyupOther');var ruleNbrs=self.ruleNbrs[itemid];if(jQuery.inArray(i,ruleNbrs)<0){ruleNbrs.push(i);}}
if(criteriaEl.closest('.cf-table').size()===0&&criteriaEl.closest('.cf-collection').size()===0)
self.evalRuleSet(rules,fields,[i],null,listChanged);else if(criteriaEl.closest('.cf-collection').size()!==0){criteriaEl.each(function(n){self.evalRuleSet(rules,fields,[i],$(criteriaEl[n]),listChanged);});}
else{criteriaEl.each(function(n){var index=$(criteriaEl[n]).index();$(criteriaEl[n]).closest(".cf-table").children('tbody').children('tr').each(function(r){self.evalRuleSet(rules,fields,[i],$(this).children("td").eq(index).find("input,select,textarea"),listChanged);});});}}}}};function rulesHandler(){"use strict";var listChanged=[];var id=$(this).closest('li').attr('id').match(/\d+/);if(typeof FormEngine.ruleNbrs[id]!=="undefined")
FormEngine.evalRuleSet(FormEngine.rules,FormEngine.fields,FormEngine.ruleNbrs[id],$(this).closest('.form-q'),listChanged);}
var RulesEngine={getFieldObjectById:function(fields,fieldId){return $.grep(fields,function(field){return field.fieldId==fieldId;});},stripForCompare:function(str){str=str||'';str=$.trim(str).toLowerCase();return str;},_fieldContainer:function(context){if(context&&context.closest('.cf-collection').size()!==0)
return"collection";else if(context&&context.closest('.cf-table').size()!==0)
return"table";return"none";},_resolveFieldId:function(fieldId,context){var fc=this._fieldContainer(context);if(fc==="collection"){var index=_.findIndex(context.closest('.cf-collection').find('.rpx'),function(ele){return ele==context.parent().closest('.rpx')[0];});return"Field"+fieldId+"\\("+(parseInt(index)+1).toString()+"\\)";}
else if(fc==="table")
return"Field"+fieldId+"\\("+(parseInt(context.parent().closest('tr').index())+1).toString()+"\\)";else
return"Field"+fieldId;},isQuestionHidden:function(fieldId,context){var q;if(!context)
q=$('#q'+fieldId);else{var fc=this._fieldContainer(context);if(fc==="collection"){q=context.closest(".cf-section-block").find("[id^="+this._resolveFieldId(fieldId,context)+"]").closest('.form-q')}
else{q=context.closest(".cf-section-block").find("[id^="+this._resolveFieldId(fieldId,context)+"]");}}
if(q.hasClass('hidden')||q.parents(".section").hasClass('hidden'))
return true;return false;},isempty:function(value){value=value||'';value=$.trim(value);if(value==='')return true;else return false;},is:function(str1,str2){return(str1===str2);},isnot:function(str1,str2){return(str1!==str2);},isblank:function(str1,str2){return(str1===str2);},isnotblank:function(str1,str2){return(str1!==str2);},contain:function(haystack,needle){if(needle===''&&haystack==='')return true;if(needle===''&&haystack!=='')return false;if(haystack.indexOf(needle)===-1)return false;else return true;},notcontain:function(haystack,needle){if(needle===''&&haystack==='')return false;if(needle===''&&haystack!=='')return true;if(haystack.indexOf(needle)===-1)return true;else return false;},startswith:function(str,prefix){return(str.indexOf(prefix)===0);},endswith:function(str,suffix){return str.indexOf(suffix,str.length-suffix.length)!==-1;},isless:function(exprLeft,exprRight){if(this.isempty(exprLeft))
return false;if(this.isempty(exprRight))
return false;exprLeft=Number(exprLeft);exprRight=Number(exprRight);if(exprLeft<exprRight)return true;else return false;},isgreater:function(exprLeft,exprRight){if(this.isempty(exprLeft))
return false;if(this.isempty(exprRight))
return false;exprLeft=Number(exprLeft);exprRight=Number(exprRight);if(exprLeft>exprRight)return true;else return false;},isbefore:function(exprLeft,exprRight){return this._timeCompare(exprLeft,exprRight,0);},isafter:function(exprLeft,exprRight){return this._timeCompare(exprLeft,exprRight,1);},ison:function(exprLeft,exprRight){return this._timeCompare(exprLeft,exprRight,2);},_timeCompare:function(exprLeft,exprRight,ind){var before=(exprLeft<exprRight)?true:false;var after=(exprLeft>exprRight)?true:false;return[before,after,!before&!after][ind];},compareFieldValue:function(field,op,answer,context){var match=false;var f=this._resolveFieldId(field.fieldId,context);var el=$('[name='+f+']').add('[name^='+f+'\\(]',context);if(el.size()===0){}
if(el.is(':radio,:checkbox')){var thisEngine=this;var items=$('input[name='+f+']:checked');if(items.size()===0){match=thisEngine[op]("",answer);}
else{items.each(function(){value=thisEngine.stripForCompare($(this).val());value=value.substring(0,50);answer=answer.substring(0,50);if(thisEngine['is'](value,answer)){match=true;return;}});if(op=='isnot'||op=='isnotblank')
match=!match;}
return match;}
else if(field.type=='date'){var fieldValue=el.val();if(op=='isblank'){match=this.stripForCompare(fieldValue)=="";}
else if(op=='isnotblank'){match=this.stripForCompare(fieldValue)!="";}
else{try{fieldValue=$.datepicker.parseDate(field.format,fieldValue);if(fieldValue==null){match=false;}
else{answer=$.datepicker.parseDate('yy-mm-dd',answer);match=this[op](fieldValue,answer);}}
catch(ex){}}}
else if(field.type=='select'){var thisEngine=this;for(var i=0;i<field.optionLabelex.length;i++){var option=field.optionLabelex[i];if(answer==thisEngine.stripForCompare(option.Key)){answer=thisEngine.stripForCompare(option.Value)}}
var items=$('select[id='+f+']');if(items.size()===0){match=thisEngine[op]("",answer);}
else{items.each(function(){value=thisEngine.stripForCompare($(this).val());value=value.substring(0,50);answer=answer.substring(0,50);if(thisEngine['is'](value,answer)){match=true;return;}});if(op=='isnot'||op=='isnotblank')
match=!match;}
return match;}
else if(field.type==='number'){var fieldValue=this.stripForCompare(el.val());fieldValue=LF.number.removeThousandsSeparator(fieldValue);fieldValue=LF.number.removeTrailingZeros(fieldValue);var correctedAnswer=LF.number.removeThousandsSeparator(answer);correctedAnswer=LF.number.removeTrailingZeros(correctedAnswer);match=this[op](fieldValue,correctedAnswer);}
else{var fieldValue=this.stripForCompare(el.val());match=this[op](fieldValue,answer);}
return match;},evalCriteria:function(crit,field,context){var matched=false;var criteriaAnswer=this.stripForCompare(crit.value);matched=this.compareFieldValue(field,crit.operator,criteriaAnswer,context);return matched;},evalRule:function(rule,fields,context){var criteria=rule.criteria;var match=rule.criteriaLogic==='all';for(var j=0;j<criteria.length;j++){var field=this.getFieldObjectById(fields,criteria[j].referenceFieldId)[0];if(this.evalCriteria(criteria[j],field,context)){if(rule.criteriaLogic==='any'){match=true;break;}}
else{if(rule.criteriaLogic==='all'){match=false;break;}}}
return match;}};var LFDraft={init:function(){var saveButton=$('button[value="__SaveDraft"]');var emailEle=$('input[name="tfa_emailadd"]');var pwdEle=$('input[name="tfa_password"]');saveButton.on('click',function(){LF.LFForms.saveFlag=true;var valid=true;$.each([emailEle,pwdEle],function(i,n){if(!LF.validator.getEleValid(n)){valid=false;LF.validator.onValidate({target:n});$(this).focus();return false;}});if(valid){$('<input type="hidden" name="action" />').val($(this).val()).insertBefore($(this));$('#form1').prop('novalidate',true);$('#form1').submit();$(this).attr('disabled','disabled');$('input[type=submit]').addClass('btn-disabled');}});$('#draftPage.modal').on('show.bs.modal',function(){$('#form1').find('.cf-field [required]').filter(function(){return $(this).is(':required');}).add('.group-required').addClass('draft_removedrequired').removeAttr('required');if(!$('input, textarea, select').trigger('updatevalidation').checkValidity()||!$('#form1').checkValidity()){$('#form1').find('.draft_removedrequired').attr('required','required').removeClass('draft_removedrequired');return false;}
var input=$(this).find('input').removeAttr('disabled');if(!LF.isAuthenticated){input.attr('required','required');}
$(this).find('input:first').focus();})
$('#draftPage.modal').on('hidden.bs.modal',function(){_.each($('#form1').find('.draft_removedrequired'),function(ele){$(ele).removeClass('draft_removedrequired');if(!($(ele).hasClass('group-required')&&$(ele).attr('type')=='checkbox')){$(ele).attr('required','required');}});$(this).find('input').removeAttr('required').attr('disabled','');$('#form1').find('.user-success').removeClass('user-success').trigger('updatevalidation');})
if(!LF.isAuthenticated){CheckValidation();emailEle.on('input change paste keyup mouseup',CheckValidation);pwdEle.on('input change paste keyup mouseup',CheckValidation);}
function CheckValidation(){var status=(emailEle[0]==null)?false:((pwdEle[0]==null)?($.trim(emailEle.val())===''):($.trim(emailEle.val())===''||$.trim(pwdEle.val())===''));saveButton.prop('disabled',status);}}};var submitting=false;var LFSubmit={init:function(){var isGeolocationSubmitted=false;var isSaveUserTaskDraft=false;$('#form1').on('submit',function(event){var currentBtn=document.activeElement;if(typeof currentBtn!="undefined"){if($(currentBtn).attr('type')!="submit"&&$('#form1').find('button[value=__SaveAction][active]').length>0){currentBtn=$('#form1').find('button[value=__SaveAction][active]').removeAttr('active')[0];isSaveUserTaskDraft=true;}}
if($('#form1').find(".geo-specify input[readonly][data-val='current_location']:not(.geo-lookup)").length>0&&!LF.LFForms.saveFlag&&!isSaveUserTaskDraft){var geoFields=$('#form1').find(".geo-specify input[readonly][data-val='current_location']:not(.geo-lookup)").closest(".cf-geolocation");if(!isGeolocationSubmitted){geolocation.init(geoFields,true,currentBtn);isGeolocationSubmitted=true;event.stopImmediatePropagation();return false;}
else{_.forEach(geoFields,function(geoField){var latitude=$(".geo-specify input[geo-title='latitude']",geoField).first().val();var longitude=$(".geo-specify input[geo-title='longitude']",geoField).first().val();if(latitude=="current_location")$(geoField).find(".geo-specify input[geo-title='latitude']").val('').trigger('updatevalidation');if(longitude=="current_location")$(geoField).find(".geo-specify input[geo-title='longitude']").val('').trigger('updatevalidation');});}}
if($('#form1').find(".geo-specify input[data-val='current_location']:not(.geo-lookup)").length>0&&(LF.LFForms.saveFlag||isSaveUserTaskDraft)){var geoFields=$('#form1').find(".geo-specify input[data-val='current_location']:not(.geo-lookup)").closest(".cf-geolocation");_.forEach(geoFields,function(geoField){var isSaveAsCurrent=$(geoField).find(".geo-current:visible").length>0||($(geoField).find("input[geo-title='latitude']:visible:not('.geo-lookup')").val()==""&&$(geoField).find("input[geo-title='longitude']:visible:not('.geo-lookup')").val()=="");if($(geoField).find("input:not('.geo-lookup')").length==2&&isSaveAsCurrent){$(geoField).find("input[geo-title='latitude']:not('.geo-lookup')").val("current_location");$(geoField).find("input[geo-title='longitude']:not('.geo-lookup')").val("current_location");}});}
if($('#form1').find(".calendar").length>0){var dateFields=$('#form1').find(".calendar");_.forEach(dateFields,function(date){var val=$(date).val();if(!val)return;var v=null;var lang=document.documentElement.lang.indexOf("ar")>-1?"ar-ma":document.documentElement.lang;v=$(window)[0].moment(val,$(date).attr('momentPattern'),lang);if(!v.isValid()&&$(date).attr('momentPattern').toUpperCase()=="DD-MMM-YY"){v=$(window)[0].moment(val,"DD-MMM-YY","en");}
if(!v.isValid()){v=$(window)[0].moment(val);}
var saveVal=v.locale('en').format($(date).attr('momentPattern'));$(date).val(saveVal);});}
if(submitting){event.stopImmediatePropagation();return false;}
if($('input[name=__validator]').size()>0){if($('input[name=__validator]:first').val()!=''){event.stopImmediatePropagation();return false;}
if(new Date().valueOf()-LF.LFForms.readyTime<500){event.stopImmediatePropagation();return false;}}
if($("#recaptcha_widget").size()>0&&!LF.LFForms.saveFlag){$('#validateError').hide();LF.LFForms.validatedVal='';var form={action:'Form',method:'Validate'};var data={recaptcha_challenge_field:$("#recaptcha_challenge_field").val(),recaptcha_response_field:$("#recaptcha_response_field").val()};LFSubmit.validate(data);if(!LFSubmit.updateUI(LF.LFForms.validatedVal)){event.stopImmediatePropagation();$('input[type=submit]').removeClass('btn-disabled');return false;}}
if(_.filter(uploadFieldMap,function(um){return um.availableFileNum<0;}).length>0){return false;}
$('.lf-no-validate').prop('disabled',false).removeClass('lf-no-validate');$('#form1').attr('novalidate','');var isScrolledIntoView=function(elem){var $elem=$(elem);var $window=$(window);var docViewTop=$window.scrollTop();var docViewBottom=docViewTop+$window.height();var elemTop=$elem.offset().top;var elemBottom=elemTop+$elem.height();return((elemBottom<=docViewBottom)&&(elemTop>=docViewTop));}
if(!$('#form1').prop('novalidate')&&LF.formula.errorCount>0){$("div[class=ws-errorbox]:not([hidden])").show();$(".formula-error-hidden").removeClass('formula-error-hidden').addClass('formula-error');var popField=$("div[class=ws-errorbox]:visible").first().siblings("input[id^=Field]").first();if(!isScrolledIntoView(popField)){$('html, body').animate({scrollTop:popField.offset().top},function(){popField.focus();});}
else{popField.focus();}
return false;}
if(typeof isPreviewMode!='undefined'&&isPreviewMode==true){window.location.reload();}
submitting=true;if(LF.inIframe()){setTimeout(function(){$('.cf-formwrap').replaceWith($('<div class="loading text-muted"><h4 style="margin-top:40px" class="text-center">'+localize("STR_LOADING")+'</h4></div>'));},100);}
else{$('<div style="opacity:0" class = "ui-widget-overlay" />').appendTo('.cf-formwrap');$('<h4 style="text-align:center" >'+localize("STR_SUBMITTING")+'</h4>').appendTo('form');$('.cf-formwrap').fadeTo("fast",.8);}
$('#form1').find("select:disabled").prop('disabled',false);});},validate:function(dataVal){$.ajax({type:'POST',url:LF.Url.validateUrl,cache:false,data:dataVal,dataType:'json',async:false,error:function(){LF.LFForms.validatedVal=localize("STR_FAILED_TO_VALIDATE");},success:function(data){LF.LFForms.validatedVal=data.Value;}});},validateReCaptcha:function(dataVal,btn){$.ajax({type:'POST',url:LF.Url.validateRecaptchaUrl,cache:false,data:dataVal,dataType:'json',async:false,error:function(data){LF.LFForms.recaptchaState='ready';LF.LFForms.validatedVal=localize("STR_FAILED_TO_VALIDATE");},success:function(data){LF.LFForms.recaptchaState='gotResult';LF.LFForms.validatedVal=data.success?"true":"false";$('#form1').submit();}});},updateUI:function(result){result=$.trim(result);if(result!==''){Recaptcha.reload('t');$('#validateError').text(result);$("#validateError").show();return false;}
return true;}};var GET_THUMBNAIL="/user/current/signature/thumbnail";var GET_SIGNATURE_CONFIG="/user/current/signature";var SAVE_SIGNATURE="/user/current/signature";var GENERATE_THUMBNAIL="/signature/thumbnail";var GENERATE_SIGNATURE="/signature/fullsize";var PREVIEW_FONTS="/signature/fonts";var Signature={defaultSig:{typeName:"",dataUrl:"",signatureFont:0,signatureType:0},currentSig:{},signatureDlg:{},curSignatureField:{},curSignatureFieldId:'',tableSigWidth:100,sigPad:{},cacheEnabled:false,alwaysShowEmptySigPad:true,Cache:{Add:function(id,sig){if(this.Exist(id)){this.Remove(id);}
var clone=_.clone(sig);this._cache.push({id:id,value:clone});},Remove:function(id){_.remove(this._cache,function(sig){return sig.id==id;});},Get:function(id){return _.clone(_.find(this._cache,{id:id}).value);},Exist:function(id){return _.some(this._cache,{id:id});},Clear:function(){this._cache=[];},_cache:[]},init:function(elem){Signature.selectSignatureDialog();Signature.signatureDlg.on('show.bs.modal',function(e){Signature.clearCanavas();Signature.clearText();Signature.checkFlashPlugin();var s=function(data){if(Signature.signatureDlg.is('#form-signature-dlg')){var _id=Signature.curSignatureFieldId;if(!Signature.currentSig.isInPerson){if(Signature.Cache.Exist(_id)){Signature.currentSig=Signature.Cache.Get(_id);}
else{$.extend(Signature.currentSig,Signature.defaultSig,data);}}
else{if(Signature.Cache.Exist(_id)){Signature.currentSig=Signature.Cache.Get(_id);}
else{Signature.currentSig=$.extend({isInPerson:true},Signature.defaultSig);}}
if(Signature.currentSig.signatureType==0){$('#sigNav a:first').tab('show');$('#typeSignature').val(Signature.currentSig.typeName);if(Signature.currentSig.isInPerson){Signature.getSignaturePreview();}
else if(Signature.currentSig.dataUrl){$('#type-sample').attr('src',Signature.currentSig.dataUrl);}
else{Signature.getSignaturePreview();}}else{$('#sigNav a:last').tab('show');$('#typeSignature').val('');if(!Signature.alwaysShowEmptySigPad){Signature.sigPad.fromDataURL(Signature.currentSig.dataUrl);}
Signature.getSignaturePreview();}
Signature.checkBtns();Signature.getFontsPreview();Signature.signatureDlg.on('hidden.bs.modal',function(){$('body').css('min-height','');Signature.curSignatureField.find('a').first().focus();});if(Signature.alwaysShowEmptySigPad){$.extend(Signature.currentSig,Signature.defaultSig,{signatureType:1});$('#sigNav a:first').tab('show');Signature.getSignaturePreview();Signature.clearCanavas();Signature.clearText();Signature.checkBtns();}}else{$.extend(Signature.currentSig,Signature.defaultSig,{signatureType:1});Signature.checkBtns();}}
if(LF.isAuthenticated){$.ajax({type:"GET",cache:false,url:LF.Url.webapi+GET_SIGNATURE_CONFIG,contentType:"application/json; charset=utf-8",dataType:"json"}).done(s);}
else{s({IsAuthenticated:false});}});if(typeof FlashCanvas!="undefined"){FlashCanvas.initElement(Signature.signatureDlg.find('.signatureSettings')[0]);}
if(typeof SignaturePad!="undefined"){Signature.sigPad=new SignaturePad(Signature.signatureDlg.find('.signatureSettings')[0],{minWidth:0.5,maxWidth:3,onBegin:function(){$('.signature-btn').prop('disabled',false);}});}
$('#sigNav').on('shown.bs.tab',function(){Signature.checkBtns();});$('.signSignatureBtn').on('click',function(){if($('#sigNav li.active').index()==1&&Signature.sigPad.isEmpty()){alert(localize('WRN_NO_SIG'));return false;}else{Signature.acceptsignature();if(Signature.cacheEnabled){Signature.Cache.Add(Signature.curSignatureFieldId,Signature.currentSig);}}});$('.clearSignature').on('click',function(){Signature.clearCanavas();$('.signature-btn').prop('disabled',true);});$('#typeSignature').on('keyup keypress paste',function(){$('.signature-btn').prop('disabled',true);clearTimeout(this.updatePreviewTimer);this.updatePreviewTimer=setTimeout(function(){Signature.currentSig.typeName=$('#typeSignature').val();Signature.getFontsPreview();Signature.getSignaturePreview(true);},300);})},acceptsignature:function(){if($('#sigNav li.active').index()==0){Signature.currentSig.dataUrl=$('#type-sample').attr('src');Signature.currentSig.signatureType=0;Signature.currentSig=$.extend({},Signature.defaultSig,Signature.currentSig);Signature.generateThumbnail();}else{Signature.currentSig.dataUrl=Signature.sigPad.toDataURL();Signature.currentSig.signatureType=1;Signature.currentSig.typeName='';Signature.generateCanvasThumbnail(Signature.currentSig);Signature.sigPad.clear();}},selectSignatureDialog:function(){if(isMobileBrowser){Signature.signatureDlg=$('#form-signature-mobile-dlg');Signature.signatureDlg.lockToLandscape();}else{Signature.signatureDlg=$('#form-signature-dlg');}},duplicateHtmlElement:function(n,elem){for(var i=0;i<n-1;++i){elem.after(elem.clone());};$('.sample-preview li').on('click',function(){$(this).siblings('.selected').removeClass('selected');$(this).addClass('selected');Signature.currentSig.signatureFont=$('.sample-preview li').index($(this));Signature.getSignaturePreview();$(".sample-preview").dropdown('toggle');return false;});},checkBtns:function(){if($('#sigNav li.active').index()==0){if($.trim($('#typeSignature').val())==""){$('#styleBtn').prop('disabled',true);$('.signature-btn').prop('disabled',true);}else{$('#styleBtn').prop('disabled',false);$('.signature-btn').prop('disabled',false);}}
else{if(Signature.sigPad.isEmpty()){$('.signature-btn').prop('disabled',true);}else{$('.signature-btn').prop('disabled',false);}};},clearCanavas:function(){Signature.sigPad.clear();},clearText:function(){Signature.currentSig.typeName='';$('#typeSignature').val('');},clearSignatureField:function(elem){elem.find('.Dataurl_Sig').removeAttr('value').val('');},generateCanvasThumbnail:function(){$.ajax({type:"POST",cache:false,data:JSON.stringify(Signature.currentSig),url:LF.Url.webapi+GENERATE_THUMBNAIL,contentType:"application/json; charset=utf-8",dataType:"json"}).done(function(data){var curField=Signature.curSignatureField;if(curField.is(':has(.form-sig-preview)')){curField.find('.form-sig-preview img').attr('src',data.thumbnail);}else{Signature.bootstrapPreview(curField,data.thumbnail);}
curField.find('.Dataurl_Sig').val(data.thumbnail);Signature.updateValidation(curField);});},generateThumbnail:function(){var selPreview=$('.sample-preview img').eq(Signature.currentSig.signatureFont).attr('src');var curField=Signature.curSignatureField;if(curField.is(':has(.form-sig-preview)')){curField.find('.form-sig-preview img').attr('src',selPreview);}else{Signature.bootstrapPreview(curField,selPreview);}
curField.find('.Dataurl_Sig').val(selPreview);Signature.updateValidation(curField);},getSignaturePreview:function(checkBtns){$.ajax({type:"POST",cache:false,data:JSON.stringify({typeName:Signature.currentSig.typeName,signatureFont:Signature.currentSig.signatureFont}),url:LF.Url.webapi+GENERATE_SIGNATURE,contentType:"application/json; charset=utf-8",dataType:"json"}).done(function(data){$('#type-sample').attr('src',data.dataUrl);if(!_.isUndefined(checkBtns)&&checkBtns){Signature.checkBtns();}});},getFontsPreview:function(){$.ajax({type:"POST",cache:false,data:JSON.stringify({typeName:Signature.currentSig.typeName}),url:LF.Url.webapi+PREVIEW_FONTS,contentType:"application/json; charset=utf-8",dataType:"json"}).done(function(data){if($('.sample-preview img').length==1){if(Signature.currentSig.signatureFont==undefined)Signature.currentSig.signatureFont=Signature.defaultSig.signatureFont;Signature.duplicateHtmlElement(data.fontThumbnailList.length,$('.sample-preview li'));};$('.sample-preview').children('.selected').removeClass('selected');$.each(data.fontThumbnailList,function(i,val){$('.sample-preview img').eq(i).attr('src',val);})});},getSignatureThumbnail:function(ele){var curField=Signature.curSignatureField;if(!curField.hasClass('signing')){curField.addClass('signing');var s=function(data){if(data){Signature.bootstrapPreview(curField,data.thumbnail);curField.find('.Dataurl_Sig').val(data.thumbnail);curField.find('a').first().focus();Signature.updateValidation(curField);$.ajax({type:"GET",cache:false,url:LF.Url.webapi+GET_SIGNATURE_CONFIG,contentType:"application/json; charset=utf-8",dataType:"json"}).done(function(data){$.extend(Signature.currentSig,Signature.defaultSig,data);Signature.Cache.Add(Signature.curSignatureFieldId,data);});}else{Signature.positionModal(ele);}
curField.removeClass('signing');}
if(LF.isAuthenticated){$.ajax({type:"GET",cache:false,url:LF.Url.webapi+GET_THUMBNAIL,contentType:"application/json; charset=utf-8",dataType:"json"}).done(s);}
else{s();}};},readonlyPreview:function(elem,data){if(data!=''){elem.find('.Sign_Sig').before("<div class='form-sig-preview'><img class='form-sig-img' src="
+data+"></div>").remove();}
else{elem.find('.Sign_Sig').prop('readonly',true);}},bootstrapPreview:function(elem,data){var iconUrl={signature:LF.Url.contentRoot+"img/lf.svg#signature",close:LF.Url.contentRoot+"img/lf.svg#close"}
elem.find('.Sign_Sig').hide().before("<div class='form-sig-preview'><img class='form-sig-img' src="
+data+"><a href='javascript: void(0)' class='form-sig-remove lfi-times' style='padding:0 5px 0 0;font-size:130%'>&times;</a><a href='javascript: void(0)' class='form-sig-edit lf-icon-signature'></a></div>");$('.form-sig-remove').on('click',function(){Signature.curSignatureField=$(this).closest(".cf-field:has(.Dataurl_Sig)");Signature.curSignatureFieldId=$('input.Dataurl_Sig',Signature.curSignatureField).attr('id');var field=Signature.curSignatureField;field.find(".Sign_Sig").show().focus();field.find(".Dataurl_Sig").val('');field.find(".form-sig-preview").remove();Signature.Cache.Remove(Signature.curSignatureFieldId);Signature.updateValidation(field);});$('.form-sig-edit').on('click',function(){Signature.curSignatureField=$(this).closest(".cf-field:has(.Dataurl_Sig)");Signature.curSignatureFieldId=$('input.Dataurl_Sig',Signature.curSignatureField).attr('id');Signature.currentSig.isInPerson=Signature.curSignatureField.find('.Dataurl_Sig').hasClass('inPerson');Signature.positionModal(this);});},updateValidation:function(elem){elem.find('.Dataurl_Sig').trigger('updatevalidation');},checkFlashPlugin:function(){if(!Modernizr.canvas){try{new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}
catch(e){$('#flashWarnMsg').show();}}},positionModal:function(eles){var canGetParent=false;try{var test=window.parent.document;canGetParent=true;}
catch(e){}
if(canGetParent&&LF.inIframe()&&!isMobileBrowser&&(window.innerHeight>Math.max($('html').height(),$('body').height())||window.innerHeight>window.screen.availHeight)){var offset=$('.inbox-pane-content',window.parent.document).scrollTop()+($('.inbox-pane-content',window.parent.document).height()-434)/2-30;if(offset<0){offset=0;}
if(!Signature.signatureDlg.hasClass('in')){Signature.signatureDlg.modal('show');}
Signature.signatureDlg.css('top',offset);}
else{if(!Signature.signatureDlg.hasClass('in')){Signature.signatureDlg.modal('show');}
Signature.signatureDlg.css('top',0);}}}
gSignature=Signature;})(jQuery);$(document).ready(function(){if(window.screen.width>480){$('textarea[id^=Field]:visible:enabled:first, input[id^=Field]:visible:enabled:first').first().focus();}
window.scrollTo(0,0);$('[name="timezone"]').val(new Date().getTimezoneOffset());LF.LFForms.readyTime=new Date().valueOf();setTimeout(function(){$('input[type="date"][readonly="readonly"]').each(function(){$(this).next().removeAttr('disabled').attr('readonly','readonly');});},1000);$('input[type=date]').css({padding:'1px 0px'}).addClass('border-box-exempt');if($('#recaptcha_response_field').size()>0){$('#recaptcha_response_field').keypress(function(){$("#validateError").hide();});}
var captcha=$('#recaptcha_widget');if(captcha.length>0){$('#recaptcha_image',captcha).attr('alt',RecaptchaStr.img_alt_text);$('#recaptcha_response_label .recaptcha_only_if_image',captcha).html(RecaptchaStr.instructions_visual);$('#recaptcha_response_label .recaptcha_only_if_audio',captcha).html(RecaptchaStr.instructions_audio);$('.recaptcha_only_if_incorrect_sol').html(RecaptchaStr.incorrect_try_again);$('#recaptcha_reload_btn',captcha).attr('title',RecaptchaStr.refresh_btn);$('#recaptcha_switch_audio_btn',captcha).attr('title',RecaptchaStr.audio_challenge);$('#recaptcha_switch_img_btn',captcha).attr('title',RecaptchaStr.visual_challenge);$('#recaptcha_whatsthis_btn',captcha).attr('title',RecaptchaStr.help_btn);$('#recaptcha_reload',captcha).attr('alt',RecaptchaStr.refresh_btn);$('#recaptcha_switch_audio',captcha).attr('alt',RecaptchaStr.audio_challenge);$('#recaptcha_switch_img',captcha).attr('alt',RecaptchaStr.visual_challenge);$('#recaptcha_whatsthis',captcha).attr('alt',RecaptchaStr.help_btn);$('#recaptcha_switch_img_btn',captcha).click(function(){Recaptcha.switch_type('image');});$('#recaptcha_switch_audio_btn',captcha).click(function(){Recaptcha.switch_type('audio');});}
$('#comments').on('change blur keydown keyup input',function(e){var value=$(this).val().replace(/([^\r])\n/g,'$1\r\n');if(value.length>500){$(this).val(value.substring(0,500));}});});
// Copyright 2012-2016 Laserfiche. All rights reserved

﻿ LF.lookup={url:'',pre:'',auto:'',startingCount:1,startingCalls:{},cache:[],backendCall:1,itemsToUpdateNumberFormat:[],cachedBindEvents:[],currentLookups:{},lookupCnt:0,firstTimeLoad:"start",changeAndTrigger:function(element,value,startEvent,originRule,addRepeatElement,dontTriggerChange,dontSetLookupAlt){if(!dontSetLookupAlt&&(addRepeatElement||typeof originRule!==typeof undefined)){$(element).attr('lookupAlt',true);}
var originalValue=$(element).val();if(value!==null){var maxlen=$(element).attr('maxlength')
if(maxlen!=null&&value!=null&&typeof value=="string"){value=value.substr(0,maxlen);}
$(element).val(value);}
if(!dontTriggerChange){$(element).trigger('change',[startEvent,originRule]);$(element).trigger('updatevalidation').checkValidity();}
else if($(element).hasClass("number")){if(dontTriggerChange){itemsToUpdateNumberFormat.push($(element));}
else{$(element).trigger('updateNumberFormat',[originalValue]);}}},init:function(target,url,pre,auto,trigOnStart){this.url=url;this.pre=pre;this.target=target;this.auto=auto;LF.lookup.lookupCnt=0;LF.lookup.firstTimeLoad="start";var repeatScripts=$('script[type="text/template"]');$('.cf-table-add-row,.cf-collection-append').addClass('hideAddRow');LF.lookup.autoPopulate();this.attrs=$.map(LF.location.search||{},function(v,k){return{ele:$('li[attr='+jQuerySelectorEscape(k)+']'),value:[v]};});this.selectAfterPopulate=[];if(this.attrs.length>0)
for(attr in this.attrs){var urlPreset=this.attrs[attr];if(urlPreset.ele===undefined||urlPreset.ele.length==0)
continue;var fieldId=urlPreset.ele.attr('id').match(/^q(\d+)/)[1];var inputElement=urlPreset.ele.find('[id^="Field'+fieldId+'"],[id^="Field'+fieldId+'("]');if(inputElement.attr('readonly')||inputElement.length==0)
continue;var inputEle=inputElement[0];if(inputEle.type=='checkbox'||inputEle.type=='radio'){var other=inputElement.filter('[id$="_other_value"]');if(other.length==1){other.val(urlPreset.value[0]);other.attr('user-preset',urlPreset.value[0]);}
continue;}
if(inputElement.attr('vo')!='u'&&!LF.NoUrlLookup){var data=urlPreset.value[0];if(inputEle.type=='text'||inputEle.type=='textarea'){if(inputEle.maxLength&&inputEle.maxLength!=-1&&data.length>parseInt(inputEle.maxLength))
data=data.substr(0,parseInt(inputEle.maxLength));}
inputElement.val(data).attr('vo','u');}
if(urlPreset.ele.attr('attrtype')=='select'){inputElement.attr('user-preset',urlPreset.value[0]);continue;}}
LF.number.init(jsonForm);LF.formula.init(jsonForm);var fillLookupRules=false;if(target.length==0&&LF.lookup.firstTimeLoad=="start"){LF.lookup.firstTimeLoad="processing";}
for(var g=0;g<target.length;g++){$.each(target[g].trigger,function(v,e){var ele=$("[id^=Field"+e+"\\("+"],[id=Field"+e+"]");$.each(ele,function(i,ne){if($(ne).attr('vo')=='u'&&$(ne).val()){$(ne).attr('user-preset',$(ne).val());}});});if(target[g].trigger.length<=1){var field="[id^=Field"+target[g].trigger[0]+"\\("+"],[id=Field"+target[g].trigger[0]+"]";$(field).data('populate',[]);LF.lookup.bindEvent(field,'change',target[g].pass,target[g].ruleId);LF.lookup.bindEvent(field,'lookup',target[g].pass,target[g].ruleId);if(trigOnStart&&$(field).val()!==null){fillLookupRules=true;$(field).trigger('change');}}
else if($("input[name=IsLocked]").val()!="True"){var lastFieldId=target[g].trigger[target[g].trigger.length-1];var field=$("[id^=Field"+lastFieldId+"\\("+"][type!=hidden],[id=Field"+lastFieldId+"][type!=hidden]");var targetScript=_.filter(repeatScripts,function(s){var fieldIds=$(s).attr('fieldIds');return _.isUndefined(fieldIds)?false:_.contains(fieldIds.split(","),lastFieldId.toString());});var templatehtml=$.parseHTML($(targetScript).html());script=$(templatehtml).find("[id^=Field"+lastFieldId+"\\("+"][type!=hidden],[id=Field"+lastFieldId+"][type!=hidden]");script.each(function(){if(script.attr('hasautofill')){return;}
var subid=$(this).attr('id').match(/\(\d+\)/);var btn=$('<button class="autofill" type="button" id="lookup'+target[g].ruleId+(subid?subid[0]:'')+'">'+localize('STR_AUTO_FILL')+'</button>').data('populate',[]).appendTo($(this).parent());btn.attr("vo",script.attr("vo"));if(field.length===0){LF.lookup.bindEvent('[id^=lookup'+target[g].ruleId+'\\('+'],[id=lookup'+target[g].ruleId+']','click',target[g].pass,target[g].ruleId);LF.lookup.bindEvent('[id^=lookup'+target[g].ruleId+'\\('+'],[id=lookup'+target[g].ruleId+']','lookup',target[g].pass,target[g].ruleId);}});script.attr('hasautofill',true);if(templatehtml&&targetScript.length>0){document.getElementById(targetScript[0].id).innerHTML=templatehtml[0].outerHTML;}
field.each(function(){if(field.attr('hasautofill')){return;}
var subid=$(this).attr('id').match(/\(\d+\)/);var btn=$('<button class="autofill" type="button" id="lookup'+target[g].ruleId+(subid?subid[0]:'')+'">'+localize('STR_AUTO_FILL')+'</button>').data('populate',[]).appendTo($(this).parent());btn.attr("vo",field.attr("vo"));LF.lookup.bindEvent('[id^=lookup'+target[g].ruleId+'\\('+'],[id=lookup'+target[g].ruleId+']','click',target[g].pass,target[g].ruleId);LF.lookup.bindEvent('[id^=lookup'+target[g].ruleId+'\\('+'],[id=lookup'+target[g].ruleId+']','lookup',target[g].pass,target[g].ruleId);if(trigOnStart){fillLookupRules=true;btn.trigger('click');}});field.attr('hasautofill',true);}}
if(fillLookupRules){$(document).fillLookupFields(true);}
$('.prepopulate').each(function(){LF.lookup.prePopulate($(this));});LF.lookup.checkOnLoadLookupFinishment();},autoPopulate:function(){var autopopulated=false;var dstringified=JSON.stringify({uniqueid:$('[name=uqid]').val(),formId:parseInt($('[name=formid]').val()),storeNum:LF.lookup.backendCall++});$.ajax({type:'POST',url:LF.lookup.auto,data:dstringified,dataType:'json',contentType:"application/json; charset=utf-8"}).done(function(result,txtStatus,xhr){autopopulated=result.length!=0;result.call=dstringified;LF.lookup.cache=$.merge(LF.lookup.cache,result);}).fail(function(xhr){}).always(function(){if(autopopulated)
$(document).fillLookupFields(true);LF.lookup.startingCount--;if(LF.lookup.startingCount==0){LF.lookup.initialLookupIsDone();}
LF.lookup.checkOnLoadLookupFinishment();});},prePopulate:function(trigger){LF.lookup.startingCount++;$.ajax({type:'POST',url:LF.lookup.pre,data:JSON.stringify({fieldId:trigger.attr('id').substr(5).replace(/\(\d+\)/g,''),uniqueid:$('[name=uqid]').val(),formId:parseInt($('[name=formid]').val()),storeNum:LF.lookup.backendCall++}),dataType:'json',contentType:"application/json; charset=utf-8"}).done(function(r,txtStatus,xhr){if(trigger.is('select')){var newSelect=trigger.attr('user-preset');if(newSelect===undefined)
newSelect=trigger.attr("hint");var text='<option></option>';$.each(r,function(i,v){var val=$.trim(v);if(val!=newSelect){text+='<option>'+val+'</option>';}
else{text+='<option selected="selected">'+val+'</option>';}});trigger.html(text);}
else if(trigger.is('input[type=text]')){var suggestions=$.map(r,function(u,i){return"<option value='"+LF.htmlEncode(u)+"'></option>";});try{$('select',trigger.prop('list')).htmlPolyfill(suggestions.join(''));}catch(e){}}
this.changeAndTrigger(trigger,null,true,undefined,false);}).fail(function(xhr){}).always(function(){LF.lookup.startingCount--;if(LF.lookup.startingCount==0){LF.lookup.initialLookupIsDone();}
LF.lookup.checkOnLoadLookupFinishment();});},addLookupCnt:function(){LF.lookup.lookupCnt++;},checkOnLoadLookupFinishment:function(){if(LF.lookup.firstTimeLoad=="processing"&&LF.lookup.lookupCnt==0&&LF.lookup.startingCount==0){LF.lookup.firstTimeLoad="end";$.event.trigger({type:"onloadlookupfinished"});}},callLookup:function(data,ruleId,colext,trigger,isStartEvent,originRule){var dstringified=JSON.stringify(data,null);var triggerId=trigger.length&&$(trigger[0]).attr('id');if(triggerId&&LF.lookup.currentLookups[triggerId]){setTimeout(function(){return LF.lookup.callLookup(data,ruleId,colext,trigger,isStartEvent,originRule);},100);return;}
LF.lookup.addLookupCnt();if(LF.lookup.firstTimeLoad=="start"){LF.lookup.firstTimeLoad="processing";}
LF.lookup.currentLookups[triggerId]=1;var xhr=$.ajax({type:'POST',url:LF.lookup.url,data:JSON.stringify({data:JSON.stringify(data,null),ruleId:ruleId,uniqueid:$('[name=uqid]').val(),formId:parseInt($('[name=formid]').val()),storeNum:LF.lookup.backendCall++,startEvent:isStartEvent}),dataType:'json',contentType:"application/json; charset=utf-8"}).done(function(result,txtStatus,xhr){if(triggerId){delete LF.lookup.currentLookups[triggerId];}
if(xhr.kill){return;}
if(colext==''||(isStartEvent&&trigger.attr("vo")!="u")){result.call=dstringified;_.each(result,function(r){var f=_.find(LF.lookup.cache,{id:r.id,expandColTable:r.expandColTable});if(f==null){LF.lookup.cache.push(r);}
else{var curval=r.value;_.merge(f,r);f.value=curval;}})}
if(trigger.data('populate')==null){trigger.data('populate',[]);}
for(var r in result){if(trigger.data('populate').indexOf(result[r].id)===-1){trigger.data('populate').push(result[r].id);}}
LF.lookup.populate($(document),result,colext,isStartEvent,ruleId);}).fail(function(xhr){if(triggerId){delete LF.lookup.currentLookups[triggerId];}}).always(function(){LF.lookup.lookupCnt--;LF.lookup.checkOnLoadLookupFinishment();});if(isStartEvent){LF.lookup.startingCalls[ruleId+colext].thecall=xhr;}},initialLookupIsDone:function(){$('.cf-table-add-row.hideAddRow,.cf-collection-append.hideAddRow').removeClass('hideAddRow');},triggerCachedCalls:function(){_.forEach(_.sortBy(LF.lookup.startingCalls,'order'),function(c){if(c.callback){c.callback();c.callback=null;}});},autotriggerCachedCall:null,bindEvent:function(trigger,event,pass,ruleId){if($(trigger).first().length===0){LF.lookup.cachedBindEvents.push(function(){return LF.lookup.bindEvent(trigger,event,pass,ruleId);});return false;}
var bindType=$(trigger).first().attr('id').indexOf('(')===-1;var lookupHandler=function(event,isSEvent,originRule){var data={};var isStartEvent=isSEvent||LF.lookup.startingCount!=0;trigger=$(event.target);var subid=$(this).attr('id').match(/\(\d+\)/);var colext=(subid?subid[0]:'');$.each(pass,function(k,v){var f='[id="Field'+v+colext+'"],[id="Field'+v+'"]';var fVal=$(f).val();if(fVal!=null){if($(f).attr('separator-disabled')==="false"){fVal=LF.number.removeThousandsSeparator(fVal);}
$.extend(data,$.parseJSON('{ "'+v+colext+'" : "'+fVal.replace(/\\/g,'\\\\')+'" }'));}});if(isStartEvent){clearTimeout(LF.lookup.autotriggerCachedCall);LF.lookup.autotriggerCachedCall=setTimeout(function(){LF.lookup.triggerCachedCalls()},0);if(!LF.lookup.startingCalls[ruleId+colext]){LF.lookup.startingCalls[ruleId+colext]={};}
else if(LF.lookup.startingCalls[ruleId+colext].thecall){try{LF.lookup.startingCalls[ruleId+colext].thecall.kill=true;}catch(r){}}
LF.lookup.startingCalls[ruleId+colext].callback=function(){LF.lookup.callLookup(data,ruleId,colext,trigger,isStartEvent,originRule);};LF.lookup.startingCalls[ruleId+colext].order=LF.lookup.backendCall++;}
else{if(LF.lookup.startingCalls[ruleId+colext]){try{LF.lookup.startingCalls[ruleId+colext].thecall.kill=true;}catch(r){}}
LF.lookup.triggerCachedCalls();LF.lookup.callLookup(data,ruleId,colext,trigger,isStartEvent,originRule);}};if(bindType)
$(trigger).on(event,lookupHandler);else
$(document).on(event,trigger,lookupHandler);return true;},locateCollectionOrTableBelongTo:function(element,colex,eles,rItem){var colTableElement=null;if(eles.length==0){$.each(element.find('[data-template]'),function(i,t){var fragment=$($.parseHTML($('#'+$(t).attr('data-template')).html()));var temp=!colex?fragment.find('[id="Field'+rItem.id+'"],[id^="Field'+rItem.id+'("]'):fragment.find('[id="Field'+rItem.id+colex+'"]');if(temp!=null&&temp.length!=0){colTableElement=$(t).closest('li');return false;}})}
else{colTableElement=eles.closest('.cf-collection,.cf-table').closest('li');}
return colTableElement;},populate:function(element,result,colex,isStartEvent,originRule,addRepeatElement,addRows){var self=this;_.each(result,function(rItem){if(isStartEvent&&this.attrs){var urldata=[];$.each(this.attrs,function(i,n){if(n.ele.length>0&&!n.ele.data('qfield').isReadonly){urldata.push({id:n.ele.attr('id').substr(1),type:n.ele.attr('attrtype'),value:n.value,urlData:true});}});result=$.merge(result,urldata);}
var addingRowsbyExpandColTable=rItem.expandColTable&&!addRepeatElement;var eles=null;var colTableElement=null;if(addingRowsbyExpandColTable&&!colex){eles=!colex?element.find('[id="Field'+rItem.id+'"],[id^="Field'+rItem.id+'("]'):element.find('[id="Field'+rItem.id+colex+'"]');colTableElement=self.locateCollectionOrTableBelongTo(element,colex,eles,rItem);}
if(!addRows){itemsToUpdateNumberFormat=[];}
var foundTabCol=false;if(colTableElement!=null&&colTableElement.length!=0){$.each(colTableElement.find('.cf-table-add-row,.cf-collection-append'),function(n,tt){var isTable=$(tt).hasClass('cf-table-add-row');var ftableCol=!colex?colTableElement.find('[id="Field'+rItem.id+'"],[id^="Field'+rItem.id+'("]'):colTableElement.find('[id="Field'+rItem.id+colex+'"]');if((isStartEvent&&ftableCol.attr("vo")=="u")){foundTabCol=true;return false;}
var brc=jQuery.parseJSON($(colTableElement).find(isTable?'tbody':'.cf-collection').attr('backendRowCount')||'{}');var oldmax=_.max(_.values(brc));var origCount=brc[rItem.id];brc[rItem.id]=rItem.value.length;var newmax=_.max(_.values(brc));var opt=jQuery.parseJSON($(colTableElement).data('qfield').subLabel);var minSize=$(colTableElement).data('qfield').rangeMin;var userInputedRows=opt.repeatableRowsType==1?1:0;var curRowCount=$(colTableElement).find(isTable?'.cf-table > tbody > tr':'ul').length;if(oldmax<curRowCount&&opt.repeatableRowsType!=0&&curRowCount>0){userInputedRows=curRowCount-oldmax;}
$(colTableElement).find(isTable?'tbody':'.cf-collection').attr('backendRowCount',JSON.stringify(brc));var colrepeats=$(colTableElement).find(isTable?'.cf-table > tbody > tr':'ul');var newCountRows=opt.repeatableRowsType==2?newmax+userInputedRows:newmax;if(newCountRows!=curRowCount){colrepeats=$.setTableColRowCount($(colTableElement),isTable?'.cf-table > tbody > tr':'ul',newCountRows,isTable,userInputedRows);}
$.each(colrepeats,function(v,e){var tvalue=rItem.value.slice(v,v+1);var res=_.omit(rItem,'value');res.value=tvalue;if(opt.repeatableRowsType!=2||(v<newmax)){self.populate($(colTableElement),[res],"("+(v+1)+")",isStartEvent,originRule,addRepeatElement,true);var rowcolele=$(e).find('[id="Field'+res.id+"("+(v+1)+")"+'"]');rowcolele.attr("vo","k");var findEmptyMark=rowcolele.siblings('[id="EmptyField'+res.id+"("+(v+1)+")"+'"]');if(v>(rItem.value.length-1)){if(findEmptyMark.length==0){$("<input type='hidden' name='Empty"+rowcolele.attr('id')+"' val = 'true' id='Empty"+rowcolele.attr('id')+"' />").insertAfter(rowcolele);}}
else if(findEmptyMark.length!=0){findEmptyMark.remove();}
var findPopulatedMark=rowcolele.siblings('[id="PopulatedField'+res.id+"("+(v+1)+")"+'"]');findPopulatedMark.remove();if(v<rItem.value.length){$("<input type='hidden' name='Populated"+rowcolele.attr('id')+"' value = '"+v.toString()+"' id='Populated"+rowcolele.attr('id')+"' />").insertAfter(rowcolele);}}});if(opt.repeatableRowsType==1)
{$.clearEmptyRowCol(colrepeats,isTable,newmax,minSize,opt);LF.formula.updateCollectionFormulas(rItem.id,true);_.each(itemsToUpdateNumberFormat,function(i){$(i).trigger('updateNumberFormat',[$(i).val()]);});$.addFieldLogic(jsonForm,true);}
foundTabCol=true;return false;})
if(foundTabCol){return;}}
else if(rItem.expandColTable&&!addRows){return;}
if(!eles){eles=!colex?element.find('[id="Field'+rItem.id+'"],[id^="Field'+rItem.id+'("]'):element.find('[id="Field'+rItem.id+colex+'"]');colTableElement=self.locateCollectionOrTableBelongTo(element,colex,eles,rItem);}
if(eles.length==0&&rItem.type!='address'){return;}
var qf=$(eles).closest('li,td').data('qfield');if(qf&&qf.isPreviousDataPreserved&&rItem.expandColTable&&(!isStartEvent||eles.first().attr("vo")=='d'||eles.first().attr("vo")=='e')){$.tempReadonly(eles,qf,rItem.value.length==1);}
var collitems=$.grep(eles,function(i){return i.id.indexOf("(")>0});if(originRule!==undefined){if(rItem.lastRule===undefined){rItem.lastRule=originRule;}
else if(rItem.lastRule==originRule){rItem.lastRule=undefined;return;}}
$(eles).each(function(i,eachE){var eachEles=$(eachE);if(!rItem.expandColTable&&qf&&qf.isPreviousDataPreserved&&eachEles.attr("vo")=='u'){var brc=jQuery.parseJSON($(colTableElement).find('.cf-table > tbody, .cf-collection').attr('backendRowCount')||'{}');if(brc[rItem.id]>i){return true;}}
var vo=eachEles.attr("vo");var maintainValue=(isStartEvent&&(vo=="u"))||(vo=="k"&&!addRows);var scr130313Case=isStartEvent&&(vo==="u")&&jsonForm.isDraft;var val=(rItem.type=='address'||eachEles.val()==null)?'':eachEles.val().trim();var userpre=eachEles.attr('user-preset');var foundPre=false;switch(rItem.type){case'select':if(rItem.urlData){if(rItem.value.length>0){self.changeAndTrigger(eachEles,rItem.value[0],true,originRule,addRepeatElement,addingRowsbyExpandColTable);}
if(eachEles.val()!=val){self.changeAndTrigger(eachEles,null,true,originRule,addRepeatElement,addingRowsbyExpandColTable);}}
else{val=eachEles.val()==null?null:$(eachEles).val().trim();var options='<option></option>';var foundItem=false;if(addRows){if(eachEles.val()!=rItem.urlData&&rItem.value.length==1){eachEles.val(rItem.value[0]);if(eachEles.val()==null){eachEles.append('<option selected="selected">'+rItem.value[0]+'</option>');}}
else if(rItem.value.length==0){eachEles.append('<option selected="selected"></option>');}}
else{for(var v=0;v<rItem.value.length;v++){var sel=rItem.value.length==1&&(vo!="u"||!isStartEvent);if(userpre){if(rItem.value[v].toUpperCase()==userpre.toUpperCase()){sel=true;foundPre=true;}}
else if(val!=null){if(rItem.value[v].toUpperCase()==val.toUpperCase()){sel=true;}}
if(sel){options+='<option selected="selected">';foundItem=true;}
else{options+='<option>';}
options+=rItem.value[v]+'</option>';}
if(!foundItem&&val!=''&&maintainValue){options+='<option selected="selected">'+val+'</option>';}
eachEles.html(options);}
if(!foundPre&&vo=="d"&&!isStartEvent&&!foundItem){self.changeAndTrigger(eachEles,$(eachEles).attr('default-val'),true,originRule,addRepeatElement,addingRowsbyExpandColTable);}
else if(addRepeatElement){self.changeAndTrigger(eachEles,null,true,originRule,addRepeatElement,addingRowsbyExpandColTable);}
if(eachEles.val()!=val){self.changeAndTrigger(eachEles,null,true,originRule,addRepeatElement,addingRowsbyExpandColTable);}}
break;case'text':try{if(eachEles.attr('list')!=null){eachEles.siblings('datalist').remove();var nameList='datalist'+eachEles.attr('id');eachEles.attr('list',nameList);eachEles.after("<datalist id='"+nameList+"'><select></select></datalist>");var suggestions=$.map(rItem.value,function(u,i){return"<option value='"+LF.htmlEncode(u)+"'></option>";});$('#'+jQuerySelectorEscape(nameList)).find('select').htmlPolyfill(suggestions.join(''));}}catch(e){}
if(rItem.value.length>1){if(vo=="d"&&_.contains(rItem.value,eachEles.attr('default-val'))){eachEles.val(eachEles.attr('default-val'));}
else if(!maintainValue){eachEles.val('');}}
else{if(!addRows){try{$('#'+eachEles.attr('list')).htmlPolyfill('');}catch(e){}}
var v=rItem.value[0];if(maintainValue){v=val;}
var maxLen=eachEles.attr('maxlength');if(rItem.urlData&&maxLen&&v.length>parseInt(maxLen)){v=v.substr(0,parseInt(maxLen));}
if(eachEles.val()!=v){self.changeAndTrigger(eachEles,v,isStartEvent,originRule,addRepeatElement,addingRowsbyExpandColTable);}
else if(scr130313Case&&eachEles.val()===rItem.value[0]){eachEles.attr('lookupAlt',true);}}
break;case'number':{var v=rItem.value[0];if(rItem.value.length>1){v="";}
if(vo=="d"&&_.contains(rItem.value,eachEles.attr('default-val'))){v=eachEles.attr('default-val');}
else if(maintainValue){v=val;}
if(rItem.urlData&&isNaN(v)){return true;}
if(eachEles.val()!=v){self.changeAndTrigger(eachEles,v,isStartEvent,originRule,addRepeatElement,addingRowsbyExpandColTable);if(eachEles.attr("geo-title"))eachEles.addClass("geo-lookup");}
else if(scr130313Case&&eachEles.val()===rItem.value[0]){eachEles.attr('lookupAlt',true);}
if(eachEles.attr("geo-title")){var geoField=eachEles.closest(".cf-geolocation");if($('.geo-specify:hidden',geoField).length>0){$('.geo-specify',geoField).css('display','inline-block');$('.geo-specify-rtn',geoField).show();$('.geo-default, .geo-current, .geo-current-rtn, .geo-submission, .geo-display, .geo-submission',geoField).hide();}}}
break;case'longtext':{var v=rItem.value[0];if(rItem.value.length>1){v="";}
if(vo=="d"&&_.contains(rItem.value,eachEles.attr('default-val'))){v=eachEles.attr('default-val');}
else if(maintainValue){v=val;}
var maxLen=eachEles.attr('maxlength');if(rItem.urlData&&maxLen&&v.length>parseInt(maxLen)){v=v.substr(0,parseInt(maxLen));}
if(eachEles.val()!=v){self.changeAndTrigger(eachEles,v,isStartEvent,originRule,addRepeatElement,addingRowsbyExpandColTable);}
else if(scr130313Case&&eachEles.val()===rItem.value[0]){eachEles.attr('lookupAlt',true);}}
break;case'currency':case'email':var v=rItem.value[0];if(rItem.value.length>1){v="";}
if(vo=="d"&&_.contains(rItem.value,eachEles.attr('default-val'))){v=eachEles.attr('default-val');}
else if(maintainValue)
v=val;if(eachEles.val()!=v)
self.changeAndTrigger(eachEles,v,isStartEvent,originRule,addRepeatElement,addingRowsbyExpandColTable);else if(scr130313Case&&eachEles.val()===rItem.value[0]){eachEles.attr('lookupAlt',true);}
break;case'date':var v=rItem.value[0];if(rItem.value.length>1){v="";}
if(vo=="d"&&eachEles.attr('default-val')){var fi=_.find(rItem.value,function(i){return moment($.datepicker.parseDate(qf.format,i)).format("YYYY-MM-DD")==eachEles.attr('default-val');});if(fi){v=fi;}}
else if(maintainValue)
v=val;var target=eachEles.next().is('input')?eachEles.next():eachEles;var dateField=null;if(target.val()!=v){self.changeAndTrigger(eachEles,v,isStartEvent,originRule,addRepeatElement,addingRowsbyExpandColTable);dateField=eachEles.closest(".cf-field");}
else if(scr130313Case&&eachEles.val()===rItem.value[0]){eachEles.attr('lookupAlt',true);}
if(dateField&&$('input:hidden',dateField).length>0){$('input',dateField).show();$('.date-submission',dateField).hide();}
break;case'address':for(var j=0;j<6;j++){$('[id="Field'+rItem.id+'_DSG'+j+colext+'"],[id^="Field'+rItem.id+colext+'("]').val(cache[r].value[j]).trigger('change');}
break;}});if($.AutoFitForm){$.AutoFitForm($(eles));}});}};$.tempReadonly=function(eles,qf,readonly){var opt=readonly?':enabled':'[tempRO=disabled]';var d=readonly?'disabled':null;var r=readonly?'readonly':null;switch(qf.type){case'address':eles.attr('disabled',d).attr('tempRO',d).attr('readonly',r);break;case'checkbox':case'radio':eles.attr('disabled',d).attr('tempRO',d).attr('readonly',r);break;case'date':var f=eles.attr('tempRO',d);f.attr('disabled',d).attr('readonly',r);if(f.length){f.next().toggle(!readonly);}
break;case'signature':var f=eles.attr('tempRO',d);if(f.length){f.next().attr('disabled',d);}
break;default:eles.attr('disabled',d).attr('tempRO',d).attr('readonly',r);}}
$.fn.lookup=function(url,pre,auto,trigOnStart){LF.lookup.init(this,url,pre,auto,trigOnStart);};$.fn.attemptLoadCachedBindEvents=function(){var cl=LF.lookup.cachedBindEvents;LF.lookup.cachedBindEvents=[];_.each(cl,function(e){e();});};$.fn.fillLookupFields=function(autoPopulate,addRepeatElement){$.fn.attemptLoadCachedBindEvents();LF.lookup.populate(this,LF.lookup.cache,null,autoPopulate,undefined,addRepeatElement);if(LF.lookup.cache!=null&&LF.lookup.target!=null&&LF.lookup.target.length){$(this).find('input, textarea, select').each(function(){if(this.id.length==0){return;}
var fieldId;try{fieldId=parseInt(this.id.match(/^Field(\d+)/)[1]);}
catch(e){return;}
var ruleId=-1;LF.lookup.target.each(function(){if(this.trigger.indexOf(fieldId)!=-1){ruleId=this.ruleId;}});if(ruleId!=-1){var hasFill=false;$.map(LF.lookup.cache,function(v,k){hasFill|=(k.lastRule==ruleId);});if(!hasFill){LF.lookup.changeAndTrigger(this,null,true,undefined,addRepeatElement,false,true);}}});}};
// Copyright 2012-2016 Laserfiche. All rights reserved

(function($){"use strict";var rmethods={_name:"repeatable",options:{'mode':'submit','buttonAddClass':'form-add-field','buttonAdd':false,'buttonDupClass':'form-dup-field','buttonDelClass':'form-del-field','inserted':function(){},'beforeInsert':function(){},'deleted':function(){},'beforeDelete':function(){},'renumber':false,'items':'li','template':false},_init:function(){this.element.addClass('kx-repeatable');this._addActionHandlers.apply(this,[this.element]);},_addActionHandlers:function(item){item.find("."+this.options.buttonAddClass).click(function(){$(this).closest(".kx-repeatable").repeatable("add",{"btn":$(this)});});item.find("."+this.options.buttonDupClass).click(function(){$(this).closest(".kx-repeatable").repeatable("dup",{"btn":$(this)});});item.find("."+this.options.buttonDelClass).click(function(){$(this).closest(".kx-repeatable").repeatable("del",{"btn":$(this)});});},_renumberRepeatables:function(start){var o=this.options;if(!start||start<0){start=0;}
this.element.find(o.items).slice(start).each(function(idx){$(this).find("*[id]:not(datalist)").each(function(){$(this).attr("id",$(this).attr("id").replace(/\(([0-9]+)\)/,"("+(idx+start+1)+")"));if($(this).not("[id$=_other_value]").length!=0){$(this).parent().children("label").attr("for",$(this).attr("id").replace(/\(([0-9]+)\)/,"("+(idx+start+1)+")"));}
if($(this).attr("name"))
$(this).attr("name",$(this).attr("name").replace(/\(([0-9]+)\)/,"("+(idx+start+1)+")"));if($(this).attr("aria-label")){$(this).attr("aria-label",$(this).attr("aria-label").replace(/\(([0-9]+)\)/,"("+(idx+start+1)+")"));}});});},add:function(foptions){foptions=foptions||{};var o=this.options;var template=o.template||foptions.btn.attr('data-template');if(!template){return;}
var fragment=$($.parseHTML($('#'+template).html()));if(o.beforeInsert.apply(this.element,['beforeInsert',{item:fragment}])===false){return false;}
var insertEnd=false;if(foptions.custom==true||this.options.custom_insert!=undefined)
this.options.custom_insert(fragment,this.element,foptions);else if(foptions.index!==undefined&&this.element.children().length>foptions.index){try{fragment.insertPolyfillBefore(this.element.children()[foptions.index]);}
catch(e){fragment.insertBefore(this.element.children()[foptions.index]);}}
else if(foptions.prepend==true){try{fragment.prependPolyfillTo(this.element);}
catch(e){fragment.prependTo(this.element);}}
else{try{fragment.appendPolyfillTo(this.element);}
catch(e)
{fragment.appendTo(this.element);}
insertEnd=true;}
this._addActionHandlers(fragment);if(o.renumber===true&&!insertEnd){this._renumberRepeatables.apply(this,[foptions.index]);}
else{this._renumberRepeatables.apply(this,[this.element.children().length-1]);}
o.inserted.apply(this.element,['inserted',{item:fragment,btn:foptions.btn}]);LF.validator.addHandlers(fragment);return fragment;},dup:function(options){var o=this.options,el=(options.btn)?options.btn.closest(o.items):this.element.find("li:first");var max=el.find('.form-dup-field').attr('prop');if(max!=null){if(el.find('.form-dup-field').hasClass('disabled'))return;var min=el.find('.form-del-field').attr('prop');var times=el.siblings().length+1;el.closest('.cf-section-block').find('.form-dup-field').toggleClass('disabled',times>=max-1).end().find('.form-del-field').toggle(times>min-1);}
if(el.size()===0){return;}
var settings={'id':null,'count':1,'at':0};if(options){$.extend(settings,options);}
var newCollection=$("");for(var i=0;i<settings.count;i++){var newclone=el.clone(true,false).removeClass('form-focused').find("input[type='text']").val('').end().find("input[type='checkbox']").removeAttr("checked").end();if(o.beforeInsert.apply(this.element,['beforeInsert',newclone])==false)
return false;if(settings.at===-1)
newclone.appendTo(this.element);else
newclone.insertAfter(el);this._addActionHandlers(newclone);if(settings.id===null){if(o.renumber===true){this._renumberRepeatables.apply(this);}}
else{newclone.find("*[id]").each(function(){el.attr("id",el.attr("id").replace(/\(([0-9]+)\)/,"("+settings.id+")"));el.attr("name",el.attr("id"));});}
newCollection=newCollection.add(newclone);var ui=new Object();ui.item=newclone;o.inserted.apply(this.element,['inserted',ui]);}
return el.pushStack(newCollection,"repeat","");},del:function(options){if(this==null||typeof options.btn==="undefined"){return;}
var o=this.options,toRemove=options.btn.closest(o.items);var min=parseInt(toRemove.find('.form-del-field').attr('prop'));if(min!=null){if(toRemove.find('.form-del-field').hasClass('disabled'))return;var times=toRemove.siblings().length+1;toRemove.closest('.cf-section-block').find('.form-dup-field').removeClass('disabled').end().find('.form-del-field').toggle(times>min+1);}
var ui={"item":toRemove};o.beforeDelete.apply(this.element,['beforeDelete',ui]);if(toRemove.siblings(o.items).length>0){toRemove.remove();o.deleted.apply(this.element,['deleted',ui]);}else{toRemove.find('input').attr('value','');}
if(o.renumber===true)
this._renumberRepeatables.apply(this);}};$.fn.repeatable=function(fn){if(rmethods[fn]){var instance=this.data(rmethods._name);return rmethods[fn].apply(instance,Array.prototype.slice.call(arguments,1));}else if(typeof fn==='object'||!fn){var arg=arguments[0];return this.each(function(){var instance=$.extend(true,{element:$(this)},rmethods);$.extend(instance.options,arg);$(this).data(rmethods._name,instance);rmethods._init.apply(instance);});}else{$.error('Method '+fn+' does not exist on jQuery.repeatable');}};})(jQuery);;
// Copyright 2012-2016 Laserfiche. All rights reserved

﻿;(function(LF){LF.validation=function(){this.errList=['patternMismatch','rangeOverflow','rangeUnderflow','stepMismatch','tooLong','typeMismatch','valueMissing'];};LF.validation.prototype={initialize:function(){this.initwebshims();this.addHandlers();this.oneTimeHandler();},initwebshims:function(){$('.ws-number').css('width','');$.webshims.ready('form-validators',function(){$.webshims.addCustomValidityRule('lfEmailRule',function(elem,value){if(value&&$(elem).hasClass('email')){var atpos=value.indexOf("@");var dotpos=value.lastIndexOf(".");if(atpos<1||dotpos<atpos+2||dotpos+2>=value.length){return true;}}
return false;},localize('ERR_VALIDATE_EMAIL_FAILED'));$.webshims.addCustomValidityRule('lfDateRule',function(elem,value){if(value&&$(elem).hasClass('calendar')&&$(elem).parent().hasClass('cf-field')){var v=null;var lang=document.documentElement.lang.indexOf("ar")>-1?"ar-ma":document.documentElement.lang;v=$(window)[0].moment(value,$(elem).attr('momentPattern'),lang);if(!v.isValid()&&$(elem).attr('momentPattern').toUpperCase()=="DD-MMM-YY"){v=$(window)[0].moment(value,"DD-MMM-YY","en");}
if(!v.isValid()){v=$(window)[0].moment(value);}
if(!v.isValid()){return true;}
var formattedVal=v.locale(lang).format($(elem).attr('momentPattern'));if(formattedVal!=value){$(elem).val(formattedVal);}}
return false;},localize('ERR_VALIDATE_DATE_FAILED'));$.webshims.addCustomValidityRule('lfDateRangeRule',function(elem,value){if(value&&$(elem).hasClass('calendar')&&$(elem).parent().hasClass('cf-field')){var v=$(window)[0].moment(value,$(elem).attr('momentPattern'));if(!v.isValid()){v=$(window)[0].moment(value);}
if(v.isValid()){var ret=false;if($(elem).attr('min')){var minDate=$(window)[0].moment($(elem).attr('min'),'YYYY-MM-DD');ret=minDate.isValid()&&v.diff(minDate)<0;}
if($(elem).attr('max')){var maxDate=$(window)[0].moment($(elem).attr('max'),'YYYY-MM-DD');ret|=(maxDate.isValid()&&v.diff(maxDate)>0);}
return ret;}}
return false;},localize('ERR_VALIDATE_DATE_OUT_OF_RANGE'));$.webshims.addCustomValidityRule('lfNumberFormatRule',function(elem,val){if(val&&$(elem).hasClass('number')&&!$(elem).hasClass('currency')&&$(elem).parent().hasClass('cf-field')){var separatorEnabled=$(elem).attr('separator-disabled')==="false";var isFormattedNumber=LF.number.isFormattedNumber(val,separatorEnabled);if(!isFormattedNumber){return true;}
var decimalDisabled=$(elem).attr('decimal-disabled');if(decimalDisabled==="true"&&val.split(LF.number.decimalChar).length!==1){return localize('ERR_NUMBER_INVALID_INTEGER');}}
return false;},localize('ERR_NUMBER_INVALID_FORMAT'));$.webshims.addCustomValidityRule('lfNumberMinRule',function(elem,val){if(val&&val!==""&&$(elem).hasClass('number')&&$(elem).parent().hasClass('cf-field')){var min=$(elem).attr('min');if(typeof min===typeof undefined||!LF.number.isNumeric(min)){return false;}
var testVal=math.bignumber(LF.number.removeNumberFormatting(val));if(testVal.lt(math.bignumber(min))){return LF.number.getMinValueErrorString(min);}}
return false;});$.webshims.addCustomValidityRule('lfNumberMaxRule',function(elem,val){if(val&&val!==""&&$(elem).hasClass('number')&&$(elem).parent().hasClass('cf-field')){var max=$(elem).attr('max');if(typeof max===typeof undefined||!LF.number.isNumeric(max)){return false;}
var testVal=math.bignumber(LF.number.removeNumberFormatting(val));if(testVal.gt(math.bignumber(max))){return LF.number.getMaxValueErrorString(max);}}
return false;});$.webshims.addCustomValidityRule('lfCalcErrorRule',function(elem,val){if(val===""&&$(elem).parent().hasClass('cf-field')){var calcErrAttr=$(elem).attr('calc-error');if(typeof calcErrAttr!==typeof undefined&&calcErrAttr!==false){var fieldId=parseInt($(elem).attr('id').substring(5));var referenceFieldsString=LF.formula.getReferenceStringOfField(fieldId);if(referenceFieldsString!==""){return localize('WRN_FORMULA_CALC_ERR')+'<br />'+referenceFieldsString;}
return localize('WRN_FORMULA_CALC_ERR');}}
return false;});});},groupRequiredValueValidation:function(e,extra){var escapedName=this.name.replace('(','\\(').replace(')','\\)');var checkbox_group=$('[name='+escapedName+']');if(checkbox_group.hasClass('group-required')){if(!checkbox_group.is(':checked')&&!checkbox_group.hasClass('draft_removedrequired')){return localize('ERR_CHECKBOX_REQUIRED');}}},escapeName:function(name){return name.replace('(','\\(').replace(')','\\)')},addHandlers:function(target){if(target===undefined){target=$('html');}
var self=this;$('input[type=text][class=otherchoice]',target).on('focusout',function(){var self=this;if(!$(self).attr('required')||$(self).attr('aria-invalid')=='true')
return;var field=$(self).closest('.cf-field');field.addClass('ws-hide');clearTimeout(self.timer);self.timer=setTimeout(function(){field.removeClass('ws-hide');field.find('.ws-errormessage').remove();$(self).trigger('resetvalidation');$(self).trigger('updatevalidation');$(self).siblings().trigger('resetvalidation').trigger('updatevalidation');},800);});$('input[type=checkbox]',target).on('change',function(){var escapedName=LF.validation.prototype.escapeName(this.name);var checkbox_group=$('[name='+escapedName+']');if(checkbox_group.hasClass('group-required')){checkbox_group.trigger('updatevalidation');}});$('input[type=checkbox]',target).on('valuevalidation',function(e,extra){var escapedName=this.name.replace('(','\\(').replace(')','\\)');var checkbox_group=$('[name='+escapedName+']');if(checkbox_group.hasClass('group-required')){if(!checkbox_group.is(':checked')&&!checkbox_group.hasClass('draft_removedrequired')){return localize('ERR_CHECKBOX_REQUIRED');}}});},oneTimeHandler:function(){$(document).on('invalid','input, textarea',function(){var section=$(this).closest('.cf-section-block');if(section){var collapsible=section.find('.collapsible.collapsed');if(collapsible){collapsible.next().show();collapsible.removeClass("collapsed");}}});$(document).on('invalid',"input[geo-title='latitude'], input[geo-title='longitude']",function(){var geoField=$(this).closest('.cf-geolocation');if($(".geo-specify:hidden",geoField).length){geoField.find('.geo-specify').css('display','inline-block');geoField.find('.geo-specify-rtn').show();geoField.find('.geo-default, .geo-current, .geo-current-rtn').hide();}});$('.cf-form').on('change','input[type=radio], input[type=checkbox]',function(){var getOtherTextbox=function(eN){return $('#'+eN+'_other_value');}
var escapedName=LF.validation.prototype.escapeName(this.name);var otherOption=$('[name='+escapedName+'][value=_other]');if(otherOption.length){var otherval=getOtherTextbox(escapedName);otherval.attr('disabled',!otherOption[0].checked).attr('readonly',!otherOption[0].checked);if($('[name='+escapedName+']').hasClass('group-required')){otherval.attr('required',otherOption[0].checked);otherval.trigger('resetvalidation');$(this).trigger('resetvalidation');}
if(otherOption[0].checked){$(otherval).focus();}}});},getCustomValidationMessage:function(validity,jElem){var d=jElem.data('customError'),retV=undefined;if(d){$.each(this.errList,function(i,n){if(validity[n]==true){retV=d[n];return false;}});}else{var shadowObj=$.webshims.data?$.webshims.data(jElem,'shadowData'):undefined;if(shadowObj){jElem=$(shadowObj.nativeElement);}
$.each(validity,function(name,prop){if(name!=='valid'&&prop){if($.webshims.createValidationMessage)
retV=$.webshims.createValidationMessage(jElem.get(0),name);return false;}});retV=retV||jElem.prop('validationMessage');}
return retV;},onValidate:function(target,focus){var self=this;var jElem=$(target),validity=jElem.prop('validity')||{valid:true},isIE78=($.browser.msie&&$.browser.version<9);if(jElem.prop('willValidate')&&!validity.valid){jElem.removeClass('form-ui-valid user-success').addClass('form-ui-invalid user-error');var showMsg=function(){if(focus&&!jElem.is(':checkbox')&&!jElem.is(':radio')&&!$.browser.webkit)
jElem.focus();if($.webshims.validityAlert){var msg=self.getCustomValidationMessage(validity,jElem);if(jElem.is(':file')){$.webshims.validityAlert.showFor($(jElem).parent().find('input[type=button]'),msg,false);}else{if(isIE78)
$.webshims.validityAlert.showFor($(jElem).parent(),msg,false);else
$.webshims.validityAlert.showFor(jElem,msg,true);}}};var block=jElem.closest('.cf-section-block').find('.collapsible.collapsed');;if(block.length==0){showMsg();}else{block.removeClass('collapsed').next().slideToggle(400,showMsg);}}else{jElem.removeClass('form-ui-invalid user-error').addClass('form-ui-valid user-success');}
return false;},isValidate:function(popError){var retV=$('form.cf-form').checkValidity();if(!retV&&popError==true)
$(document).trigger('invalid');return retV;},getEleValid:function(jElem){var validity=jElem.prop('validity')||{valid:true};return validity.valid;},flipHiddenState:function(e,hide,dontflipHidden,data){var ele=$(e);if(hide){if(!dontflipHidden){ele.addClass("hidden");ele.find('input:not(:disabled), textarea:not(:disabled), select:not(:disabled)').prop('disabled',true).addClass('lf-no-validate');$('.lf-no-validate.required, .lf-no-validate[required]').addClass('old-required').prop('required',false);}}
else{if(!dontflipHidden){ele.removeClass("hidden");$.each(ele.find('.fileuploader[type=file]'),function(i,item){var b=$(item).next();if(b.hasClass('fileuploader')&&b.attr('type')==="button"){$(item).width(b.width());try{if($(item).siblings('.flash-container')){var ul=LF.uploads["upload"+$(item).attr('id').substr(5)];ul.setButtonDimensions(b.width(),b.height());}}catch(e){}}});$.each(ele.find('.lf-no-validate'),function(index,item){if(!$(item).closest('.hidden').length){$(item).prop('disabled',false).removeClass('lf-no-validate');if($(item).hasClass('old-required')){$(item).removeClass('old-required');if(!$(item).hasClass('hasFiles')){$(item).prop('required',true);}}}});}}}};LF.validator=new LF.validation();})(LF);;
// Copyright 2012-2016 Laserfiche. All rights reserved

﻿(function($){var originalMethod=$.fn.attr,isIE7=($.browser&&$.browser.msie&&$.browser.version<8);$.fn.extend({attr:function(name,value){if(isIE7&&arguments.length>1&&name==='name'){this.each(function(){this.mergeAttributes(document.createElement("<input name='"+value+"'/>"),false);});return this;}else{return originalMethod.apply(this,arguments);}}});})(jQuery);;
// Copyright 2012-2016 Laserfiche. All rights reserved

﻿
(function($){var element,$dlgFrame;var _DefaultCanvasWidth=440;var _DefaultCanvasHeight=150;$.fn.lockToLandscape=function(){element=$(this);if(!isMobileBrowser)return;$dlgFrame=$('.modal-dialog',element);if($dlgFrame.length!=1)return;$(window).on('resize',_OrientationHanlder);$(document).ready(_OrientationHanlder);}
function _OrientationHanlder(){var screenPosition=_GetScreenPosition();if(screenPosition=='portrait'){_Rotate90();}
else{_UndoRotate90();}
_SetFullScreen();}
function _GetScreenPosition(){return $(window).width()>$(window).height()?"landscape":"portrait";}
function _GetScreenResolution(){return{width:$(window).width(),height:$(window).height()}}
function _Rotate90(){$dlgFrame.css({'-webkit-transform':'rotate(90deg)','-moz-transform':'rotate(90deg)','-o-transform':'rotate(90deg)','-ms-transform':'rotate(90deg)','transform':'rotate(90deg)','-webkit-transition-duration':'0s','-moz-transition-duration':'0s','-o-transition-duration':'0s','transition-duration':'0s','position':'fixed',});$('canvas',$dlgFrame).attr('rotated','');}
function _UndoRotate90(){$dlgFrame.css({'-webkit-transform':'','-moz-transform':'','-o-transform':'','-ms-transform':'','transform':'','position':'initial'});$('canvas',$dlgFrame).removeAttr('rotated');}
function _SetFullScreen(){var dlgWidth,dlgHeight,topOffset,rightOffset;var resolution=_GetScreenResolution();if(_GetScreenPosition()=='landscape'){dlgWidth=resolution.width<_DefaultCanvasWidth?_DefaultCanvasWidth:resolution.width;dlgHeight=resolution.height<_DefaultCanvasHeight?_DefaultCanvasHeight:resolution.height;}
else{dlgWidth=resolution.height<_DefaultCanvasHeight?_DefaultCanvasHeight:resolution.height;dlgHeight=resolution.width<_DefaultCanvasWidth?_DefaultCanvasWidth:resolution.width;}
var totalOffset=dlgWidth-dlgHeight;topOffset=totalOffset/2;rightOffset=-totalOffset/2;$dlgFrame.css({'width':dlgWidth+'px','height':dlgHeight+'px','margin':'0','top':topOffset+'px','right':rightOffset+'px'});$('.modal-content',$dlgFrame).css({'width':dlgWidth+'px','height':dlgHeight+'px',});}})(jQuery);;
// Copyright 2012-2016 Laserfiche. All rights reserved

﻿
$(function(){$(".cf-section-block>.collapsible.collapsed").each(function(){if(window.isPrintMode){$(this).next().show();$(this).toggleClass("collapsed");}});$.ConvertFieldsReadonly=function(){$(".files a").each(function(){if(!window.isPrintMode)
return;var v=$('<span/>').text($(this).text());$(this).replaceWith(v);});if(!($("input[name=IsLocked]").val()=="True"&&!LF.isLessThenIE8)){return;}
$(":input[name^=Field][type='text'],[type='number'],[type='email']").not(".calendar, [geo-title='latitude'][default-val='current_location'], [geo-title='longitude'][default-val='current_location']").each(function(){if(!shouldMakeReadOnly($(this)))
return;var fieldType=$(this).attr('type');var v=$('<div/>').text(fieldType=="number"?$(this).attr('data-val'):$(this).val()).html();var eid="id='"+$(this).attr('id')+"'"+" type='"+fieldType+"'";var cf=$(this).attr("currencyformat");if(cf){eid+="currencyformat='"+cf+"'";}
var link=v;if(!window.isPrintMode){link=LF.utils.GenerateLink(v,true);}
if(window.isPrintMode){$(this).parent().width($(this).parent().innerWidth());}
$(this).parent().css("word-wrap","break-word");var new1=$("<div class='ro' "+eid+" >"+link+"</div>");if(cf){new1.css("display","inline-block");}
else{setWidthPrintItem($(this)[0].className.split(/\s+/),new1);}
$(this).replaceWith(new1);});$(":input[name^=Field][type='text'].calendar").each(function(){if(!shouldMakeReadOnly($(this)))
return;var v=$('<div/>').text($(this).val()).html();if(window.isPrintMode){$(this).parent().width($(this).parent().innerWidth());}
$(this).parent().css("word-wrap","break-word");var new1=$("<span class='ro'>"+v+"</span>");if($(this).css("display")=="none"){new1.hide();}
$(this).replaceWith(new1);});$("textarea[name^=Field]").each(function(){if(!shouldMakeReadOnly($(this)))
return;var eid="id='"+$(this).attr('id')+"'"+" type='textarea'";var v=$(this).val();v=$('<div/>').text(v).html().replace(/\n/g,"<br>");var link=v;if(!window.isPrintMode){var link=LF.utils.GenerateLink(v);}
var new1=$("<div class='ro' style = 'word-wrap: break-word'  "+eid+" >"+link+"</div>");setWidthPrintItem($(this)[0].className.split(/\s+/),new1);$(this).replaceWith(new1);});$("input[name^=Field][type='checkbox'],[type='radio']").each(function(){if(!shouldMakeReadOnly($(this)))
return;$(this).attr('disabled','disabled');});$("select").each(function(){if(!shouldMakeReadOnly($(this)))
return;var t=$(this).find("option:selected").text();if(window.isPrintMode){$(this).parent().width($(this).parent().innerWidth());}
$(this).parent().css("word-wrap","break-word");var eid="id='"+$(this).attr('id')+"'"+" type='select'";var new1=$("<div class='ro' "+eid+" >"+t+"</div>");setWidthPrintItem($(this)[0].className.split(/\s+/),new1);$(this).replaceWith(new1);});if($("input[name=IsLocked]").val()=="True")
{$(".ui-datepicker-trigger, .form-del-field, .form-add-field").remove();$('.form-dup-field, .form-del-field').addClass('disabled');}
function setWidthPrintItem(classes,newItem){$.each(classes,function(index,item){if(item==='cf-xlarge'||item==='cf-large'||item==='cf-medium'||item==='cf-small'){newItem.addClass(item);return false;}});};function shouldMakeReadOnly(ele){return(!ele.hasClass("Dataurl_Sig"));};}});;
/*! bignumber.js v1.4.1 https://github.com/MikeMcl/bignumber.js/LICENCE */
(function(n){"use strict";function t(n,i){var c,l,a,b,w,p,s=this;if(!(s instanceof t))return new t(n,i);if(n instanceof t)if(u=0,i!==c)n+="";else{s.s=n.s;s.e=n.e;s.c=(n=n.c)?n.slice():n;return}if(typeof n!="string"&&(n=(a=typeof n=="number"||Object.prototype.toString.call(n)=="[object Number]")&&n===0&&1/n<0?"-0":n+""),p=n,i===c&&g.test(n))s.s=n.charAt(0)=="-"?(n=n.slice(1),-1):1;else{if(i==10)return k(n,e,r);if(n=rt.call(n).replace(/^\+(?!-)/,""),s.s=n.charAt(0)=="-"?(n=n.replace(/^-(?!-)/,""),-1):1,i!=null?i!=(i|0)&&y||(o=!(i>=2&&i<65))?(f(i,2),w=g.test(n)):(b="["+d.slice(0,i=i|0)+"]+",n=n.replace(/\.$/,"").replace(/^\./,"0."),(w=new RegExp("^"+b+"(?:\\."+b+")?$",i<37?"i":"").test(n))?(a&&(n.replace(/^0\.0*|\./,"").length>15&&f(p,0),a=!a),n=tt(n,10,i,s.s)):n!="Infinity"&&n!="NaN"&&(f(p,1,i),n="NaN")):w=g.test(n),!w){s.c=s.e=null;n!="Infinity"&&(n!="NaN"&&f(p,3),s.s=null);u=0;return}}for((c=n.indexOf("."))>-1&&(n=n.replace(".","")),(l=n.search(/e/i))>0?(c<0&&(c=l),c+=+n.slice(l+1),n=n.substring(0,l)):c<0&&(c=n.length),l=0;n.charAt(l)=="0";l++);if(i=n.length,a&&i>15&&n.slice(l).length>15&&f(p,0),u=0,(c-=l+1)>h)s.c=s.e=null;else if(l==i||c<v)s.c=[s.e=0];else{for(;n.charAt(--i)=="0";);for(s.e=c,s.c=[],c=0;l<=i;s.c[c++]=+n.charAt(l++));}}function f(n,t,i,r,f,e){if(y){var c,s=["new BigNumber","cmp","div","eq","gt","gte","lt","lte","minus","mod","plus","times","toFr"][u?u<0?-u:u:1/u<0?1:0]+"()",h=o?" out of range":" not a"+(f?" non-zero":"n")+" integer";h=([s+" number type has more than 15 significant digits",s+" not a base "+i+" number",s+" base"+h,s+" not a number"][t]||i+"() "+t+(e?" not a boolean or binary digit":h+(r?" or not ["+(o?" negative, positive":" integer, integer")+" ]":"")))+": "+n;o=u=0;c=new Error(h);c.name="BigNumber Error";throw c;}}function tt(n,i,r,u){function h(n,t){var u,e=0,s=n.length,o,f=[0];for(t=t||r;e<s;e++){for(o=f.length,u=0;u<o;f[u]*=t,u++);for(f[0]+=d.indexOf(n.charAt(e)),u=0;u<f.length;u++)f[u]>i-1&&(f[u+1]==null&&(f[u+1]=0),f[u+1]+=f[u]/i^0,f[u]%=i)}return f.reverse()}function o(n){for(var t=0,r=n.length,i="";t<r;i+=d.charAt(n[t++]));return i}var e,c,l,f,s,a;if(r<37&&(n=n.toLowerCase()),(e=n.indexOf("."))>-1)if(e=n.length-e-1,c=h(new t(r).pow(e).toF(),10),f=n.split("."),l=h(f[1]),f=h(f[0]),a=it(l,c,l.length-c.length,u,i,f[f.length-1]&1),s=a.c,e=a.e){for(;++e;s.unshift(0));n=o(f)+"."+o(s)}else s[0]?f[e=f.length-1]<i-1?(++f[e],n=o(f)):n=new t(o(f),i).plus(p).toS(i):n=o(f);else n=o(h(n));return n}function it(n,i,r,u,f,o){var y,d,k,w,a,rt=i.slice(),g=y=i.length,ut=n.length,s=n.slice(0,y),c=s.length,l=new t(p),nt=l.c=[],tt=0,it=e+(l.e=r)+1;for(l.s=u,u=it<0?0:it;c++<y;s.push(0));rt.unshift(0);do{for(k=0;k<f;k++){if(y!=(c=s.length))w=y>c?1:-1;else for(a=-1,w=0;++a<y;)if(i[a]!=s[a]){w=i[a]>s[a]?1:-1;break}if(w<0){for(d=c==y?i:rt;c;){if(s[--c]<d[c]){for(a=c;a&&!s[--a];s[a]=f-1);--s[a];s[c]+=f}s[c]-=d[c]}for(;!s[0];s.shift());}else break}nt[tt++]=w?k:++k;s[0]&&w?s[c]=n[g]||0:s=[n[g]]}while((g++<ut||s[0]!=null)&&u--);return nt[0]||tt==1||(--l.e,nt.shift()),tt>it&&b(l,e,f,o,s[0]!=null),l.e>h?l.c=l.e=null:l.e<v&&(l.c=[l.e=0]),l}function w(n,i,r){var u=i-(n=new t(n)).e,f=n.c;if(!f)return n.toS();for(f.length>++i&&b(n,u,10),u=f[0]==0?u+1:r?i:n.e+u+1;f.length<u;f.push(0));return u=n.e,r==1||r==2&&(--i<u||u<=c)?(n.s<0&&f[0]?"-":"")+(f.length>1?(f.splice(1,0,"."),f.join("")):f[0])+(u<0?"e":"e+")+u:n.toS()}function b(n,t,i,u,f){var e=n.c,s=n.s<0,c=i/2,o=n.e+t+1,h=e[o],l=f||o<0||e[o+1]!=null;if(f=r<4?(h!=null||l)&&(r==0||r==2&&!s||r==3&&s):h>c||h==c&&(r==4||l||r==6&&(e[o-1]&1||!t&&u)||r==7&&!s||r==8&&s),o<1||!e[0])return e.length=0,e.push(0),f?(e[0]=1,n.e=-t):n.e=0,n;if(e.length=o--,f)for(--i;++e[o]>i;)e[o]=0,o--||(++n.e,e.unshift(1));for(o=e.length;!e[--o];e.pop());return n}function k(n,i,u){var f=r;return r=u,n=new t(n),n.c&&b(n,i,10),r=f,n}var s=1e9,nt=1e6,e=20,r=4,c=-7,a=21,v=-s,h=s,y=!0,l=parseInt,i=t.prototype,d="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_",o,u=0,g=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,rt=String.prototype.trim||function(){return this.replace(/^\s+|\s+$/g,"")},p=t(1);t.ROUND_UP=0;t.ROUND_DOWN=1;t.ROUND_CEIL=2;t.ROUND_FLOOR=3;t.ROUND_HALF_UP=4;t.ROUND_HALF_DOWN=5;t.ROUND_HALF_EVEN=6;t.ROUND_HALF_CEIL=7;t.ROUND_HALF_FLOOR=8;t.config=function(){var n,t,g=0,p={},d=arguments,k=d[0],w="config",i=function(n,t,i){return!((o=n<t||n>i)||l(n)!=n&&n!==0)},b=k&&typeof k=="object"?function(){if(k.hasOwnProperty(t))return(n=k[t])!=null}:function(){if(d.length>g)return(n=d[g++])!=null};return b(t="DECIMAL_PLACES")&&(i(n,0,s)?e=n|0:f(n,t,w)),p[t]=e,b(t="ROUNDING_MODE")&&(i(n,0,8)?r=n|0:f(n,t,w)),p[t]=r,b(t="EXPONENTIAL_AT")&&(i(n,-s,s)?c=-(a=~~(n<0?-n:+n)):!o&&n&&i(n[0],-s,0)&&i(n[1],0,s)?(c=~~n[0],a=~~n[1]):f(n,t,w,1)),p[t]=[c,a],b(t="RANGE")&&(i(n,-s,s)&&~~n?v=-(h=~~(n<0?-n:+n)):!o&&n&&i(n[0],-s,-1)&&i(n[1],1,s)?(v=~~n[0],h=~~n[1]):f(n,t,w,1,1)),p[t]=[v,h],b(t="ERRORS")&&(n===!!n||n===1||n===0?l=(o=u=0,y=!!n)?parseInt:parseFloat:f(n,t,w,0,0,1)),p[t]=y,p};i.abs=i.absoluteValue=function(){var n=new t(this);return n.s<0&&(n.s=1),n};i.ceil=function(){return k(this,0,2)};i.comparedTo=i.cmp=function(n,i){var f,l=this,e=l.c,o=(u=-u,n=new t(n,i)).c,r=l.s,c=n.s,s=l.e,h=n.e;if(!r||!c)return null;if(f=e&&!e[0],i=o&&!o[0],f||i)return f?i?0:-c:r;if(r!=c)return r;if(f=r<0,i=s==h,!e||!o)return i?0:!e^f?1:-1;if(!i)return s>h^f?1:-1;for(r=-1,c=(s=e.length)<(h=o.length)?s:h;++r<c;)if(e[r]!=o[r])return e[r]>o[r]^f?1:-1;return s==h?0:s>h^f?1:-1};i.dividedBy=i.div=function(n,i){var r=this.c,o=this.e,s=this.s,f=(u=2,n=new t(n,i)).c,h=n.e,c=n.s,e=s==c?1:-1;return!o&&(!r||!r[0])||!h&&(!f||!f[0])?new t(!s||!c||(r?f&&r[0]==f[0]:!f)?NaN:r&&r[0]==0||!f?e*0:e/0):it(r,f,o-h,e,10)};i.equals=i.eq=function(n,t){return u=3,this.cmp(n,t)===0};i.floor=function(){return k(this,0,3)};i.greaterThan=i.gt=function(n,t){return u=4,this.cmp(n,t)>0};i.greaterThanOrEqualTo=i.gte=function(n,t){return u=5,(t=this.cmp(n,t))==1||t===0};i.isFinite=i.isF=function(){return!!this.c};i.isNaN=function(){return!this.s};i.isNegative=i.isNeg=function(){return this.s<0};i.isZero=i.isZ=function(){return!!this.c&&this.c[0]==0};i.lessThan=i.lt=function(n,t){return u=6,this.cmp(n,t)<0};i.lessThanOrEqualTo=i.lte=function(n,t){return u=7,(t=this.cmp(n,t))==-1||t===0};i.minus=function(n,i){var h,l,a,y,c=this,o=c.s;if(i=(u=8,n=new t(n,i)).s,!o||!i)return new t(NaN);if(o!=i)return n.s=-i,c.plus(n);var f=c.c,p=c.e,e=n.c,s=n.e;if(!p||!s){if(!f||!e)return f?(n.s=-i,n):new t(e?c:NaN);if(!f[0]||!e[0])return e[0]?(n.s=-i,n):new t(f[0]?c:r==3?-0:0)}if(f=f.slice(),o=p-s){for(h=(y=o<0)?(o=-o,f):(s=p,e),h.reverse(),i=o;i--;h.push(0));h.reverse()}else for(a=((y=f.length<e.length)?f:e).length,o=i=0;i<a;i++)if(f[i]!=e[i]){y=f[i]<e[i];break}if(y&&(h=f,f=e,e=h,n.s=-n.s),(i=-((a=f.length)-e.length))>0)for(;i--;f[a++]=0);for(i=e.length;i>o;){if(f[--i]<e[i]){for(l=i;l&&!f[--l];f[l]=9);--f[l];f[i]+=10}f[i]-=e[i]}for(;f[--a]==0;f.pop());for(;f[0]==0;f.shift(),--s);return(s<v||!f[0])&&(f[0]||(n.s=r==3?-1:1),f=[s=0]),n.c=f,n.e=s,n};i.modulo=i.mod=function(n,i){var f=this,h=f.c,c=(u=9,n=new t(n,i)).c,o=f.s,s=n.s;return(i=!o||!s||c&&!c[0],i||h&&!h[0])?new t(i?NaN:f):(f.s=n.s=1,i=n.cmp(f)==1,f.s=o,n.s=s,i?new t(f):(o=e,s=r,e=0,r=1,f=f.div(n),e=o,r=s,this.minus(f.times(n))))};i.negated=i.neg=function(){var n=new t(this);return n.s=-n.s||null,n};i.plus=function(n,i){var o,c=this,f=c.s;if(i=(u=10,n=new t(n,i)).s,!f||!i)return new t(NaN);if(f!=i)return n.s=-i,c.minus(n);var l=c.e,r=c.c,s=n.e,e=n.c;if(!l||!s){if(!r||!e)return new t(f/0);if(!r[0]||!e[0])return e[0]?n:new t(r[0]?c:f*0)}if(r=r.slice(),f=l-s){for(o=f>0?(s=l,e):(f=-f,r),o.reverse();f--;o.push(0));o.reverse()}for(r.length-e.length<0&&(o=e,e=r,r=o),f=e.length,i=0;f;i=(r[--f]=r[f]+e[f]+i)/10^0,r[f]%=10);for(i&&(r.unshift(i),++s>h&&(r=s=null)),f=r.length;r[--f]==0;r.pop());return n.c=r,n.e=s,n};i.toPower=i.pow=function(n){var i=n*0==0?n|0:n,r=new t(this),u=new t(p);if(((o=n<-nt||n>nt)&&(i=n/0)||l(n)!=n&&n!==0&&!(i=NaN))&&!f(n,"exponent","pow")||!i)return new t(Math.pow(r.toS(),i));for(i=i<0?-i:i;;){if(i&1&&(u=u.times(r)),i>>=1,!i)break;r=r.times(r)}return n<0?p.div(u):u};i.round=function(n,t){return n=n==null||((o=n<0||n>s)||l(n)!=n)&&!f(n,"decimal places","round")?0:n|0,t=t==null||((o=t<0||t>8)||l(t)!=t&&t!==0)&&!f(t,"mode","round")?r:t|0,k(this,n,t)};i.squareRoot=i.sqrt=function(){var o,u,c,s,h=this,n=h.c,i=h.s,f=h.e,l=e,a=r,v=new t("0.5");if(i!==1||!n||!n[0])return new t(!i||i<0&&(!n||n[0])?NaN:n?h:1/0);for(i=Math.sqrt(h.toS()),r=1,i==0||i==1/0?(o=n.join(""),o.length+f&1||(o+="0"),u=new t(Math.sqrt(o)+""),u.c||(u.c=[1]),u.e=((f+1)/2|0)-(f<0||f&1)):u=new t(o=i.toString()),c=u.e,i=c+(e+=4),i<3&&(i=0),f=i;;)if(s=u,u=v.times(s.plus(h.div(s))),s.c.slice(0,i).join("")===u.c.slice(0,i).join(""))if(n=u.c,i=i-(o&&u.e<c),n[i]==9&&n[i-1]==9&&n[i-2]==9&&(n[i-3]==9||o&&n[i-3]==4)){if(o&&n[i-3]==9&&(s=u.round(l,0),s.times(s).eq(h)))return r=a,e=l,s;e+=4;i+=4;o=""}else{if(!n[f]&&!n[f-1]&&!n[f-2]&&(!n[f-3]||n[f-3]==5)&&(n.length>f-2&&(n.length=f-2),!u.times(u).eq(h))){while(n.length<f-3)n.push(0);n[f-3]++}return r=a,b(u,e=l,10),u}};i.times=function(n,i){var f,l=this,e=l.c,o=(u=11,n=new t(n,i)).c,s=l.e,r=n.e,c=l.s;if(n.s=c==(i=n.s)?1:-1,!s&&(!e||!e[0])||!r&&(!o||!o[0]))return new t(!c||!i||e&&!e[0]&&!o||o&&!o[0]&&!e?NaN:!e||!o?n.s/0:n.s*0);for(n.e=s+r,(c=e.length)<(i=o.length)&&(f=e,e=o,o=f,r=c,c=i,i=r),r=c+i,f=[];r--;f.push(0));for(s=i-1;s>-1;s--){for(i=0,r=c+s;r>s;i=f[r]+o[s]*e[r-s-1]+i,f[r--]=i%10|0,i=i/10|0);i&&(f[r]=(f[r]+i)%10)}for(i&&++n.e,f[0]||f.shift(),r=f.length;!f[--r];f.pop());return n.c=n.e>h?n.e=null:n.e<v?[n.e=0]:f,n};i.toExponential=i.toE=function(n){return w(this,(n==null||((o=n<0||n>s)||l(n)!=n&&n!==0)&&!f(n,"decimal places","toE"))&&this.c?this.c.length-1:n|0,1)};i.toFixed=i.toF=function(n){var u,t,r,i=this;return n==null||((o=n<0||n>s)||l(n)!=n&&n!==0)&&!f(n,"decimal places","toF")||(r=i.e+(n|0)),u=c,n=a,c=-(a=1/0),r==t?t=i.toS():(t=w(i,r),i.s<0&&i.c&&(i.c[0]?t.indexOf("-")<0&&(t="-"+t):t=t.replace(/^-/,""))),c=u,a=n,t};i.toFraction=i.toFr=function(n){var k,nt,c,l,i,s,d,a=l=new t(p),v=c=new t("0"),w=this,g=w.c,tt=h,it=e,rt=r,b=new t(p);if(!g)return w.toS();for(d=b.e=g.length-w.e-1,(n==null||(!(u=12,s=new t(n)).s||(o=s.cmp(a)<0||!s.c)||y&&s.e<s.c.length-1)&&!f(n,"max denominator","toFr")||(n=s).cmp(b)>0)&&(n=d>0?b:a),h=1/0,s=new t(g.join("")),e=0,r=1;;){if(k=s.div(b),i=l.plus(k.times(v)),i.cmp(n)==1)break;l=v;v=i;a=c.plus(k.times(i=a));c=i;b=s.minus(k.times(i=b));s=i}return i=n.minus(l).div(v),c=c.plus(i.times(a)),l=l.plus(i.times(v)),c.s=a.s=w.s,e=d*2,r=rt,nt=a.div(v).minus(w).abs().cmp(c.div(l).minus(w).abs())<1?[a.toS(),v.toS()]:[c.toS(),l.toS()],h=tt,e=it,nt};i.toPrecision=i.toP=function(n){return n==null||((o=n<1||n>s)||l(n)!=n)&&!f(n,"precision","toP")?this.toS():w(this,--n|0,2)};i.toString=i.toS=function(n){var u,t,e,r=this,i=r.e;if(i===null)t=r.s?"Infinity":"NaN";else{if(n===u&&(i<=c||i>=a))return w(r,r.c.length-1,1);if(t=r.c.join(""),i<0){for(;++i;t="0"+t);t="0."+t}else if(e=t.length,i>0)if(++i>e)for(i-=e;i--;t+="0");else i<e&&(t=t.slice(0,i)+"."+t.slice(i));else if(u=t.charAt(0),e>1)t=u+"."+t.slice(1);else if(u=="0")return u;if(n!=null)if((o=!(n>=2&&n<65))||n!=(n|0)&&y)f(n,"base","toS");else if(t=tt(t,n|0,10,r.s),t=="0")return t}return r.s<0?"-"+t:t};i.toNumber=i.toN=function(){var n=this;return+n||(n.s?0*n.s:NaN)};i.valueOf=function(){return this.toS()};typeof module!="undefined"&&module.exports?module.exports=t:typeof define=="function"&&define.amd?define(function(){return t}):n.BigNumber=t})(this);
/*!
 * numeral.js
 * version : 1.5.3
 * author : Adam Draper
 * license : MIT
 * http://adamwdraper.github.com/Numeral-js/
 */
(function(){function a(a){this._value=a}function b(a,b,c,d){var e,f,g=Math.pow(10,b);return f=(c(a*g)/g).toFixed(b),d&&(e=new RegExp("0{1,"+d+"}$"),f=f.replace(e,"")),f}function c(a,b,c){var d;return d=b.indexOf("$")>-1?e(a,b,c):b.indexOf("%")>-1?f(a,b,c):b.indexOf(":")>-1?g(a,b):i(a._value,b,c)}function d(a,b){var c,d,e,f,g,i=b,j=["KB","MB","GB","TB","PB","EB","ZB","YB"],k=!1;if(b.indexOf(":")>-1)a._value=h(b);else if(b===q)a._value=0;else{for("."!==o[p].delimiters.decimal&&(b=b.replace(/\./g,"").replace(o[p].delimiters.decimal,".")),c=new RegExp("[^a-zA-Z]"+o[p].abbreviations.thousand+"(?:\\)|(\\"+o[p].currency.symbol+")?(?:\\))?)?$"),d=new RegExp("[^a-zA-Z]"+o[p].abbreviations.million+"(?:\\)|(\\"+o[p].currency.symbol+")?(?:\\))?)?$"),e=new RegExp("[^a-zA-Z]"+o[p].abbreviations.billion+"(?:\\)|(\\"+o[p].currency.symbol+")?(?:\\))?)?$"),f=new RegExp("[^a-zA-Z]"+o[p].abbreviations.trillion+"(?:\\)|(\\"+o[p].currency.symbol+")?(?:\\))?)?$"),g=0;g<=j.length&&!(k=b.indexOf(j[g])>-1?Math.pow(1024,g+1):!1);g++);a._value=(k?k:1)*(i.match(c)?Math.pow(10,3):1)*(i.match(d)?Math.pow(10,6):1)*(i.match(e)?Math.pow(10,9):1)*(i.match(f)?Math.pow(10,12):1)*(b.indexOf("%")>-1?.01:1)*((b.split("-").length+Math.min(b.split("(").length-1,b.split(")").length-1))%2?1:-1)*Number(b.replace(/[^0-9\.]+/g,"")),a._value=k?Math.ceil(a._value):a._value}return a._value}function e(a,b,c){var d,e,f=b.indexOf("$"),g=b.indexOf("("),h=b.indexOf("-"),j="";return b.indexOf(" $")>-1?(j=" ",b=b.replace(" $","")):b.indexOf("$ ")>-1?(j=" ",b=b.replace("$ ","")):b=b.replace("$",""),e=i(a._value,b,c),1>=f?e.indexOf("(")>-1||e.indexOf("-")>-1?(e=e.split(""),d=1,(g>f||h>f)&&(d=0),e.splice(d,0,o[p].currency.symbol+j),e=e.join("")):e=o[p].currency.symbol+j+e:e.indexOf(")")>-1?(e=e.split(""),e.splice(-1,0,j+o[p].currency.symbol),e=e.join("")):e=e+j+o[p].currency.symbol,e}function f(a,b,c){var d,e="",f=100*a._value;return b.indexOf(" %")>-1?(e=" ",b=b.replace(" %","")):b=b.replace("%",""),d=i(f,b,c),d.indexOf(")")>-1?(d=d.split(""),d.splice(-1,0,e+"%"),d=d.join("")):d=d+e+"%",d}function g(a){var b=Math.floor(a._value/60/60),c=Math.floor((a._value-60*b*60)/60),d=Math.round(a._value-60*b*60-60*c);return b+":"+(10>c?"0"+c:c)+":"+(10>d?"0"+d:d)}function h(a){var b=a.split(":"),c=0;return 3===b.length?(c+=60*Number(b[0])*60,c+=60*Number(b[1]),c+=Number(b[2])):2===b.length&&(c+=60*Number(b[0]),c+=Number(b[1])),Number(c)}function i(a,c,d){var e,f,g,h,i,j,k=!1,l=!1,m=!1,n="",r=!1,s=!1,t=!1,u=!1,v=!1,w="",x="",y=Math.abs(a),z=["B","KB","MB","GB","TB","PB","EB","ZB","YB"],A="",B=!1;if(0===a&&null!==q)return q;if(c.indexOf("(")>-1?(k=!0,c=c.slice(1,-1)):c.indexOf("+")>-1&&(l=!0,c=c.replace(/\+/g,"")),c.indexOf("a")>-1&&(r=c.indexOf("aK")>=0,s=c.indexOf("aM")>=0,t=c.indexOf("aB")>=0,u=c.indexOf("aT")>=0,v=r||s||t||u,c.indexOf(" a")>-1?(n=" ",c=c.replace(" a","")):c=c.replace("a",""),y>=Math.pow(10,12)&&!v||u?(n+=o[p].abbreviations.trillion,a/=Math.pow(10,12)):y<Math.pow(10,12)&&y>=Math.pow(10,9)&&!v||t?(n+=o[p].abbreviations.billion,a/=Math.pow(10,9)):y<Math.pow(10,9)&&y>=Math.pow(10,6)&&!v||s?(n+=o[p].abbreviations.million,a/=Math.pow(10,6)):(y<Math.pow(10,6)&&y>=Math.pow(10,3)&&!v||r)&&(n+=o[p].abbreviations.thousand,a/=Math.pow(10,3))),c.indexOf("b")>-1)for(c.indexOf(" b")>-1?(w=" ",c=c.replace(" b","")):c=c.replace("b",""),g=0;g<=z.length;g++)if(e=Math.pow(1024,g),f=Math.pow(1024,g+1),a>=e&&f>a){w+=z[g],e>0&&(a/=e);break}return c.indexOf("o")>-1&&(c.indexOf(" o")>-1?(x=" ",c=c.replace(" o","")):c=c.replace("o",""),x+=o[p].ordinal(a)),c.indexOf("[.]")>-1&&(m=!0,c=c.replace("[.]",".")),h=a.toString().split(".")[0],i=c.split(".")[1],j=c.indexOf(","),i?(i.indexOf("[")>-1?(i=i.replace("]",""),i=i.split("["),A=b(a,i[0].length+i[1].length,d,i[1].length)):A=b(a,i.length,d),h=A.split(".")[0],A=A.split(".")[1].length?o[p].delimiters.decimal+A.split(".")[1]:"",m&&0===Number(A.slice(1))&&(A="")):h=b(a,null,d),h.indexOf("-")>-1&&(h=h.slice(1),B=!0),j>-1&&(h=h.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g,"$1"+o[p].delimiters.thousands)),0===c.indexOf(".")&&(h=""),(k&&B?"(":"")+(!k&&B?"-":"")+(!B&&l?"+":"")+h+A+(x?x:"")+(n?n:"")+(w?w:"")+(k&&B?")":"")}function j(a,b){o[a]=b}function k(a){var b=a.toString().split(".");return b.length<2?1:Math.pow(10,b[1].length)}function l(){var a=Array.prototype.slice.call(arguments);return a.reduce(function(a,b){var c=k(a),d=k(b);return c>d?c:d},-1/0)}var m,n="1.5.3",o={},p="en",q=null,r="0,0",s="undefined"!=typeof module&&module.exports;m=function(b){return m.isNumeral(b)?b=b.value():0===b||"undefined"==typeof b?b=0:Number(b)||(b=m.fn.unformat(b)),new a(Number(b))},m.version=n,m.isNumeral=function(b){return b instanceof a},m.language=function(a,b){if(!a)return p;if(a&&!b){if(!o[a])throw new Error("Unknown language : "+a);p=a}return(b||!o[a])&&j(a,b),m},m.languageData=function(a){if(!a)return o[p];if(!o[a])throw new Error("Unknown language : "+a);return o[a]},m.language("en",{delimiters:{thousands:",",decimal:"."},abbreviations:{thousand:"k",million:"m",billion:"b",trillion:"t"},ordinal:function(a){var b=a%10;return 1===~~(a%100/10)?"th":1===b?"st":2===b?"nd":3===b?"rd":"th"},currency:{symbol:"$"}}),m.zeroFormat=function(a){q="string"==typeof a?a:null},m.defaultFormat=function(a){r="string"==typeof a?a:"0.0"},"function"!=typeof Array.prototype.reduce&&(Array.prototype.reduce=function(a,b){"use strict";if(null===this||"undefined"==typeof this)throw new TypeError("Array.prototype.reduce called on null or undefined");if("function"!=typeof a)throw new TypeError(a+" is not a function");var c,d,e=this.length>>>0,f=!1;for(1<arguments.length&&(d=b,f=!0),c=0;e>c;++c)this.hasOwnProperty(c)&&(f?d=a(d,this[c],c,this):(d=this[c],f=!0));if(!f)throw new TypeError("Reduce of empty array with no initial value");return d}),m.fn=a.prototype={clone:function(){return m(this)},format:function(a,b){return c(this,a?a:r,void 0!==b?b:Math.round)},unformat:function(a){return"[object Number]"===Object.prototype.toString.call(a)?a:d(this,a?a:r)},value:function(){return this._value},valueOf:function(){return this._value},set:function(a){return this._value=Number(a),this},add:function(a){function b(a,b){return a+c*b}var c=l.call(null,this._value,a);return this._value=[this._value,a].reduce(b,0)/c,this},subtract:function(a){function b(a,b){return a-c*b}var c=l.call(null,this._value,a);return this._value=[a].reduce(b,this._value*c)/c,this},multiply:function(a){function b(a,b){var c=l(a,b);return a*c*b*c/(c*c)}return this._value=[this._value,a].reduce(b,1),this},divide:function(a){function b(a,b){var c=l(a,b);return a*c/(b*c)}return this._value=[this._value,a].reduce(b),this},difference:function(a){return Math.abs(m(this._value).subtract(a).value())}},s&&(module.exports=m),"undefined"==typeof ender&&(this.numeral=m),"function"==typeof define&&define.amd&&define([],function(){return m})}).call(this);;
/**
 * math.js
 * https://github.com/josdejong/mathjs
 *
 * Math.js is an extensive math library for JavaScript and Node.js,
 * It features real and complex numbers, units, matrices, a large set of
 * mathematical functions, and a flexible expression parser.
 *
 * @version 0.27.0
 * @date    2014-08-21
 *
 * @license
 * Copyright (C) 2013-2014 Jos de Jong <wjosdejong@gmail.com>
 *
 * 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(e,r){"object"==typeof exports&&"object"==typeof module?module.exports=r():"function"==typeof define&&define.amd?define(r):"object"==typeof exports?exports.math=r():e.math=r()}(this,function(){return function(e){function r(t){if(n[t])return n[t].exports;var i=n[t]={exports:{},id:t,loaded:!1};return e[t].call(i.exports,i,i.exports,r),i.loaded=!0,i.exports}var n={};return r.m=e,r.c=n,r.p="",r(0)}([function(e,r,n){e.exports=n(1)},function(e,r,n){"use strict";function t(e){if("function"!=typeof Object.create)throw new Error("ES5 not supported by this JavaScript engine. Please load the es5-shim and es5-sham library for compatibility.");var r={},a={matrix:"matrix",number:"number",precision:64,epsilon:1e-14};r.config=function(e){if(e){if(i.deepExtend(a,e),e.precision&&r.type.BigNumber.config({precision:e.precision}),n(2)(r,a),e.number&&e.number.defaultType)throw new Error("setting `number.defaultType` is deprecated. Use `number` instead.");if(e.number&&e.number.precision)throw new Error("setting `number.precision` is deprecated. Use `precision` instead.");if(e.matrix&&e.matrix.defaultType)throw new Error("setting `matrix.defaultType` is deprecated. Use `matrix` instead.");if(e.matrix&&e.matrix["default"])throw new Error("setting `matrix.default` is deprecated. Use `matrix` instead.");if(e.decimals)throw new Error("setting `decimals` is deprecated. Use `precision` instead.")}return i.clone(a)},r.create=t;var s=n(142).constructor();if("function"!=typeof s.prototype.clone&&(s.prototype.clone=function(){return new s(this)}),"function"==typeof s.convert)throw new Error("Cannot add function convert to BigNumber: function already exists");return s.convert=function(e){return o(e)>15?e:new s(e)},r.error=n(5),r.type={},r.type.Complex=n(6),r.type.Range=n(7),r.type.Index=n(8),r.type.Matrix=n(9),r.type.Unit=n(10),r.type.Help=n(11),r.type.ResultSet=n(12),r.type.BigNumber=s,r.collection=n(13),r.expression={},r.expression.node=n(16),r.expression.parse=n(14),r.expression.Parser=n(15),r.expression.docs=n(17),n(28)(r,a),n(29)(r,a),n(30)(r,a),n(31)(r,a),n(32)(r,a),n(33)(r,a),n(34)(r,a),n(35)(r,a),n(36)(r,a),n(37)(r,a),n(38)(r,a),n(39)(r,a),n(40)(r,a),n(41)(r,a),n(42)(r,a),n(43)(r,a),n(44)(r,a),n(45)(r,a),n(46)(r,a),n(47)(r,a),n(48)(r,a),n(49)(r,a),n(50)(r,a),n(51)(r,a),n(52)(r,a),n(53)(r,a),n(54)(r,a),n(55)(r,a),n(56)(r,a),n(57)(r,a),n(58)(r,a),n(59)(r,a),n(60)(r,a),n(61)(r,a),n(62)(r,a),n(63)(r,a),n(64)(r,a),n(65)(r,a),n(66)(r,a),n(67)(r,a),n(68)(r,a),n(69)(r,a),n(70)(r,a),n(71)(r,a),n(72)(r,a),n(73)(r,a),n(74)(r,a),n(75)(r,a),n(76)(r,a),n(77)(r,a),n(78)(r,a),n(79)(r,a),n(80)(r,a),n(81)(r,a),n(82)(r,a),n(83)(r,a),n(84)(r,a),n(85)(r,a),n(86)(r,a),n(87)(r,a),n(88)(r,a),n(89)(r,a),n(90)(r,a),n(91)(r,a),n(92)(r,a),n(93)(r,a),n(94)(r,a),n(95)(r,a),n(96)(r,a),n(97)(r,a),n(98)(r,a),n(99)(r,a),n(100)(r,a),n(101)(r,a),n(102)(r,a),n(103)(r,a),n(104)(r,a),n(105)(r,a),n(106)(r,a),n(107)(r,a),n(108)(r,a),n(109)(r,a),n(110)(r,a),n(111)(r,a),n(112)(r,a),n(113)(r,a),n(114)(r,a),n(115)(r,a),n(116)(r,a),n(117)(r,a),n(118)(r,a),n(119)(r,a),n(120)(r,a),n(121)(r,a),n(122)(r,a),n(123)(r,a),n(124)(r,a),n(125)(r,a),n(126)(r,a),n(127)(r,a),n(128)(r,a),n(129)(r,a),n(130)(r,a),n(131)(r,a),n(132)(r,a),n(133)(r,a),n(134)(r,a),r.ifElse=function(){throw new Error("Function ifElse is deprecated. Use the conditional operator instead.")},n(2)(r,a),n(18)(r,a),n(19)(r,a),n(20)(r,a),n(21)(r,a),n(22)(r,a),n(23)(r,a),n(24)(r,a),n(25)(r,a),n(26)(r,a),r.chaining={},r.chaining.Selector=n(27)(r,a),r.config(a),r.config(e),r}var i=n(3),o=n(4).digits,a=t();"undefined"!=typeof window&&(window.mathjs=a),e.exports=a},function(e,r,n){"use strict";e.exports=function(e,r){function t(){return new f(1).exp()}function i(){return new f(1).plus(new f(5).sqrt()).div(2)}function o(e){for(var r=e,n=0/0,t=e.times(e),i=e,o=-1,a=3;!r.equals(n);a+=2)i=i.times(t),n=r,r=o>0?r.plus(i.div(a)):r.minus(i.div(a)),o=-o;return r}function a(){var e=f.constructor({precision:f.precision+4}),r=new e(4).times(o(new e(1).div(5))).minus(o(new e(1).div(239)));return new f(4).times(r)}function s(){f.config({precision:r.precision+2});var e=a();return f.config({precision:r.precision}),new f(2).times(e)}var u=(n(135),n(6)),f=e.type.BigNumber,c="bignumber"===r.number;e.pi=c?a():Math.PI,e.tau=c?s():2*Math.PI,e.e=c?t():Math.E,e.phi=c?i():1.618033988749895,e.i=new u(0,1),e.Infinity=1/0,e.NaN=0/0,e["true"]=!0,e["false"]=!1,e["null"]=null,e.uninitialized=n(136).UNINITIALIZED,e.E=e.e,e.LN2=c?new f(2).ln():Math.LN2,e.LN10=c?new f(10).ln():Math.LN10,e.LOG2E=c?new f(1).div(new f(2).ln()):Math.LOG2E,e.LOG10E=c?new f(1).div(new f(10).ln()):Math.LOG10E,e.PI=e.pi,e.SQRT1_2=c?new f(.5).sqrt():Math.SQRT1_2,e.SQRT2=c?new f(2).sqrt():Math.SQRT2,e.version=n(137)}},function(e,r){"use strict";r.clone=function n(e){var r=typeof e;if("number"===r||"string"===r||"boolean"===r||null===e||void 0===e)return e;if("function"==typeof e.clone)return e.clone();if(Array.isArray(e))return e.map(function(e){return n(e)});if(e instanceof Number)return new Number(e.valueOf());if(e instanceof String)return new String(e.valueOf());if(e instanceof Boolean)return new Boolean(e.valueOf());if(e instanceof Date)return new Date(e.valueOf());if(e instanceof RegExp)throw new TypeError("Cannot clone "+e);var t={};for(var i in e)e.hasOwnProperty(i)&&(t[i]=n(e[i]));return t},r.extend=function(e,r){for(var n in r)r.hasOwnProperty(n)&&(e[n]=r[n]);return e},r.deepExtend=function t(e,r){if(Array.isArray(r))throw new TypeError("Arrays are not supported by deepExtend");for(var n in r)if(r.hasOwnProperty(n))if(r[n]&&r[n].constructor===Object)void 0===e[n]&&(e[n]={}),e[n].constructor===Object?t(e[n],r[n]):e[n]=r[n];else{if(Array.isArray(r[n]))throw new TypeError("Arrays are not supported by deepExtend");e[n]=r[n]}return e},r.deepEqual=function(e,n){var t,i,o;if(Array.isArray(e)){if(!Array.isArray(n))return!1;if(e.length!=n.length)return!1;for(i=0,o=e.length;o>i;i++)if(!r.deepEqual(e[i],n[i]))return!1;return!0}if(e instanceof Object){if(Array.isArray(n)||!(n instanceof Object))return!1;for(t in e)if(!r.deepEqual(e[t],n[t]))return!1;for(t in n)if(!r.deepEqual(e[t],n[t]))return!1;return!0}return typeof e==typeof n&&e==n}},function(e,r){"use strict";r.isNumber=function(e){return e instanceof Number||"number"==typeof e},r.isInteger=function(e){return e==Math.round(e)},r.sign=function(e){return e>0?1:0>e?-1:0},r.format=function(e,n){if("function"==typeof n)return n(e);if(1/0===e)return"Infinity";if(e===-1/0)return"-Infinity";if(isNaN(e))return"NaN";var t="auto",i=void 0;switch(n&&(n.notation&&(t=n.notation),r.isNumber(n)?i=n:n.precision&&(i=n.precision)),t){case"fixed":return r.toFixed(e,i);case"exponential":return r.toExponential(e,i);case"auto":var o=.001,a=1e5;if(n&&n.exponential&&(void 0!==n.exponential.lower&&(o=n.exponential.lower),void 0!==n.exponential.upper&&(a=n.exponential.upper)),0===e)return"0";var s,u=Math.abs(e);if(u>=o&&a>u){var f=i?e.toPrecision(Math.min(i,21)):e.toPrecision();s=parseFloat(f)+""}else s=r.toExponential(e,i);return s.replace(/((\.\d*?)(0+))($|e)/,function(){var e=arguments[2],r=arguments[4];return"."!==e?e+r:r});default:throw new Error('Unknown notation "'+t+'". Choose "auto", "exponential", or "fixed".')}},r.toExponential=function(e,r){return void 0!==r?e.toExponential(Math.min(r-1,20)):e.toExponential()},r.toFixed=function(e,r){return e.toFixed(Math.min(r,20))},r.digits=function(e){return e.toExponential().replace(/e.*$/,"").replace(/^0\.?0*|\./,"").length},r.DBL_EPSILON=Number.EPSILON||2.220446049250313e-16,r.nearlyEqual=function(e,n,t){if(null==t)return e==n;if(e==n)return!0;if(isNaN(e)||isNaN(n))return!1;if(isFinite(e)&&isFinite(n)){var i=Math.abs(e-n);return i<r.DBL_EPSILON?!0:i<=Math.max(Math.abs(e),Math.abs(n))*t}return!1}},function(e,r,n){"use strict";r.ArgumentsError=n(138),r.DimensionError=n(139),r.IndexError=n(140),r.UnsupportedTypeError=n(141)},function(e,r,n){"use strict";function t(e,r){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");switch(arguments.length){case 0:this.re=0,this.im=0;break;case 1:var n=arguments[0];if("object"==typeof n){if("re"in n&&"im"in n){var i=new t(n.re,n.im);this.re=i.re,this.im=i.im;break}if("r"in n&&"phi"in n){var i=t.fromPolar(n.r,n.phi);this.re=i.re,this.im=i.im;break}}throw new SyntaxError("Object with the re and im or r and phi properties expected.");case 2:if(!h(e)||!h(r))throw new TypeError("Two numbers expected in Complex constructor");this.re=e,this.im=r;break;default:throw new SyntaxError("One, two or three arguments expected in Complex constructor")}}function i(){for(;" "==w||"	"==w;)s()}function o(e){return e>="0"&&"9">=e||"."==e}function a(e){return e>="0"&&"9">=e}function s(){y++,w=x.charAt(y)}function u(e){y=e,w=x.charAt(y)}function f(){var e,r="";if(e=y,"+"==w?s():"-"==w&&(r+=w,s()),!o(w))return u(e),null;if("."==w){if(r+=w,s(),!a(w))return u(e),null}else{for(;a(w);)r+=w,s();"."==w&&(r+=w,s())}for(;a(w);)r+=w,s();if("E"==w||"e"==w){if(r+=w,s(),("+"==w||"-"==w)&&(r+=w,s()),!a(w))return u(e),null;for(;a(w);)r+=w,s()}return r}function c(){var e=x.charAt(y+1);if("I"==w||"i"==w)return s(),"1";if(!("+"!=w&&"-"!=w||"I"!=e&&"i"!=e)){var r="+"==w?"1":"-1";return s(),s(),r}return null}var l=n(143),p=n(10),m=l.number,h=l.number.isNumber,g=p.isUnit,d=l.string.isString;t.isComplex=function(e){return e instanceof t};var x,y,w;t.parse=function(e){if(x=e,y=-1,w="",!d(x))return null;s(),i();var r=f();if(r){if("I"==w||"i"==w)return s(),i(),w?null:new t(0,Number(r));i();var n=w;if("+"!=n&&"-"!=n)return i(),w?null:new t(Number(r),0);s(),i();var o=f();if(o){if("I"!=w&&"i"!=w)return null;s()}else if(o=c(),!o)return null;return"-"==n&&(o="-"==o[0]?"+"+o.substring(1):"-"+o),s(),i(),w?null:new t(Number(r),Number(o))}return(r=c())?(i(),w?null:new t(0,Number(r))):null},t.fromPolar=function(){switch(arguments.length){case 1:var e=arguments[0];if("object"==typeof e)return t.fromPolar(e.r,e.phi);throw new TypeError("Input has to be an object with r and phi keys.");case 2:var r=arguments[0],n=arguments[1];if(h(r)){if(g(n)&&n.hasBase(p.BASE_UNITS.ANGLE)&&(n=n.toNumber("rad")),h(n))return new t(r*Math.cos(n),r*Math.sin(n));throw new TypeError("Phi is not a number nor an angle unit.")}throw new TypeError("Radius r is not a number.");default:throw new SyntaxError("Wrong number of arguments in function fromPolar")}},t.prototype.toPolar=function(){return{r:Math.sqrt(this.re*this.re+this.im*this.im),phi:Math.atan2(this.im,this.re)}},t.prototype.clone=function(){return new t(this.re,this.im)},t.prototype.equals=function(e){return this.re===e.re&&this.im===e.im},t.prototype.format=function(e){var r="",n=m.format(this.re,e),t=m.format(this.im,e);return r=0==this.im?n:0==this.re?1==this.im?"i":-1==this.im?"-i":t+"i":this.im>0?1==this.im?n+" + i":n+" + "+t+"i":-1==this.im?n+" - i":n+" - "+t.substring(1)+"i"},t.prototype.toString=function(){return this.format()},t.prototype.valueOf=t.prototype.toString,e.exports=t},function(e,r,n){"use strict";function t(e,r,n){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(null!=e&&!o.isNumber(e))throw new TypeError("Parameter start must be a number");if(null!=r&&!o.isNumber(r))throw new TypeError("Parameter end must be a number");if(null!=n&&!o.isNumber(n))throw new TypeError("Parameter step must be a number");this.start=null!=e?parseFloat(e):0,this.end=null!=r?parseFloat(r):0,this.step=null!=n?parseFloat(n):1}{var i=n(143),o=i.number,a=i.string;i.array}t.parse=function(e){if(!a.isString(e))return null;var r=e.split(":"),n=r.map(function(e){return parseFloat(e)}),i=n.some(function(e){return isNaN(e)});if(i)return null;switch(n.length){case 2:return new t(n[0],n[1]);case 3:return new t(n[0],n[2],n[1]);default:return null}},t.prototype.clone=function(){return new t(this.start,this.end,this.step)},t.isRange=function(e){return e instanceof t},t.prototype.size=function(){var e=0,r=this.start,n=this.step,t=this.end,i=t-r;return o.sign(n)==o.sign(i)?e=Math.ceil(i/n):0==i&&(e=0),isNaN(e)&&(e=0),[e]},t.prototype.min=function(){var e=this.size()[0];return e>0?this.step>0?this.start:this.start+(e-1)*this.step:void 0},t.prototype.max=function(){var e=this.size()[0];return e>0?this.step>0?this.start+(e-1)*this.step:this.start:void 0},t.prototype.forEach=function(e){var r=this.start,n=this.step,t=this.end,i=0;if(n>0)for(;t>r;)e(r,i,this),r+=n,i++;else if(0>n)for(;r>t;)e(r,i,this),r+=n,i++},t.prototype.map=function(e){var r=[];return this.forEach(function(n,t,i){r[t]=e(n,t,i)}),r},t.prototype.toArray=function(){var e=[];return this.forEach(function(r,n){e[n]=r}),e},t.prototype.valueOf=function(){return this.toArray()},t.prototype.format=function(e){var r=o.format(this.start,e);return 1!=this.step&&(r+=":"+o.format(this.step,e)),r+=":"+o.format(this.end,e)},t.prototype.toString=function(){return this.format()},e.exports=t},function(e,r,n){"use strict";function t(){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");this._ranges=[],this._isScalar=!0;for(var e=0,r=arguments.length;r>e;e++){var n=arguments[e];if(n instanceof a)this._ranges.push(n),this._isScalar=!1;else if(c(n))this._ranges.push(i(n)),this._isScalar=!1;else if(u(n))this._ranges.push(i([n,n+1]));else{var o=n.valueOf();if(!c(o))throw new TypeError("Ranges must be an Array, Number, or Range");this._ranges.push(i(o)),this._isScalar=!1}}}function i(e){for(var r=e.length,n=0;r>n;n++)if(!u(e[n])||!f(e[n]))throw new TypeError("Index parameters must be integer numbers");switch(e.length){case 2:return new a(e[0],e[1]);case 3:return new a(e[0],e[1],e[2]);default:throw new SyntaxError("Wrong number of arguments in Index (2 or 3 expected)")}}var o=n(143),a=n(7),s=o.number,u=s.isNumber,f=s.isInteger,c=Array.isArray;t.prototype.clone=function(){var e=new t;return e._ranges=o.object.clone(this._ranges),e._isScalar=this._isScalar,e},t.isIndex=function(e){return e instanceof t},t.create=function(e){var r=new t;return t.apply(r,e),r},t.prototype.size=function(){for(var e=[],r=0,n=this._ranges.length;n>r;r++){var t=this._ranges[r];e[r]=t.size()[0]}return e},t.prototype.max=function(){for(var e=[],r=0,n=this._ranges.length;n>r;r++){var t=this._ranges[r];e[r]=t.max()}return e},t.prototype.min=function(){for(var e=[],r=0,n=this._ranges.length;n>r;r++){var t=this._ranges[r];e[r]=t.min()}return e},t.prototype.forEach=function(e){for(var r=0,n=this._ranges.length;n>r;r++)e(this._ranges[r],r,this)},t.prototype.range=function(e){return this._ranges[e]||null},t.prototype.isScalar=function(){return this._isScalar},t.prototype.toArray=function(){for(var e=[],r=0,n=this._ranges.length;n>r;r++){var t=this._ranges[r],i=[],o=t.start,a=t.end,s=t.step;if(s>0)for(;a>o;)i.push(o),o+=s;else if(0>s)for(;o>a;)i.push(o),o+=s;e.push(i)}return e},t.prototype.valueOf=t.prototype.toArray,t.prototype.toString=function(){for(var e=[],r=0,n=this._ranges.length;n>r;r++){var t=this._ranges[r],i=s.format(t.start);1!=t.step&&(i+=":"+s.format(t.step)),i+=":"+s.format(t.end),e.push(i)}return"["+e.join(", ")+"]"},e.exports=t},function(e,r,n){"use strict";function t(e){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(e instanceof t)this._data=e.clone()._data;else if(d(e))this._data=f(e);else{if(null!=e)throw new TypeError("Unsupported type of data ("+c.types.type(e)+")");this._data=[]}this._size=h.size(this._data)}function i(e,r){if(!(r instanceof p))throw new TypeError("Invalid index");var n=r.isScalar();if(n)return e.get(r.min());var i=r.size();if(i.length!=e._size.length)throw new l(i.length,e._size.length);for(var a=r.min(),s=r.max(),u=0,f=e._size.length;f>u;u++)x(a[u],e._size[u]),x(s[u],e._size[u]);return new t(o(e._data,r,i.length,0))}function o(e,r,n,t){var i=t==n-1,a=r.range(t);return a.map(i?function(r){return e[r]}:function(i){var a=e[i];return o(a,r,n,t+1)})}function a(e,r,n,i){if(!(r instanceof p))throw new TypeError("Invalid index");var o,a=r.size(),f=r.isScalar();if(n instanceof t?(o=n.size(),n=n.valueOf()):o=h.size(n),f){if(0!=o.length)throw new TypeError("Scalar expected");e.set(r.min(),n,i)}else{if(a.length<e._size.length)throw new l(a.length,e._size.length,"<");if(o.length<a.length){for(var c=0,m=0;1===a[c]&&1===o[c];)c++;for(;1===a[c];)m++,c++;n=h.unsqueeze(n,a.length,m,o)}if(!g.deepEqual(a,o))throw new l(a,o,">");var d=r.max().map(function(e){return e+1});u(e,d,i);var x=a.length,y=0;s(e._data,r,n,x,y)}return e}function s(e,r,n,t,i){var o=i==t-1,a=r.range(i);a.forEach(o?function(r,t){x(r),e[r]=n[t]}:function(o,a){x(o),s(e[o],r,n[a],t,i+1)})}function u(e,r,n){for(var t=g.clone(e._size),i=!1;t.length<r.length;)t.push(0),i=!0;for(var o=0,a=r.length;a>o;o++)r[o]>t[o]&&(t[o]=r[o],i=!0);i&&e.resize(t,n)}function f(e){for(var r=0,n=e.length;n>r;r++){var i=e[r];d(i)?e[r]=f(i):i instanceof t&&(e[r]=f(i._data))}return e}var c=n(143),l=n(139),p=n(8),m=(c.number,c.string),h=c.array,g=c.object,d=Array.isArray,x=h.validateIndex;t.isMatrix=function(e){return e instanceof t},t.prototype.subset=function(e,r,n){switch(arguments.length){case 1:return i(this,e);case 2:case 3:return a(this,e,r,n);default:throw new SyntaxError("Wrong number of arguments")}},t.prototype.get=function(e){if(!d(e))throw new TypeError("Array expected");if(e.length!=this._size.length)throw new l(e.length,this._size.length);for(var r=this._data,n=0,t=e.length;t>n;n++){var i=e[n];x(i,r.length),r=r[i]}return g.clone(r)},t.prototype.set=function(e,r,n){var t,i;if(!d(e))throw new Error("Array expected");if(e.length<this._size.length)throw new l(e.length,this._size.length,"<");var o=e.map(function(e){return e+1});u(this,o,n);var a=this._data;for(t=0,i=e.length-1;i>t;t++){var s=e[t];x(s,a.length),a=a[s]}return s=e[e.length-1],x(s,a.length),a[s]=r,this},t.prototype.resize=function(e,r){return this._size=g.clone(e),this._data=h.resize(this._data,this._size,r),this},t.prototype.clone=function(){var e=new t;return e._data=g.clone(this._data),e._size=g.clone(this._size),e},t.prototype.size=function(){return this._size},t.prototype.map=function(e){var r=this,n=new t,i=[],o=function(n,t){return d(n)?n.map(function(e,r){return i[t]=r,o(e,t+1)}):e(n,i,r)};return n._data=o(this._data,0),n._size=g.clone(this._size),n},t.prototype.forEach=function(e){var r=this,n=[],t=function(i,o){d(i)?i.forEach(function(e,r){n[o]=r,t(e,o+1)}):e(i,n,r)};t(this._data,0)},t.prototype.toArray=function(){return g.clone(this._data)},t.prototype.valueOf=function(){return this._data},t.prototype.format=function(e){return m.format(this._data,e)},t.prototype.toString=function(){return m.format(this._data)},e.exports=t},function(e,r,n){"use strict";function t(e,r){if(!(this instanceof t))throw new Error("Constructor must be called with the new operator");if(void 0!=e&&!y(e))throw new TypeError("First parameter in Unit constructor must be a number");if(void 0!=r&&(!w(r)||""==r))throw new TypeError("Second parameter in Unit constructor must be a string");if(void 0!=r){var n=l(r);if(!n)throw new SyntaxError('Unknown unit "'+r+'"');this.unit=n.unit,this.prefix=n.prefix}else this.unit=M,this.prefix=b;this.value=void 0!=e?this._normalize(e):null,this.fixPrefix=!1}function i(){for(;" "==h||"	"==h;)s()}function o(e){return e>="0"&&"9">=e||"."==e}function a(e){return e>="0"&&"9">=e}function s(){m++,h=p.charAt(m)}function u(e){m=e,h=p.charAt(m)}function f(){var e,r="";if(e=m,"+"==h?s():"-"==h&&(r+=h,s()),!o(h))return u(e),null;if("."==h){if(r+=h,s(),!a(h))return u(e),null}else{for(;a(h);)r+=h,s();"."==h&&(r+=h,s())}for(;a(h);)r+=h,s();if("E"==h||"e"==h){if(r+=h,s(),("+"==h||"-"==h)&&(r+=h,s()),!a(h))return u(e),null;for(;a(h);)r+=h,s()}return r}function c(){var e="";for(i();h&&" "!=h&&"	"!=h;)e+=h,s();return e||null}function l(e){for(var r in A)if(A.hasOwnProperty(r)&&x.endsWith(e,r)){var n=A[r],t=e.length-r.length,i=e.substring(0,t),o=n.prefixes[i];if(void 0!==o)return{unit:n,prefix:o}}return null}var p,m,h,g=n(143),d=g.number,x=g.string,y=g.number.isNumber,w=g.string.isString;t.parse=function(e){if(p=e,m=-1,h="",!w(p))return null;s(),i();var r,n=f();if(n){if(r=c(),s(),i(),h)return null;if(n&&r)try{return new t(Number(n),r)}catch(o){}}else{if(r=c(),s(),i(),h)return null;if(r)try{return new t(null,r)}catch(o){}}return null},t.isUnit=function(e){return e instanceof t},t.prototype.clone=function(){var e=new t;for(var r in this)this.hasOwnProperty(r)&&(e[r]=this[r]);return e},t.prototype._normalize=function(e){return(e+this.unit.offset)*this.unit.value*this.prefix.value},t.prototype._unnormalize=function(e,r){return void 0==r?e/this.unit.value/this.prefix.value-this.unit.offset:e/this.unit.value/r-this.unit.offset},t.isValuelessUnit=function(e){return null!=l(e)},t.prototype.hasBase=function(e){return this.unit.base===e},t.prototype.equalBase=function(e){return this.unit.base===e.unit.base},t.prototype.equals=function(e){return this.equalBase(e)&&this.value==e.value},t.prototype.to=function(e){var r;if(w(e)){if(r=new t(null,e),!this.equalBase(r))throw new Error("Units do not match");return r.value=this.value,r.fixPrefix=!0,r}if(e instanceof t){if(!this.equalBase(e))throw new Error("Units do not match");if(null!==e.value)throw new Error("Cannot convert to a unit with a value");return r=e.clone(),r.value=this.value,r.fixPrefix=!0,r}throw new Error("String or Unit expected as parameter")},t.prototype.toNumber=function(e){var r=this.to(e);return r._unnormalize(r.value,r.prefix.value)},t.prototype.toString=function(){return this.format()},t.prototype.valueOf=t.prototype.toString,t.prototype.format=function(e){var r,n;if(null===this.value||this.fixPrefix)r=this._unnormalize(this.value),n=null!==this.value?d.format(r,e)+" ":"",n+=this.prefix.name+this.unit.name;else{var t=this._bestPrefix();r=this._unnormalize(this.value,t.value),n=d.format(r,e)+" ",n+=t.name+this.unit.name}return n},t.prototype._bestPrefix=function(){var e=Math.abs(this.value/this.unit.value),r=b,n=Math.abs(Math.log(e/r.value)/Math.LN10-1.2),t=this.unit.prefixes;for(var i in t)if(t.hasOwnProperty(i)){var o=t[i];if(o.scientific){var a=Math.abs(Math.log(e/o.value)/Math.LN10-1.2);n>a&&(r=o,n=a)}}return r};var v={NONE:{"":{name:"",value:1,scientific:!0}},SHORT:{"":{name:"",value:1,scientific:!0},da:{name:"da",value:10,scientific:!1},h:{name:"h",value:100,scientific:!1},k:{name:"k",value:1e3,scientific:!0},M:{name:"M",value:1e6,scientific:!0},G:{name:"G",value:1e9,scientific:!0},T:{name:"T",value:1e12,scientific:!0},P:{name:"P",value:1e15,scientific:!0},E:{name:"E",value:1e18,scientific:!0},Z:{name:"Z",value:1e21,scientific:!0},Y:{name:"Y",value:1e24,scientific:!0},d:{name:"d",value:.1,scientific:!1},c:{name:"c",value:.01,scientific:!1},m:{name:"m",value:.001,scientific:!0},u:{name:"u",value:1e-6,scientific:!0},n:{name:"n",value:1e-9,scientific:!0},p:{name:"p",value:1e-12,scientific:!0},f:{name:"f",value:1e-15,scientific:!0},a:{name:"a",value:1e-18,scientific:!0},z:{name:"z",value:1e-21,scientific:!0},y:{name:"y",value:1e-24,scientific:!0}},LONG:{"":{name:"",value:1,scientific:!0},deca:{name:"deca",value:10,scientific:!1},hecto:{name:"hecto",value:100,scientific:!1},kilo:{name:"kilo",value:1e3,scientific:!0},mega:{name:"mega",value:1e6,scientific:!0},giga:{name:"giga",value:1e9,scientific:!0},tera:{name:"tera",value:1e12,scientific:!0},peta:{name:"peta",value:1e15,scientific:!0},exa:{name:"exa",value:1e18,scientific:!0},zetta:{name:"zetta",value:1e21,scientific:!0},yotta:{name:"yotta",value:1e24,scientific:!0},deci:{name:"deci",value:.1,scientific:!1},centi:{name:"centi",value:.01,scientific:!1},milli:{name:"milli",value:.001,scientific:!0},micro:{name:"micro",value:1e-6,scientific:!0},nano:{name:"nano",value:1e-9,scientific:!0},pico:{name:"pico",value:1e-12,scientific:!0},femto:{name:"femto",value:1e-15,scientific:!0},atto:{name:"atto",value:1e-18,scientific:!0},zepto:{name:"zepto",value:1e-21,scientific:!0},yocto:{name:"yocto",value:1e-24,scientific:!0}},SQUARED:{"":{name:"",value:1,scientific:!0},da:{name:"da",value:100,scientific:!1},h:{name:"h",value:1e4,scientific:!1},k:{name:"k",value:1e6,scientific:!0},M:{name:"M",value:1e12,scientific:!0},G:{name:"G",value:1e18,scientific:!0},T:{name:"T",value:1e24,scientific:!0},P:{name:"P",value:1e30,scientific:!0},E:{name:"E",value:1e36,scientific:!0},Z:{name:"Z",value:1e42,scientific:!0},Y:{name:"Y",value:1e48,scientific:!0},d:{name:"d",value:.01,scientific:!1},c:{name:"c",value:1e-4,scientific:!1},m:{name:"m",value:1e-6,scientific:!0},u:{name:"u",value:1e-12,scientific:!0},n:{name:"n",value:1e-18,scientific:!0},p:{name:"p",value:1e-24,scientific:!0},f:{name:"f",value:1e-30,scientific:!0},a:{name:"a",value:1e-36,scientific:!0},z:{name:"z",value:1e-42,scientific:!0},y:{name:"y",value:1e-42,scientific:!0}},CUBIC:{"":{name:"",value:1,scientific:!0},da:{name:"da",value:1e3,scientific:!1},h:{name:"h",value:1e6,scientific:!1},k:{name:"k",value:1e9,scientific:!0},M:{name:"M",value:1e18,scientific:!0},G:{name:"G",value:1e27,scientific:!0},T:{name:"T",value:1e36,scientific:!0},P:{name:"P",value:1e45,scientific:!0},E:{name:"E",value:1e54,scientific:!0},Z:{name:"Z",value:1e63,scientific:!0},Y:{name:"Y",value:1e72,scientific:!0},d:{name:"d",value:.001,scientific:!1},c:{name:"c",value:1e-6,scientific:!1},m:{name:"m",value:1e-9,scientific:!0},u:{name:"u",value:1e-18,scientific:!0},n:{name:"n",value:1e-27,scientific:!0},p:{name:"p",value:1e-36,scientific:!0},f:{name:"f",value:1e-45,scientific:!0},a:{name:"a",value:1e-54,scientific:!0},z:{name:"z",value:1e-63,scientific:!0},y:{name:"y",value:1e-72,scientific:!0}},BINARY_SHORT:{"":{name:"",value:1,scientific:!0},k:{name:"k",value:1024,scientific:!0},M:{name:"M",value:Math.pow(1024,2),scientific:!0},G:{name:"G",value:Math.pow(1024,3),scientific:!0},T:{name:"T",value:Math.pow(1024,4),scientific:!0},P:{name:"P",value:Math.pow(1024,5),scientific:!0},E:{name:"E",value:Math.pow(1024,6),scientific:!0},Z:{name:"Z",value:Math.pow(1024,7),scientific:!0},Y:{name:"Y",value:Math.pow(1024,8),scientific:!0},Ki:{name:"Ki",value:1024,scientific:!0},Mi:{name:"Mi",value:Math.pow(1024,2),scientific:!0},Gi:{name:"Gi",value:Math.pow(1024,3),scientific:!0},Ti:{name:"Ti",value:Math.pow(1024,4),scientific:!0},Pi:{name:"Pi",value:Math.pow(1024,5),scientific:!0},Ei:{name:"Ei",value:Math.pow(1024,6),scientific:!0},Zi:{name:"Zi",value:Math.pow(1024,7),scientific:!0},Yi:{name:"Yi",value:Math.pow(1024,8),scientific:!0}},BINARY_LONG:{"":{name:"",value:1,scientific:!0},kilo:{name:"kilo",value:1024,scientific:!0},mega:{name:"mega",value:Math.pow(1024,2),scientific:!0},giga:{name:"giga",value:Math.pow(1024,3),scientific:!0},tera:{name:"tera",value:Math.pow(1024,4),scientific:!0},peta:{name:"peta",value:Math.pow(1024,5),scientific:!0},exa:{name:"exa",value:Math.pow(1024,6),scientific:!0},zetta:{name:"zetta",value:Math.pow(1024,7),scientific:!0},yotta:{name:"yotta",value:Math.pow(1024,8),scientific:!0},kibi:{name:"kibi",value:1024,scientific:!0},mebi:{name:"mebi",value:Math.pow(1024,2),scientific:!0},gibi:{name:"gibi",value:Math.pow(1024,3),scientific:!0},tebi:{name:"tebi",value:Math.pow(1024,4),scientific:!0},pebi:{name:"pebi",value:Math.pow(1024,5),scientific:!0},exi:{name:"exi",value:Math.pow(1024,6),scientific:!0},zebi:{name:"zebi",value:Math.pow(1024,7),scientific:!0},yobi:{name:"yobi",value:Math.pow(1024,8),scientific:!0}}},b={name:"",value:1,scientific:!0},E={NONE:{},LENGTH:{},MASS:{},TIME:{},CURRENT:{},TEMPERATURE:{},LUMINOUS_INTENSITY:{},AMOUNT_OF_SUBSTANCE:{},FORCE:{},SURFACE:{},VOLUME:{},ANGLE:{},BIT:{}},N={},M={name:"",base:N,value:1,offset:0},A={meter:{name:"meter",base:E.LENGTH,prefixes:v.LONG,value:1,offset:0},inch:{name:"inch",base:E.LENGTH,prefixes:v.NONE,value:.0254,offset:0},foot:{name:"foot",base:E.LENGTH,prefixes:v.NONE,value:.3048,offset:0},yard:{name:"yard",base:E.LENGTH,prefixes:v.NONE,value:.9144,offset:0},mile:{name:"mile",base:E.LENGTH,prefixes:v.NONE,value:1609.344,offset:0},link:{name:"link",base:E.LENGTH,prefixes:v.NONE,value:.201168,offset:0},rod:{name:"rod",base:E.LENGTH,prefixes:v.NONE,value:5.02921,offset:0},chain:{name:"chain",base:E.LENGTH,prefixes:v.NONE,value:20.1168,offset:0},angstrom:{name:"angstrom",base:E.LENGTH,prefixes:v.NONE,value:1e-10,offset:0},m:{name:"m",base:E.LENGTH,prefixes:v.SHORT,value:1,offset:0},"in":{name:"in",base:E.LENGTH,prefixes:v.NONE,value:.0254,offset:0},ft:{name:"ft",base:E.LENGTH,prefixes:v.NONE,value:.3048,offset:0},yd:{name:"yd",base:E.LENGTH,prefixes:v.NONE,value:.9144,offset:0},mi:{name:"mi",base:E.LENGTH,prefixes:v.NONE,value:1609.344,offset:0},li:{name:"li",base:E.LENGTH,prefixes:v.NONE,value:.201168,offset:0},rd:{name:"rd",base:E.LENGTH,prefixes:v.NONE,value:5.02921,offset:0},ch:{name:"ch",base:E.LENGTH,prefixes:v.NONE,value:20.1168,offset:0},mil:{name:"mil",base:E.LENGTH,prefixes:v.NONE,value:254e-7,offset:0},m2:{name:"m2",base:E.SURFACE,prefixes:v.SQUARED,value:1,offset:0},sqin:{name:"sqin",base:E.SURFACE,prefixes:v.NONE,value:64516e-8,offset:0},sqft:{name:"sqft",base:E.SURFACE,prefixes:v.NONE,value:.09290304,offset:0},sqyd:{name:"sqyd",base:E.SURFACE,prefixes:v.NONE,value:.83612736,offset:0},sqmi:{name:"sqmi",base:E.SURFACE,prefixes:v.NONE,value:2589988.110336,offset:0},sqrd:{name:"sqrd",base:E.SURFACE,prefixes:v.NONE,value:25.29295,offset:0},sqch:{name:"sqch",base:E.SURFACE,prefixes:v.NONE,value:404.6873,offset:0},sqmil:{name:"sqmil",base:E.SURFACE,prefixes:v.NONE,value:6.4516e-10,offset:0},m3:{name:"m3",base:E.VOLUME,prefixes:v.CUBIC,value:1,offset:0},L:{name:"L",base:E.VOLUME,prefixes:v.SHORT,value:.001,offset:0},l:{name:"l",base:E.VOLUME,prefixes:v.SHORT,value:.001,offset:0},litre:{name:"litre",base:E.VOLUME,prefixes:v.LONG,value:.001,offset:0},cuin:{name:"cuin",base:E.VOLUME,prefixes:v.NONE,value:16387064e-12,offset:0},cuft:{name:"cuft",base:E.VOLUME,prefixes:v.NONE,value:.028316846592,offset:0},cuyd:{name:"cuyd",base:E.VOLUME,prefixes:v.NONE,value:.764554857984,offset:0},teaspoon:{name:"teaspoon",base:E.VOLUME,prefixes:v.NONE,value:5e-6,offset:0},tablespoon:{name:"tablespoon",base:E.VOLUME,prefixes:v.NONE,value:15e-6,offset:0},drop:{name:"drop",base:E.VOLUME,prefixes:v.NONE,value:5e-8,offset:0},gtt:{name:"gtt",base:E.VOLUME,prefixes:v.NONE,value:5e-8,offset:0},minim:{name:"minim",base:E.VOLUME,prefixes:v.NONE,value:6.161152e-8,offset:0},fluiddram:{name:"fluiddram",base:E.VOLUME,prefixes:v.NONE,value:36966911e-13,offset:0},fluidounce:{name:"fluidounce",base:E.VOLUME,prefixes:v.NONE,value:2957353e-11,offset:0},gill:{name:"gill",base:E.VOLUME,prefixes:v.NONE,value:.0001182941,offset:0},cc:{name:"cc",base:E.VOLUME,prefixes:v.NONE,value:1e-6,offset:0},cup:{name:"cup",base:E.VOLUME,prefixes:v.NONE,value:.0002365882,offset:0},pint:{name:"pint",base:E.VOLUME,prefixes:v.NONE,value:.0004731765,offset:0},quart:{name:"quart",base:E.VOLUME,prefixes:v.NONE,value:.0009463529,offset:0},gallon:{name:"gallon",base:E.VOLUME,prefixes:v.NONE,value:.003785412,offset:0},beerbarrel:{name:"beerbarrel",base:E.VOLUME,prefixes:v.NONE,value:.1173478,offset:0},oilbarrel:{name:"oilbarrel",base:E.VOLUME,prefixes:v.NONE,value:.1589873,offset:0},hogshead:{name:"hogshead",base:E.VOLUME,prefixes:v.NONE,value:.238481,offset:0},fldr:{name:"fldr",base:E.VOLUME,prefixes:v.NONE,value:36966911e-13,offset:0},floz:{name:"floz",base:E.VOLUME,prefixes:v.NONE,value:2957353e-11,offset:0},gi:{name:"gi",base:E.VOLUME,prefixes:v.NONE,value:.0001182941,offset:0},cp:{name:"cp",base:E.VOLUME,prefixes:v.NONE,value:.0002365882,offset:0},pt:{name:"pt",base:E.VOLUME,prefixes:v.NONE,value:.0004731765,offset:0},qt:{name:"qt",base:E.VOLUME,prefixes:v.NONE,value:.0009463529,offset:0},gal:{name:"gal",base:E.VOLUME,prefixes:v.NONE,value:.003785412,offset:0},bbl:{name:"bbl",base:E.VOLUME,prefixes:v.NONE,value:.1173478,offset:0},obl:{name:"obl",base:E.VOLUME,prefixes:v.NONE,value:.1589873,offset:0},g:{name:"g",base:E.MASS,prefixes:v.SHORT,value:.001,offset:0},gram:{name:"gram",base:E.MASS,prefixes:v.LONG,value:.001,offset:0},ton:{name:"ton",base:E.MASS,prefixes:v.SHORT,value:907.18474,offset:0},tonne:{name:"tonne",base:E.MASS,prefixes:v.SHORT,value:1e3,offset:0},grain:{name:"grain",base:E.MASS,prefixes:v.NONE,value:6479891e-11,offset:0},dram:{name:"dram",base:E.MASS,prefixes:v.NONE,value:.0017718451953125,offset:0},ounce:{name:"ounce",base:E.MASS,prefixes:v.NONE,value:.028349523125,offset:0},poundmass:{name:"poundmass",base:E.MASS,prefixes:v.NONE,value:.45359237,offset:0},hundredweight:{name:"hundredweight",base:E.MASS,prefixes:v.NONE,value:45.359237,offset:0},stick:{name:"stick",base:E.MASS,prefixes:v.NONE,value:.115,offset:0},gr:{name:"gr",base:E.MASS,prefixes:v.NONE,value:6479891e-11,offset:0},dr:{name:"dr",base:E.MASS,prefixes:v.NONE,value:.0017718451953125,offset:0},oz:{name:"oz",base:E.MASS,prefixes:v.NONE,value:.028349523125,offset:0},lbm:{name:"lbm",base:E.MASS,prefixes:v.NONE,value:.45359237,offset:0},cwt:{name:"cwt",base:E.MASS,prefixes:v.NONE,value:45.359237,offset:0},s:{name:"s",base:E.TIME,prefixes:v.SHORT,value:1,offset:0},min:{name:"min",base:E.TIME,prefixes:v.NONE,value:60,offset:0},h:{name:"h",base:E.TIME,prefixes:v.NONE,value:3600,offset:0},second:{name:"second",base:E.TIME,prefixes:v.LONG,value:1,offset:0},sec:{name:"sec",base:E.TIME,prefixes:v.LONG,value:1,offset:0},minute:{name:"minute",base:E.TIME,prefixes:v.NONE,value:60,offset:0},hour:{name:"hour",base:E.TIME,prefixes:v.NONE,value:3600,offset:0},day:{name:"day",base:E.TIME,prefixes:v.NONE,value:86400,offset:0},rad:{name:"rad",base:E.ANGLE,prefixes:v.NONE,value:1,offset:0},deg:{name:"deg",base:E.ANGLE,prefixes:v.NONE,value:.017453292519943295,offset:0},grad:{name:"grad",base:E.ANGLE,prefixes:v.NONE,value:.015707963267948967,offset:0},cycle:{name:"cycle",base:E.ANGLE,prefixes:v.NONE,value:6.283185307179586,offset:0},A:{name:"A",base:E.CURRENT,prefixes:v.SHORT,value:1,offset:0},ampere:{name:"ampere",base:E.CURRENT,prefixes:v.LONG,value:1,offset:0},K:{name:"K",base:E.TEMPERATURE,prefixes:v.NONE,value:1,offset:0},degC:{name:"degC",base:E.TEMPERATURE,prefixes:v.NONE,value:1,offset:273.15},degF:{name:"degF",base:E.TEMPERATURE,prefixes:v.NONE,value:1/1.8,offset:459.67},degR:{name:"degR",base:E.TEMPERATURE,prefixes:v.NONE,value:1/1.8,offset:0},kelvin:{name:"kelvin",base:E.TEMPERATURE,prefixes:v.NONE,value:1,offset:0},celsius:{name:"celsius",base:E.TEMPERATURE,prefixes:v.NONE,value:1,offset:273.15},fahrenheit:{name:"fahrenheit",base:E.TEMPERATURE,prefixes:v.NONE,value:1/1.8,offset:459.67},rankine:{name:"rankine",base:E.TEMPERATURE,prefixes:v.NONE,value:1/1.8,offset:0},mol:{name:"mol",base:E.AMOUNT_OF_SUBSTANCE,prefixes:v.NONE,value:1,offset:0},mole:{name:"mole",base:E.AMOUNT_OF_SUBSTANCE,prefixes:v.NONE,value:1,offset:0},cd:{name:"cd",base:E.LUMINOUS_INTENSITY,prefixes:v.NONE,value:1,offset:0},candela:{name:"candela",base:E.LUMINOUS_INTENSITY,prefixes:v.NONE,value:1,offset:0},N:{name:"N",base:E.FORCE,prefixes:v.SHORT,value:1,offset:0},newton:{name:"newton",base:E.FORCE,prefixes:v.LONG,value:1,offset:0},lbf:{name:"lbf",base:E.FORCE,prefixes:v.NONE,value:4.4482216152605,offset:0},poundforce:{name:"poundforce",base:E.FORCE,prefixes:v.NONE,value:4.4482216152605,offset:0},b:{name:"b",base:E.BIT,prefixes:v.BINARY_SHORT,value:1,offset:0},bits:{name:"bits",base:E.BIT,prefixes:v.BINARY_LONG,value:1,offset:0},B:{name:"B",base:E.BIT,prefixes:v.BINARY_SHORT,value:8,offset:0},bytes:{name:"bytes",base:E.BIT,prefixes:v.BINARY_LONG,value:8,offset:0}},T={meters:"meter",inches:"inch",feet:"foot",yards:"yard",miles:"mile",links:"link",rods:"rod",chains:"chain",angstroms:"angstrom",litres:"litre",teaspoons:"teaspoon",tablespoons:"tablespoon",minims:"minim",fluiddrams:"fluiddram",fluidounces:"fluidounce",gills:"gill",cups:"cup",pints:"pint",quarts:"quart",gallons:"gallon",beerbarrels:"beerbarrel",oilbarrels:"oilbarrel",hogsheads:"hogshead",gtts:"gtt",grams:"gram",tons:"ton",tonnes:"tonne",grains:"grain",drams:"dram",ounces:"ounce",poundmasses:"poundmass",hundredweights:"hundredweight",sticks:"stick",seconds:"second",minutes:"minute",hours:"hour",days:"day",radians:"rad",degrees:"deg",gradients:"grad",cycles:"cycle",amperes:"ampere",moles:"mole"};
for(var S in T)if(T.hasOwnProperty(S)){var O=A[T[S]],C=Object.create(O);C.name=S,A[S]=C}A.lt=A.l,A.liter=A.litre,A.liters=A.litres,A.lb=A.lbm,A.lbs=A.lbm,t.PREFIXES=v,t.BASE_UNITS=E,t.UNITS=A,e.exports=t},function(e,r,n){"use strict";function t(e,r){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");this.math=e,this.doc=r}var i=n(143),o=i.object,a=i.string;t.isHelp=function(e){return e instanceof t},t.prototype.toString=function(){var e=this.doc||{},r="\n";if(e.name&&(r+="Name: "+e.name+"\n\n"),e.category&&(r+="Category: "+e.category+"\n\n"),e.description&&(r+="Description:\n    "+e.description+"\n\n"),e.syntax&&(r+="Syntax:\n    "+e.syntax.join("\n    ")+"\n\n"),e.examples){var n=this.math.parser();r+="Examples:\n";for(var i=0;i<e.examples.length;i++){var o,s=e.examples[i];try{o=n.eval(s)}catch(u){o=u}r+="    "+s+"\n",!o||o instanceof t||(r+="        "+a.format(o)+"\n")}r+="\n"}return e.seealso&&(r+="See also: "+e.seealso.join(", ")+"\n"),r},t.prototype.toJSON=function(){return o.clone(this.doc)},t.prototype.valueOf=t.prototype.toString,e.exports=t},function(e){"use strict";function r(e){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");this.entries=e||[]}r.prototype.valueOf=function(){return this.entries},r.prototype.toString=function(){return"["+this.entries.join(", ")+"]"},e.exports=r},function(e,r,n){"use strict";function t(e,r,n){var o,a,s,u;if(0>=r){if(c(e[0])){for(u=i(e),a=[],o=0;o<u.length;o++)a[o]=t(u[o],r-1,n);return a}for(s=e[0],o=1;o<e.length;o++)s=n(s,e[o]);return s}for(a=[],o=0;o<e.length;o++)a[o]=t(e[o],r-1,n);return a}function i(e){var r,n,t=e.length,i=e[0].length,o=[];for(n=0;i>n;n++){var a=[];for(r=0;t>r;r++)a.push(e[r][n]);o.push(a)}return o}{var o=n(143),a=n(140),s=n(139),u=n(9),f=o.array,c=o.array.isArray;o.string.isString}r.argsToArray=function(e){if(0==e.length)return[];if(1==e.length){var r=e[0];return r instanceof u&&(r=r.valueOf()),c(r)||(r=[r]),r}return o.array.argsToArray(e)},r.isCollection=function(e){return c(e)||e instanceof u},r.deepMap=function l(e,r){return e&&"function"==typeof e.map?e.map(function(e){return l(e,r)}):r(e)},r.deepMap2=function p(e,r,n){var t,i,o;if(c(e))if(c(r)){if(e.length!=r.length)throw new s(e.length,r.length);for(t=[],i=e.length,o=0;i>o;o++)t[o]=p(e[o],r[o],n)}else{if(r instanceof u)return t=p(e,r.valueOf(),n),new u(t);for(t=[],i=e.length,o=0;i>o;o++)t[o]=p(e[o],r,n)}else{if(e instanceof u)return r instanceof u?(t=p(e.valueOf(),r.valueOf(),n),new u(t)):(t=p(e.valueOf(),r,n),new u(t));if(c(r))for(t=[],i=r.length,o=0;i>o;o++)t[o]=p(e,r[o],n);else{if(r instanceof u)return t=p(e,r.valueOf(),n),new u(t);t=n(e,r)}}return t},r.reduce=function(e,r,n){var i=c(e)?f.size(e):e.size();if(0>r)throw new a(r);if(r>=i.length)throw new a(r,i.length);return e instanceof u?new u(t(e.valueOf(),r,n)):t(e,r,n)},r.deepForEach=function m(e,r){e instanceof u&&(e=e.valueOf());for(var n=0,t=e.length;t>n;n++){var i=e[n];c(i)?m(i,r):r(i)}}},function(e,r,n){"use strict";function t(e,r){if(1!=arguments.length&&2!=arguments.length)throw new F("parse",arguments.length,1,2);if(sr=r&&r.nodes?r.nodes:{},D(e))return ur=e,h();if(G(e)||e instanceof V)return H.deepMap(e,function(e){if(!D(e))throw new TypeError("String expected");return ur=e,h()});throw new TypeError("String or matrix expected")}function i(){fr=0,cr=ur.charAt(0),mr=0}function o(){fr++,cr=ur.charAt(fr)}function a(){return ur.charAt(fr+1)}function s(){for(pr=ir.NULL,lr="";" "==cr||"	"==cr||"\n"==cr&&mr;)o();if("#"==cr)for(;"\n"!=cr&&""!=cr;)o();if(""==cr)return void(pr=ir.DELIMITER);if("\n"==cr&&!mr)return pr=ir.DELIMITER,lr=cr,void o();var e=cr+a();if(2==e.length&&or[e])return pr=ir.DELIMITER,lr=e,o(),void o();if(or[cr])return pr=ir.DELIMITER,lr=cr,void o();if(!p(cr)){if(l(cr)){for(;l(cr)||m(cr);)lr+=cr,o();return void(pr=ar[lr]?ir.DELIMITER:ir.SYMBOL)}for(pr=ir.UNKNOWN;""!=cr;)lr+=cr,o();throw P('Syntax error in part "'+lr+'"')}if(pr=ir.NUMBER,"."==cr)lr+=cr,o(),m(cr)||(pr=ir.UNKNOWN);else{for(;m(cr);)lr+=cr,o();"."==cr&&(lr+=cr,o())}for(;m(cr);)lr+=cr,o();if("E"==cr||"e"==cr)for(lr+=cr,o(),("+"==cr||"-"==cr)&&(lr+=cr,o()),m(cr)||(pr=ir.UNKNOWN);m(cr);)lr+=cr,o()}function u(){do s();while("\n"==lr)}function f(){mr++}function c(){mr--}function l(e){return e>="a"&&"z">=e||e>="A"&&"Z">=e||"_"==e}function p(e){return e>="0"&&"9">=e||"."==e}function m(e){return e>="0"&&"9">=e}function h(){i(),s();var e=g();if(""!=lr)throw pr==ir.DELIMITER?k("Unexpected operator "+lr):P('Unexpected part "'+lr+'"');return e}function g(){var e,r,n;if(""==lr)return new K("undefined","undefined");for("\n"!=lr&&";"!=lr&&(e=d());"\n"==lr||";"==lr;)r||(r=new W,e&&(n=";"!=lr,r.add(e,n))),s(),"\n"!=lr&&";"!=lr&&""!=lr&&(e=d(),n=";"!=lr,r.add(e,n));return r?r:e}function d(){if(pr==ir.SYMBOL&&"function"==lr)throw P('Deprecated keyword "function". Functions can now be assigned without it, like "f(x) = x^2".');return x()}function x(){var e,r,n,t,i=y();if("="==lr){if(i instanceof nr)return e=i.name,u(),n=x(),new Z(e,n);if(i instanceof J)return u(),n=x(),new tr(i,n);if(i instanceof er&&(t=!0,r=[],e=i.symbol.name,i.params.forEach(function(e,n){e instanceof nr?r[n]=e.name:t=!1}),t))return u(),n=x(),new $(e,r,n);throw P("Invalid left hand side of assignment operator =")}return i}function y(){for(var e=w();"?"==lr;){u();var r=e,n=v();if(":"!=lr)throw P("False part of conditional expression expected");u();var t=y();e=new Q(r,n,t)}return e}function w(){var e,r=[];if(e=":"==lr?new K("1","number"):v(),":"==lr){for(r.push(e);":"==lr;)u(),r.push(")"==lr||"]"==lr||","==lr||""==lr?new nr("end"):v());if(3==r.length){var n=r[2];r[2]=r[1],r[1]=n}e=new rr(r)}return e}function v(){var e,r,n,t,i;for(e=b(),r={to:"to","in":"to"};lr in r;)n=lr,t=r[n],u(),i=[e,b()],e=new X(n,t,i);return e}function b(){var e,r,n,t,i;for(e=E(),r={"==":"equal","!=":"unequal","<":"smaller",">":"larger","<=":"smallerEq",">=":"largerEq"};lr in r;)n=lr,t=r[n],u(),i=[e,E()],e=new X(n,t,i);return e}function E(){var e,r,n,t,i;for(e=N(),r={"+":"add","-":"subtract"};lr in r;)n=lr,t=r[n],u(),i=[e,N()],e=new X(n,t,i);return e}function N(){var e,r,n,t,i;if(e=M(),r={"*":"multiply",".*":"dotMultiply","/":"divide","./":"dotDivide","%":"mod",mod:"mod"},lr in r)for(;lr in r;)n=lr,t=r[n],u(),i=[e,M()],e=new X(n,t,i);return(pr==ir.SYMBOL||"in"==lr&&e instanceof K||pr==ir.NUMBER&&!(e instanceof K)||"("==lr||"["==lr)&&(e=new X("*","multiply",[e,N()])),e}function M(){var e,r,n;return"-"==lr||"+"==lr?(e=lr,r="+"==e?"unaryPlus":"unaryMinus",u(),n=[M()],new X(e,r,n)):A()}function A(){var e,r,n,t;return e=T(),("^"==lr||".^"==lr)&&(r=lr,n="^"==r?"pow":"dotPow",u(),t=[e,M()],e=new X(r,n,t)),e}function T(){var e,r,n,t,i;for(e=S(),r={"!":"factorial","'":"transpose"};lr in r;)n=lr,t=r[n],s(),i=[e],e=new X(n,t,i);return e}function S(){var e,r=[];if(pr==ir.SYMBOL&&sr[lr]){if(e=sr[lr],s(),"("==lr){if(r=[],f(),s(),")"!=lr)for(r.push(y());","==lr;)s(),r.push(y());if(")"!=lr)throw P("Parenthesis ) expected");c(),s()}return new e(r)}return O()}function O(){var e,r;return pr==ir.SYMBOL||pr==ir.DELIMITER&&lr in ar?(r=lr,s(),e=new nr(r),e=C(e),e=U(e)):q()}function C(e){var r;if("("==lr){if(r=[],f(),s(),")"!=lr)for(r.push(y());","==lr;)s(),r.push(y());if(")"!=lr)throw P("Parenthesis ) expected");return c(),s(),new er(e,r)}return e}function U(e){for(var r;"["==lr;){if(r=[],f(),s(),"]"!=lr)for(r.push(y());","==lr;)s(),r.push(y());if("]"!=lr)throw P("Parenthesis ] expected");c(),s(),e=new J(e,r)}return e}function q(){var e,r,n;if('"'==lr){for(r="",n="";""!=cr&&('"'!=cr||"\\"==n);)r+=cr,n=cr,o();if(s(),'"'!=lr)throw P('End of string " expected');return s(),e=new K(r,"string"),e=U(e)}return B()}function B(){var e,r,n,t;if("["==lr){if(f(),s(),"]"!=lr){var i=z();if(";"==lr){for(n=1,r=[i];";"==lr;)s(),r[n]=z(),n++;if("]"!=lr)throw P("End of matrix ] expected");c(),s(),t=r[0].nodes.length;for(var o=1;n>o;o++)if(r[o].nodes.length!=t)throw k("Column dimensions mismatch ("+r[o].nodes.length+" != "+t+")");e=new Y(r)}else{if("]"!=lr)throw P("End of matrix ] expected");c(),s(),e=i}}else c(),s(),e=new Y([]);return e}return I()}function z(){for(var e=[x()],r=1;","==lr;)s(),e[r]=x(),r++;return new Y(e)}function I(){var e;return pr==ir.NUMBER?(e=lr,s(),new K(e,"number")):_()}function _(){var e;if("("==lr){if(f(),s(),e=x(),")"!=lr)throw P("Parenthesis ) expected");return c(),s(),e}return R()}function R(){throw P(""==lr?"Unexpected end of expression":"Value expected")}function L(){return fr-lr.length+1}function P(e){var r=L(),n=new SyntaxError(e+" (char "+r+")");return n["char"]=r,n}function k(e){var r=L(),n=new Error(e+" (char "+r+")");return n["char"]=r,n}var j=n(143),F=n(138),D=j.string.isString,G=Array.isArray,V=(j.types.type,n(6),n(9)),H=(n(10),n(13)),Y=n(144),Z=n(145),W=n(146),Q=n(147),K=n(148),$=n(150),J=n(149),X=n(153),er=n(151),rr=n(154),nr=n(155),tr=n(156),ir={NULL:0,DELIMITER:1,NUMBER:2,SYMBOL:3,UNKNOWN:4},or={",":!0,"(":!0,")":!0,"[":!0,"]":!0,'"':!0,";":!0,"+":!0,"-":!0,"*":!0,".*":!0,"/":!0,"./":!0,"%":!0,"^":!0,".^":!0,"!":!0,"'":!0,"=":!0,":":!0,"?":!0,"==":!0,"!=":!0,"<":!0,">":!0,"<=":!0,">=":!0},ar={mod:!0,to:!0,"in":!0},sr={},ur="",fr=0,cr="",lr="",pr=ir.NULL,mr=0;e.exports=t},function(e,r,n){"use strict";function t(e){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(!(e instanceof Object))throw new TypeError("Object expected as parameter math");this.math=e,this.scope={}}var i=n(14);t.prototype.parse=function(){throw new Error("Parser.parse is deprecated. Use math.parse instead.")},t.prototype.compile=function(){throw new Error("Parser.compile is deprecated. Use math.compile instead.")},t.prototype.eval=function(e){return i(e).compile(this.math).eval(this.scope)},t.prototype.get=function(e){return this.scope[e]},t.prototype.set=function(e,r){return this.scope[e]=r},t.prototype.remove=function(e){delete this.scope[e]},t.prototype.clear=function(){for(var e in this.scope)this.scope.hasOwnProperty(e)&&delete this.scope[e]},e.exports=t},function(e,r,n){"use strict";r.ArrayNode=n(144),r.AssignmentNode=n(145),r.BlockNode=n(146),r.ConditionalNode=n(147),r.ConstantNode=n(148),r.IndexNode=n(149),r.FunctionAssignmentNode=n(150),r.FunctionNode=n(151),r.Node=n(152),r.OperatorNode=n(153),r.RangeNode=n(154),r.SymbolNode=n(155),r.UpdateNode=n(156)},function(e,r,n){r.e=n(160),r.E=n(160),r["false"]=n(161),r.i=n(162),r.Infinity=n(163),r.LN2=n(164),r.LN10=n(165),r.LOG2E=n(166),r.LOG10E=n(167),r.NaN=n(168),r["null"]=n(169),r.pi=n(170),r.PI=n(170),r.phi=n(171),r.SQRT1_2=n(172),r.SQRT2=n(173),r.tau=n(174),r["true"]=n(175),r.version=n(176),r.abs=n(179),r.add=n(180),r.ceil=n(181),r.cube=n(182),r.divide=n(183),r.dotDivide=n(184),r.dotMultiply=n(185),r.dotPow=n(186),r.exp=n(187),r.fix=n(188),r.floor=n(189),r.gcd=n(190),r.lcm=n(191),r.log=n(192),r.log10=n(193),r.mod=n(194),r.multiply=n(195),r.norm=n(196),r.pow=n(197),r.round=n(198),r.sign=n(199),r.sqrt=n(200),r.square=n(201),r.subtract=n(202),r.unaryMinus=n(203),r.unaryPlus=n(204),r.xgcd=n(205),r.compare=n(206),r.deepEqual=n(207),r.equal=n(208),r.larger=n(209),r.largerEq=n(210),r.smaller=n(211),r.smallerEq=n(212),r.unequal=n(213),r.arg=n(214),r.conj=n(215),r.re=n(216),r.im=n(217),r.bignumber=n(218),r["boolean"]=n(219),r.complex=n(220),r.index=n(221),r.matrix=n(222),r.number=n(223),r.string=n(224),r.unit=n(225),r.eval=n(226),r.help=n(227),r.concat=n(228),r.det=n(229),r.diag=n(230),r.eye=n(231),r.flatten=n(232),r.inv=n(233),r.ones=n(234),r.range=n(235),r.resize=n(236),r.size=n(237),r.squeeze=n(238),r.subset=n(239),r.transpose=n(240),r.zeros=n(241),r.combinations=n(242),r.distribution=n(243),r.factorial=n(244),r.permutations=n(245),r.pickRandom=n(246),r.random=n(247),r.randomInt=n(248),r.max=n(249),r.mean=n(250),r.median=n(251),r.min=n(252),r.prod=n(253),r.std=n(254),r.sum=n(255),r["var"]=n(256),r.acos=n(257),r.asin=n(258),r.atan=n(259),r.atan2=n(260),r.cos=n(261),r.cosh=n(262),r.cot=n(263),r.coth=n(264),r.csc=n(265),r.csch=n(266),r.sec=n(267),r.sech=n(268),r.sin=n(269),r.sinh=n(270),r.tan=n(271),r.tanh=n(272),r.to=n(273),r.clone=n(274),r.map=n(275),r.forEach=n(276),r.format=n(277),r["import"]=n(278),r.sort=n(279),r["typeof"]=n(280)},function(e,r,n){"use strict";var t=n(142),i=n(157).transform,o=n(4).isNumber,a=n(136).argsToArray;e.exports=function(e){e.concat.transform=function(){var r=a(arguments),n=r.length-1,s=r[n];o(s)?r[n]=s-1:s instanceof t&&(r[n]=s.minus(1));try{return e.concat.apply(e,r)}catch(u){throw i(u)}}}},function(e,r,n){"use strict";{var t=n(9);n(142),n(7),n(8),n(4).isNumber,Array.isArray}e.exports=function(e){e.forEach.transform=function(r,n){if(2!=arguments.length)throw new e.error.ArgumentsError("forEach",arguments.length,2);var i=r instanceof t?r.valueOf():r;if(!Array.isArray(i))throw new e.error.UnsupportedTypeError("forEach",e["typeof"](r));var o=[],a=function(e,t){return Array.isArray(e)?e.map(function(e,r){return o[t]=r+1,a(e,t+1)}):void n(e,o,r)};a(i,0)}}},function(e,r,n){"use strict";var t=n(142),i=n(7),o=n(8),a=n(4).isNumber,s=Array.isArray;e.exports=function(e){e.index.transform=function(){for(var e=[],r=0,n=arguments.length;n>r;r++){var u=arguments[r];if(u instanceof i)u.start--,u.end-=u.step.valueOf()>0?0:2;else if(s(u)){for(var f=0,c=u.length;c>f;f++)u[f]=u[f]instanceof t?u[f].toNumber():u[f];var l=u.length>2?u[2]:1;u[0]--,u[1]-=l>0?0:2}else a(u)?u--:u instanceof t&&(u=u.toNumber()-1);e[r]=u}var p=new o;return o.apply(p,e),p}}},function(e,r,n){"use strict";{var t=n(9);n(142),n(7),n(8),n(4).isNumber,Array.isArray}e.exports=function(e){e.map.transform=function(r,n){if(2!=arguments.length)throw new e.error.ArgumentsError("map",arguments.length,2);var i=r instanceof t,o=i?r.valueOf():r;if(Array.isArray(o)){var a=[],s=function(e,t){return Array.isArray(e)?e.map(function(e,r){return a[t]=r+1,s(e,t+1)}):n(e,a,r)},u=s(o,0);return i?new t(u):u}throw new e.error.UnsupportedTypeError("map",e["typeof"](r))}}},function(e,r,n){"use strict";var t=n(142),i=n(157).transform,o=n(4).isNumber,a=n(13).isCollection,s=n(136).argsToArray;e.exports=function(e){e.max.transform=function(){var r=s(arguments);if(2==r.length&&a(r[0])){var n=r[1];o(n)?r[1]=n-1:n instanceof t&&(r[1]=n.minus(1))}try{return e.max.apply(e,r)}catch(u){throw i(u)}}}},function(e,r,n){"use strict";var t=n(142),i=n(157).transform,o=n(4).isNumber,a=n(13).isCollection,s=n(136).argsToArray;e.exports=function(e){e.mean.transform=function(){var r=s(arguments);if(2==r.length&&a(r[0])){var n=r[1];o(n)?r[1]=n-1:n instanceof t&&(r[1]=n.minus(1))}try{return e.mean.apply(e,r)}catch(u){throw i(u)}}}},function(e,r,n){"use strict";var t=n(142),i=n(157).transform,o=n(4).isNumber,a=n(13).isCollection,s=n(136).argsToArray;e.exports=function(e){e.min.transform=function(){var r=s(arguments);if(2==r.length&&a(r[0])){var n=r[1];o(n)?r[1]=n-1:n instanceof t&&(r[1]=n.minus(1))}try{return e.min.apply(e,r)}catch(u){throw i(u)}}}},function(e,r,n){"use strict";var t=n(158).isBoolean,i=n(136).argsToArray;e.exports=function(e){e.range.transform=function(){var r=i(arguments),n=r.length-1,o=r[n];return t(o)||r.push(!0),e.range.apply(e,r)}}},function(e,r,n){"use strict";var t=n(157).transform,i=(n(158).isBoolean,n(136).argsToArray);e.exports=function(e){e.subset.transform=function(){try{return e.subset.apply(e,i(arguments))}catch(r){throw t(r)}}}},function(e,r,n){"use strict";e.exports=function(e){function r(e){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");this.value=e instanceof r?e.value:e}function t(e,n){var t=Array.prototype.slice;r.prototype[e]="function"==typeof n?function(){var e=[this.value].concat(t.call(arguments,0));return new r(n.apply(this,e))}:new r(n)}var i=n(159);r.prototype.done=function(){return this.value},r.prototype.valueOf=function(){return this.value},r.prototype.toString=function(){return i.format(this.value)},r.createProxy=t;for(var o in e)e.hasOwnProperty(o)&&t(o,e[o]);return r}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=n(14),i=n(13),o=r.string.isString,a=i.isCollection;e.compile=function(r){if(1!=arguments.length)throw new e.error.ArgumentsError("compile",arguments.length,1);if(o(r))return t(r).compile(e);if(a(r))return i.deepMap(r,function(r){return t(r).compile(e)});throw new TypeError("String, array, or matrix expected")}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=n(14),i=n(13),o=r.string.isString,a=i.isCollection;e.eval=function(r,n){if(1!=arguments.length&&2!=arguments.length)throw new e.error.ArgumentsError("eval",arguments.length,1,2);if(n=n||{},o(r))return t(r).compile(e).eval(n);if(a(r))return i.deepMap(r,function(r){return t(r).compile(e).eval(n)});throw new TypeError("String, array, or matrix expected")}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(11);e.help=function(n){if(1!=arguments.length)throw new SyntaxError("Wrong number of arguments in function help ("+arguments.length+" provided, 1 expected)");var t=null;if(n instanceof String||"string"==typeof n)t=n;else{var i;for(i in e)if(e.hasOwnProperty(i)&&n===e[i]){t=i;break}}var o=e.expression.docs[t];if(!t||!o)throw new Error('No documentation found on "'+t+'"');return new r(e,o)}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(14);e.parse=function(){return r.apply(r,arguments)}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=(n(9),n(13)),a=r.number.isNumber,s=r["boolean"].isBoolean,u=i.isComplex,f=o.isCollection;e.abs=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("abs",arguments.length,1);if(a(r))return Math.abs(r);if(u(r))return Math.sqrt(r.re*r.re+r.im*r.im);if(r instanceof t)return r.abs();if(f(r))return o.deepMap(r,c);if(s(r)||null===r)return Math.abs(r);throw new e.error.UnsupportedTypeError("abs",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=(n(9),n(10)),a=n(13),s=r["boolean"].isBoolean,u=r.number.isNumber,f=r.string.isString,c=i.isComplex,l=o.isUnit,p=a.isCollection;e.add=function m(r,n){if(2!=arguments.length)throw new e.error.ArgumentsError("add",arguments.length,2);if(u(r)){if(u(n))return r+n;if(c(n))return new i(r+n.re,n.im)}if(c(r)){if(c(n))return new i(r.re+n.re,r.im+n.im);if(u(n))return new i(r.re+n,r.im)}if(l(r)&&l(n)){if(null==r.value)throw new Error("Parameter x contains a unit with undefined value");if(null==n.value)throw new Error("Parameter y contains a unit with undefined value");if(!r.equalBase(n))throw new Error("Units do not match");var o=r.clone();return o.value+=n.value,o.fixPrefix=!1,o}if(r instanceof t)return u(n)?n=t.convert(n):(s(n)||null===n)&&(n=new t(n?1:0)),n instanceof t?r.plus(n):m(r.toNumber(),n);if(n instanceof t)return u(r)?r=t.convert(r):(s(r)||null===r)&&(r=new t(r?1:0)),r instanceof t?r.plus(n):m(r,n.toNumber());if(p(r)||p(n))return a.deepMap2(r,n,m);if(f(r)||f(n))return r+n;if(s(r)||null===r)return m(+r,n);if(s(n)||null===n)return m(r,+n);throw new e.error.UnsupportedTypeError("add",e["typeof"](r),e["typeof"](n))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=o.isCollection,f=i.isComplex;e.ceil=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("ceil",arguments.length,1);if(a(r))return Math.ceil(r);if(f(r))return new i(Math.ceil(r.re),Math.ceil(r.im));if(r instanceof t)return r.ceil();if(u(r))return o.deepMap(r,c);if(s(r)||null===r)return Math.ceil(r);throw new e.error.UnsupportedTypeError("ceil",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=i.isComplex,f=o.isCollection;e.cube=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("cube",arguments.length,1);if(a(r))return r*r*r;if(u(r))return e.multiply(e.multiply(r,r),r);if(r instanceof t)return r.times(r).times(r);if(f(r))return o.deepMap(r,c);if(s(r)||null===r)return c(+r);throw new e.error.UnsupportedTypeError("cube",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){function r(e,r){var n=r.re*r.re+r.im*r.im;return 0!=n?new o((e.re*r.re+e.im*r.im)/n,(e.im*r.re-e.re*r.im)/n):new o(0!=e.re?e.re/0:0,0!=e.im?e.im/0:0)}var t=n(143),i=e.type.BigNumber,o=n(6),a=(n(9),n(10)),s=n(13),u=t.number.isNumber,f=t["boolean"].isBoolean,c=o.isComplex,l=a.isUnit,p=s.isCollection;e.divide=function m(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("divide",arguments.length,2);if(u(n)){if(u(t))return n/t;if(c(t))return r(new o(n,0),t)}if(c(n)){if(c(t))return r(n,t);if(u(t))return r(n,new o(t,0))}if(n instanceof i)return u(t)?t=i.convert(t):(f(t)||null===t)&&(t=new i(t?1:0)),t instanceof i?n.div(t):m(n.toNumber(),t);if(t instanceof i)return u(n)?n=i.convert(n):(f(n)||null===n)&&(n=new i(n?1:0)),n instanceof i?n.div(t):m(n,t.toNumber());if(l(n)&&u(t)){var a=n.clone();return a.value/=t,a}if(p(n))return p(t)?e.multiply(n,e.inv(t)):s.deepMap2(n,t,m);if(p(t))return e.multiply(n,e.inv(t));if(f(n)||null===n)return m(+n,t);if(f(t)||null===t)return m(n,+t);throw new e.error.UnsupportedTypeError("divide",e["typeof"](n),e["typeof"](t))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(13);e.dotDivide=function(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("dotDivide",arguments.length,2);return r.deepMap2(n,t,e.divide)},e.edivide=function(){throw new Error("Function edivide is renamed to dotDivide")}}},function(e,r,n){"use strict";e.exports=function(e){var r=(n(143),n(13));e.dotMultiply=function(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("dotMultiply",arguments.length,2);return r.deepMap2(n,t,e.multiply)},e.emultiply=function(){throw new Error("Function emultiply is renamed to dotMultiply")}}},function(e,r,n){"use strict";e.exports=function(e){var r=(n(143),n(13));e.dotPow=function(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("dotPow",arguments.length,2);return r.deepMap2(n,t,e.pow)},e.epow=function(){throw new Error("Function epow is renamed to dotPow")}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=(n(9),n(13)),a=r.number.isNumber,s=r["boolean"].isBoolean,u=i.isComplex,f=o.isCollection;e.exp=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("exp",arguments.length,1);if(a(r))return Math.exp(r);if(u(r)){var n=Math.exp(r.re);return new i(n*Math.cos(r.im),n*Math.sin(r.im))}if(r instanceof t)return r.exp();if(f(r))return o.deepMap(r,c);if(s(r)||null===r)return Math.exp(r);throw new e.error.UnsupportedTypeError("exp",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=i.isComplex,f=o.isCollection;e.fix=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("fix",arguments.length,1);if(a(r))return r>0?Math.floor(r):Math.ceil(r);if(u(r))return new i(r.re>0?Math.floor(r.re):Math.ceil(r.re),r.im>0?Math.floor(r.im):Math.ceil(r.im));if(r instanceof t)return r.isNegative()?r.ceil():r.floor();if(f(r))return o.deepMap(r,c);if(s(r)||null===r)return c(+r);throw new e.error.UnsupportedTypeError("fix",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=i.isComplex,f=o.isCollection;e.floor=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("floor",arguments.length,1);if(a(r))return Math.floor(r);if(u(r))return new i(Math.floor(r.re),Math.floor(r.im));if(r instanceof t)return r.floor();if(f(r))return o.deepMap(r,c);if(s(r)||null===r)return c(+r);throw new e.error.UnsupportedTypeError("floor",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){function r(e,r){if(!e.isInt()||!r.isInt())throw new Error("Parameters in function gcd must be integer numbers");for(var n=new i(0);!r.isZero();){var t=e.mod(r);e=r,r=t}return e.lt(n)?e.neg():e}var t=n(143),i=e.type.BigNumber,o=n(13),a=t.number.isNumber,s=t["boolean"].isBoolean,u=t.number.isInteger,f=o.isCollection;e.gcd=function c(){var n,t=arguments[0],l=arguments[1];if(2==arguments.length){if(a(t)&&a(l)){if(!u(t)||!u(l))throw new Error("Parameters in function gcd must be integer numbers");for(;0!=l;)n=t%l,t=l,l=n;return 0>t?-t:t}if(f(t)||f(l))return o.deepMap2(t,l,c);if(t instanceof i)return a(l)?l=i.convert(l):(s(l)||null===l)&&(l=new i(l?1:0)),l instanceof i?r(t,l):c(t.toNumber(),l);if(l instanceof i)return a(t)?t=i.convert(t):(s(t)||null===t)&&(t=new i(t?1:0)),t instanceof i?r(t,l):c(t.toNumber(),l);if(s(t)||null===t)return c(+t,l);if(s(l)||null===l)return c(t,+l);throw new e.error.UnsupportedTypeError("gcd",e["typeof"](t),e["typeof"](l))}if(arguments.length>2){for(var p=1;p<arguments.length;p++)t=c(t,arguments[p]);return t}throw new SyntaxError("Function gcd expects two or more arguments")}}},function(e,r,n){"use strict";e.exports=function(e){function r(e,r){if(!e.isInt()||!r.isInt())throw new Error("Parameters in function lcm must be integer numbers");if(e.isZero()||r.isZero())return new i(0);for(var n=e.times(r);!r.isZero();){var t=r;r=e.mod(t),e=t}return n.div(e).abs()}var t=n(143),i=e.type.BigNumber,o=n(13),a=t.number.isNumber,s=t["boolean"].isBoolean,u=t.number.isInteger,f=o.isCollection;e.lcm=function c(){var n,t=arguments[0],l=arguments[1];if(2==arguments.length){if(a(t)&&a(l)){if(!u(t)||!u(l))throw new Error("Parameters in function lcm must be integer numbers");if(0==t||0==l)return 0;for(var p=t*l;0!=l;)n=l,l=t%n,t=n;return Math.abs(p/t)}if(f(t)||f(l))return o.deepMap2(t,l,c);if(t instanceof i)return a(l)?l=i.convert(l):(s(l)||null===l)&&(l=new i(l?1:0)),l instanceof i?r(t,l):c(t.toNumber(),l);if(l instanceof i)return a(t)?t=i.convert(t):(s(t)||null===t)&&(t=new i(t?1:0)),t instanceof i?r(t,l):c(t.toNumber(),l);if(s(t)||null===t)return c(+t,l);if(s(l)||null===l)return c(t,+l);throw new e.error.UnsupportedTypeError("lcm",e["typeof"](t),e["typeof"](l))}if(arguments.length>2){for(var m=1;m<arguments.length;m++)t=c(t,arguments[m]);return t}throw new SyntaxError("Function lcm expects two or more arguments")}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=i.isComplex,f=o.isCollection;e.log=function c(r,n){if(1==arguments.length){if(a(r))return r>=0?Math.log(r):c(new i(r,0));if(u(r))return new i(Math.log(Math.sqrt(r.re*r.re+r.im*r.im)),Math.atan2(r.im,r.re));if(r instanceof t)return r.isNegative()?c(r.toNumber()):r.ln();if(f(r))return o.deepMap(r,c);if(s(r)||null===r)return c(+r);throw new e.error.UnsupportedTypeError("log",e["typeof"](r))}if(2==arguments.length)return e.divide(c(r),c(n));throw new e.error.ArgumentsError("log",arguments.length,1,2)}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=i.isComplex,f=o.isCollection;e.log10=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("log10",arguments.length,1);if(a(r))return r>=0?Math.log(r)/Math.LN10:c(new i(r,0));if(r instanceof t)return r.isNegative()?c(r.toNumber()):r.log();if(u(r))return new i(Math.log(Math.sqrt(r.re*r.re+r.im*r.im))/Math.LN10,Math.atan2(r.im,r.re)/Math.LN10);if(f(r))return o.deepMap(r,c);if(s(r)||null===r)return c(+r);throw new e.error.UnsupportedTypeError("log10",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){function r(e,r){if(r>0)return e-r*Math.floor(e/r);if(0==r)return e;throw new Error("Cannot calculate mod for a negative divisor")}var t=n(143),i=e.type.BigNumber,o=n(13),a=t.number.isNumber,s=t["boolean"].isBoolean,u=o.isCollection;e.mod=function f(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("mod",arguments.length,2);if(a(n)&&a(t))return r(n,t);if(n instanceof i)return a(t)?t=i.convert(t):(s(t)||null===t)&&(t=new i(t?1:0)),t instanceof i?t.isZero()?n:n.mod(t):f(n.toNumber(),t);if(t instanceof i)return a(n)?n=i.convert(n):(s(n)||null===n)&&(n=new i(n?1:0)),n instanceof i?t.isZero()?n:n.mod(t):f(n,t.toNumber());if(u(n)||u(t))return o.deepMap2(n,t,f);if(s(n)||null===n)return f(+n,t);if(s(t)||null===t)return f(n,+t);throw new e.error.UnsupportedTypeError("mod",e["typeof"](n),e["typeof"](t))}}},function(e,r,n){"use strict";e.exports=function(e){function r(r,n){for(var t=[],i=r.length,o=n[0].length,a=r[0].length,s=0;i>s;s++){t[s]=[];for(var u=0;o>u;u++){for(var f=null,c=0;a>c;c++){var l=e.multiply(r[s][c],n[c][u]);f=null===f?l:e.add(f,l)}t[s][u]=f}}var p=1===i&&1===o;return p?t[0][0]:t}function t(r,n){for(var t=[],i=n.length,o=n[0].length,a=0;o>a;a++){for(var s=null,u=0;i>u;u++){var f=e.multiply(r[u],n[u][a]);s=0===u?f:e.add(s,f)}t[a]=s}return 1===t.length?t[0]:t}function i(r,n){for(var t=[],i=r.length,o=r[0].length,a=0;i>a;a++){for(var s=null,u=0;o>u;u++){var f=e.multiply(r[a][u],n[u]);s=0===u?f:e.add(s,f)}t[a]=s}return 1===t.length?t[0]:t}function o(r,n){var t=r.length;if(!t)throw new Error("Cannot multiply two empty vectors");for(var i=0,o=0;t>o;o++)i=e.add(i,e.multiply(r[o],n[o]));return i}function a(e,r){return 0==e.im?0==r.im?new f(e.re*r.re,0):0==r.re?new f(0,e.re*r.im):new f(e.re*r.re,e.re*r.im):0==e.re?0==r.im?new f(0,e.im*r.re):0==r.re?new f(-e.im*r.im,0):new f(-e.im*r.im,e.im*r.re):0==r.im?new f(e.re*r.re,e.im*r.re):0==r.re?new f(-e.im*r.im,e.re*r.im):new f(e.re*r.re-e.im*r.im,e.re*r.im+e.im*r.re)}var s=n(143),u=e.type.BigNumber,f=n(6),c=n(9),l=n(10),p=n(13),m=s.array,h=s.number.isNumber,g=s["boolean"].isBoolean,d=f.isComplex,x=Array.isArray,y=l.isUnit;e.multiply=function w(n,s){var l;if(2!=arguments.length)throw new e.error.ArgumentsError("multiply",arguments.length,2);if(h(n)){if(h(s))return n*s;if(d(s))return a(new f(n,0),s);if(y(s))return l=s.clone(),l.value=null===l.value?l._normalize(n):l.value*n,l}if(d(n)){if(h(s))return a(n,new f(s,0));if(d(s))return a(n,s)}if(n instanceof u)return h(s)?s=u.convert(s):(g(s)||null===s)&&(s=new u(s?1:0)),s instanceof u?n.times(s):w(n.toNumber(),s);if(s instanceof u)return h(n)?n=u.convert(n):(g(n)||null===n)&&(n=new u(n?1:0)),n instanceof u?n.times(s):w(n,s.toNumber());if(y(n)&&h(s))return l=n.clone(),l.value=null===l.value?l._normalize(s):l.value*s,l;if(x(n)){if(x(s)){var v=m.size(n),b=m.size(s);if(1==v.length){if(1==b.length){if(v[0]!=b[0])throw new RangeError("Dimension mismatch in multiplication. Length of A must match length of B (A is "+v[0]+", B is "+b[0]+v[0]+" != "+b[0]+")");return o(n,s)}if(2==b.length){if(v[0]!=b[0])throw new RangeError("Dimension mismatch in multiplication. Length of A must match rows of B (A is "+v[0]+", B is "+b[0]+"x"+b[1]+", "+v[0]+" != "+b[0]+")");return t(n,s)}throw new Error("Can only multiply a 1 or 2 dimensional matrix (B has "+b.length+" dimensions)")}if(2==v.length){if(1==b.length){if(v[1]!=b[0])throw new RangeError("Dimension mismatch in multiplication. Columns of A must match length of B (A is "+v[0]+"x"+v[0]+", B is "+b[0]+", "+v[1]+" != "+b[0]+")");return i(n,s)}if(2==b.length){if(v[1]!=b[0])throw new RangeError("Dimension mismatch in multiplication. Columns of A must match rows of B (A is "+v[0]+"x"+v[1]+", B is "+b[0]+"x"+b[1]+", "+v[1]+" != "+b[0]+")");return r(n,s)}throw new Error("Can only multiply a 1 or 2 dimensional matrix (B has "+b.length+" dimensions)")}throw new Error("Can only multiply a 1 or 2 dimensional matrix (A has "+v.length+" dimensions)")}return s instanceof c?(l=w(n,s.valueOf()),x(l)?new c(l):l):p.deepMap2(n,s,w)}if(n instanceof c)return s instanceof c?(l=w(n.valueOf(),s.valueOf()),x(l)?new c(l):l):(l=w(n.valueOf(),s),x(l)?new c(l):l);if(x(s))return p.deepMap2(n,s,w);if(s instanceof c)return new c(p.deepMap2(n,s.valueOf(),w));if(g(n)||null===n)return w(+n,s);if(g(s)||null===s)return w(n,+s);throw new e.error.UnsupportedTypeError("multiply",e["typeof"](n),e["typeof"](s))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=n(136),i=e.type.BigNumber,o=n(6),a=n(9),s=(n(13),r.number.isNumber),u=r["boolean"].isBoolean,f=o.isComplex,c=Array.isArray;
e.norm=function l(r,n){if(arguments.length<1||arguments.length>2)throw new e.error.ArgumentsError("abs",arguments.length,1,2);if(s(r))return Math.abs(r);if(f(r))return Math.sqrt(r.re*r.re+r.im*r.im);if(r instanceof i)return r.abs();if(u(r)||null===r)return Math.abs(r);if(c(r)){var o=t.size(r);if(null==n&&(n=2),1==o.length){if(n===Number.POSITIVE_INFINITY||"inf"===n){var p;return e.forEach(r,function(r){var n=e.abs(r);(!p||e.larger(n,p))&&(p=n)}),p}if(n===Number.NEGATIVE_INFINITY||"-inf"===n){var p;return e.forEach(r,function(r){var n=e.abs(r);(!p||e.smaller(n,p))&&(p=n)}),p}if("fro"===n)return l(r);if(s(n)&&!isNaN(n)){if(!e.equal(n,0)){var p=0;return e.forEach(r,function(r){p=e.add(e.pow(e.abs(r),n),p)}),e.pow(p,1/n)}return Number.POSITIVE_INFINITY}throw new Error("Unsupported parameter value")}if(2==o.length){if(1==n){for(var m=[],h=0;h<r.length;h++)for(var g=r[h],d=0;d<g.length;d++)m[d]=e.add(m[d]||0,e.abs(g[d]));return e.max(m)}if(n==Number.POSITIVE_INFINITY||"inf"===n){for(var p=0,h=0;h<r.length;h++){for(var x=0,g=r[h],d=0;d<g.length;d++)x=e.add(x,e.abs(g[d]));e.larger(x,p)&&(p=x)}return p}if("fro"===n){var y=e.diag(e.multiply(e.transpose(r),r)),w=0;return e.forEach(y,function(r){w=e.add(r,w)}),e.sqrt(w)}if(2==n)throw new Error("Unsupported parameter value, missing implementation of matrix singular value decomposition");throw new Error("Unsupported parameter value")}}if(r instanceof a)return l(r.valueOf(),n);throw new e.error.UnsupportedTypeError("norm",r)}}},function(e,r,n){"use strict";e.exports=function(e){function r(r,n){var t=e.log(r),i=e.multiply(t,n);return e.exp(i)}var t=n(143),i=e.type.BigNumber,o=n(6),a=n(9),s=(n(13),t.array),u=t.number.isNumber,f=t["boolean"].isBoolean,c=Array.isArray,l=t.number.isInteger,p=o.isComplex;e.pow=function m(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("pow",arguments.length,2);if(u(n)){if(u(t))return l(t)||n>=0?Math.pow(n,t):r(new o(n,0),new o(t,0));if(p(t))return r(new o(n,0),t)}if(p(n)){if(u(t))return r(n,new o(t,0));if(p(t))return r(n,t)}if(n instanceof i)return u(t)?t=i.convert(t):(f(t)||null===t)&&(t=new i(t?1:0)),t instanceof i?t.isInteger()&&!n.isNegative()?n.pow(t):m(n.toNumber(),t.toNumber()):m(n.toNumber(),t);if(t instanceof i)return u(n)?n=i.convert(n):(f(n)||null===n)&&(n=new i(n?1:0)),n instanceof i?t.isInteger()&&!n.isNegative()?n.pow(t):m(n.toNumber(),t.toNumber()):m(n,t.toNumber());if(c(n)){if(!u(t)||!l(t)||0>t)throw new TypeError("For A^b, b must be a positive integer (value is "+t+")");var h=s.size(n);if(2!=h.length)throw new Error("For A^b, A must be 2 dimensional (A has "+h.length+" dimensions)");if(h[0]!=h[1])throw new Error("For A^b, A must be square (size is "+h[0]+"x"+h[1]+")");for(var g=e.eye(h[0]).valueOf(),d=n;t>=1;)1==(1&t)&&(g=e.multiply(d,g)),t>>=1,d=e.multiply(d,d);return g}if(n instanceof a)return new a(m(n.valueOf(),t));if(f(n)||null===n)return m(+n,t);if(f(t)||null===t)return m(n,+t);throw new e.error.UnsupportedTypeError("pow",e["typeof"](n),e["typeof"](t))}}},function(e,r,n){"use strict";e.exports=function(e){function r(e,r){var n=Math.pow(10,r);return Math.round(e*n)/n}var t=n(143),i=e.type.BigNumber,o=n(6),a=n(13),s=t.number.isNumber,u=t.number.isInteger,f=t["boolean"].isBoolean,c=o.isComplex,l=a.isCollection;e.round=function p(n,t){if(1!=arguments.length&&2!=arguments.length)throw new e.error.ArgumentsError("round",arguments.length,1,2);if(void 0==t){if(s(n))return Math.round(n);if(c(n))return new o(Math.round(n.re),Math.round(n.im));if(n instanceof i)return n.toDecimalPlaces(0);if(l(n))return a.deepMap(n,p);if(f(n)||null===n)return Math.round(n);throw new e.error.UnsupportedTypeError("round",e["typeof"](n))}if(!s(t)||!u(t)){if(!(t instanceof i)){if(f(t)||null===n)return p(n,+t);throw new TypeError("Number of decimals in function round must be an integer")}t=parseFloat(t.valueOf())}if(0>t||t>15)throw new Error("Number of decimals in function round must be in te range of 0-15");if(s(n))return r(n,t);if(c(n))return new o(r(n.re,t),r(n.im,t));if(n instanceof i)return n.toDecimalPlaces(t);if(l(n)||l(t))return a.deepMap2(n,t,p);if(f(n)||null===n)return p(+n,t);throw new e.error.UnsupportedTypeError("round",e["typeof"](n),e["typeof"](t))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number,s=r.number.isNumber,u=r["boolean"].isBoolean,f=i.isComplex,c=o.isCollection;e.sign=function l(r){if(1!=arguments.length)throw new e.error.ArgumentsError("sign",arguments.length,1);if(s(r))return a.sign(r);if(f(r)){var n=Math.sqrt(r.re*r.re+r.im*r.im);return new i(r.re/n,r.im/n)}if(r instanceof t)return new t(r.cmp(0));if(c(r))return o.deepMap(r,l);if(u(r)||null===r)return a.sign(r);throw new e.error.UnsupportedTypeError("sign",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=i.isComplex,f=o.isCollection;e.sqrt=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("sqrt",arguments.length,1);if(a(r))return r>=0?Math.sqrt(r):c(new i(r,0));if(u(r)){var n,l,p=Math.sqrt(r.re*r.re+r.im*r.im);return n=r.re>=0?.5*Math.sqrt(2*(p+r.re)):Math.abs(r.im)/Math.sqrt(2*(p-r.re)),l=r.re<=0?.5*Math.sqrt(2*(p-r.re)):Math.abs(r.im)/Math.sqrt(2*(p+r.re)),r.im>=0?new i(n,l):new i(n,-l)}if(r instanceof t)return r.isNegative()?c(r.toNumber()):r.sqrt();if(f(r))return o.deepMap(r,c);if(s(r)||null===r)return c(+r);throw new e.error.UnsupportedTypeError("sqrt",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=i.isComplex,f=o.isCollection;e.square=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("square",arguments.length,1);if(a(r))return r*r;if(u(r))return e.multiply(r,r);if(r instanceof t)return r.times(r);if(f(r))return o.deepMap(r,c);if(s(r)||null===r)return r*r;throw new e.error.UnsupportedTypeError("square",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=(n(9),n(10)),a=n(13),s=r["boolean"].isBoolean,u=r.number.isNumber,f=i.isComplex,c=o.isUnit,l=a.isCollection;e.subtract=function p(r,n){if(2!=arguments.length)throw new e.error.ArgumentsError("subtract",arguments.length,2);if(u(r)){if(u(n))return r-n;if(f(n))return new i(r-n.re,-n.im)}else if(f(r)){if(u(n))return new i(r.re-n,r.im);if(f(n))return new i(r.re-n.re,r.im-n.im)}if(r instanceof t)return u(n)?n=t.convert(n):(s(n)||null===n)&&(n=new t(n?1:0)),n instanceof t?r.minus(n):p(r.toNumber(),n);if(n instanceof t)return u(r)?r=t.convert(r):(s(r)||null===r)&&(r=new t(r?1:0)),r instanceof t?r.minus(n):p(r,n.toNumber());if(c(r)&&c(n)){if(null==r.value)throw new Error("Parameter x contains a unit with undefined value");if(null==n.value)throw new Error("Parameter y contains a unit with undefined value");if(!r.equalBase(n))throw new Error("Units do not match");var o=r.clone();return o.value-=n.value,o.fixPrefix=!1,o}if(l(r)||l(n))return a.deepMap2(r,n,p);if(s(r)||null===r)return p(+r,n);if(s(n)||null===n)return p(r,+n);throw new e.error.UnsupportedTypeError("subtract",e["typeof"](r),e["typeof"](n))}}},function(e,r,n){"use strict";e.exports=function(e,r){var t=n(143),i=e.type.BigNumber,o=n(6),a=n(10),s=n(13),u=t.number.isNumber,f=t["boolean"].isBoolean,c=t.string.isString,l=o.isComplex,p=a.isUnit,m=s.isCollection;e.unaryMinus=function h(n){if(1!=arguments.length)throw new e.error.ArgumentsError("unaryMinus",arguments.length,1);if(u(n))return-n;if(l(n))return new o(-n.re,-n.im);if(n instanceof i)return n.neg();if(p(n)){var t=n.clone();return t.value=-n.value,t}if(m(n))return s.deepMap(n,h);if(f(n)||c(n)||null===n)return"bignumber"==r.number?new i(-n):-n;throw new e.error.UnsupportedTypeError("unaryMinus",e["typeof"](n))},e.unary=function(){throw new Error("Function unary is deprecated. Use unaryMinus instead.")}}},function(e,r,n){"use strict";e.exports=function(e,r){var t=n(143),i=e.type.BigNumber,o=n(6),a=n(10),s=n(13),u=t.number.isNumber,f=t["boolean"].isBoolean,c=t.string.isString,l=o.isComplex,p=a.isUnit,m=s.isCollection;e.unaryPlus=function h(n){if(1!=arguments.length)throw new e.error.ArgumentsError("unaryPlus",arguments.length,1);if(u(n))return n;if(l(n))return n.clone();if(n instanceof i)return n;if(p(n))return n.clone();if(m(n))return s.deepMap(n,h);if(f(n)||c(n)||null===n)return"bignumber"==r.number?new i(+n):+n;throw new e.error.UnsupportedTypeError("unaryPlus",e["typeof"](n))}}},function(e,r,n){"use strict";e.exports=function(e,r){function t(e,n){for(var t,i,o,s=0,u=1,f=1,c=0;n;)i=Math.floor(e/n),o=e%n,t=s,s=u-i*s,u=t,t=f,f=c-i*f,c=t,e=n,n=o;var l;return l=0>e?[-e,-u,-c]:[e,e?u:0,c],"array"===r.matrix?l:new a(l)}function i(e,n){for(var t,i,o,u=new s(0),f=new s(0),c=new s(1),l=new s(1),p=new s(0);!n.isZero();)i=e.div(n).floor(),o=e.mod(n),t=f,f=c.minus(i.times(f)),c=t,t=l,l=p.minus(i.times(l)),p=t,e=n,n=o;var m;return m=e.lt(u)?[e.neg(),c.neg(),p.neg()]:[e,e.isZero()?0:c,p],"array"===r.matrix?m:new a(m)}var o=n(143),a=n(9),s=e.type.BigNumber,u=o.number.isNumber,f=o["boolean"].isBoolean,c=o.number.isInteger;e.xgcd=function l(r,n){if(2==arguments.length){if(u(r)&&u(n)){if(!c(r)||!c(n))throw new Error("Parameters in function xgcd must be integer numbers");return t(r,n)}if(r instanceof s)return u(n)?n=s.convert(n):(f(n)||null===n)&&(n=new s(n?1:0)),n instanceof s?i(r,n):l(r.toNumber(),n);if(n instanceof s)return u(r)?r=s.convert(r):(f(r)||null===r)&&(r=new s(r?1:0)),r instanceof s?i(r,n):l(r.toNumber(),n);if(f(r)||null===r)return l(+r,n);if(f(n)||null===n)return l(r,+n);throw new e.error.UnsupportedTypeError("xgcd",e["typeof"](r),e["typeof"](n))}throw new SyntaxError("Function xgcd expects two arguments")}}},function(e,r,n){"use strict";e.exports=function(e,r){var t=n(143),i=e.type.BigNumber,o=n(6),a=n(10),s=n(13),u=t.number.isNumber,f=t.number.nearlyEqual,c=t["boolean"].isBoolean,l=t.string.isString,p=o.isComplex,m=a.isUnit,h=s.isCollection;e.compare=function g(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("compare",arguments.length,2);if(u(n)&&u(t))return f(n,t,r.epsilon)?0:n>t?1:-1;if(n instanceof i)return u(t)?t=i.convert(t):(c(t)||null===t)&&(t=new i(t?1:0)),t instanceof i?new i(n.cmp(t)):g(n.toNumber(),t);if(t instanceof i)return u(n)?n=i.convert(n):(c(n)||null===n)&&(n=new i(n?1:0)),n instanceof i?new i(n.cmp(t)):g(n,t.toNumber());if(m(n)&&m(t)){if(!n.equalBase(t))throw new Error("Cannot compare units with different base");return n.value>t.value?1:n.value<t.value?-1:0}if(h(n)||h(t))return s.deepMap2(n,t,g);if(l(n)||l(t))return n>t?1:t>n?-1:0;if(c(n)||null===n)return g(+n,t);if(c(t)||null===t)return g(n,+t);if(p(n)||p(t))throw new TypeError("No ordering relation is defined for complex numbers");throw new e.error.UnsupportedTypeError("compare",e["typeof"](n),e["typeof"](t))}}},function(e,r,n){"use strict";e.exports=function(e){function r(n,t){if(o(n)){if(o(t)){var i=n.length;if(i!==t.length)return!1;for(var a=0;i>a;a++)if(!r(n[a],t[a]))return!1;return!0}return!1}return o(t)?!1:e.equal(n,t)}var t=n(13),i=t.isCollection,o=Array.isArray;e.deepEqual=function(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("deepEqual",arguments.length,2);return i(n)||i(t)?r(n.valueOf(),t.valueOf()):e.equal(n,t)}}},function(e,r,n){"use strict";e.exports=function(e,r){var t=n(143),i=e.type.BigNumber,o=n(6),a=n(10),s=n(13),u=t.number.isNumber,f=t.number.nearlyEqual,c=t["boolean"].isBoolean,l=t.string.isString,p=o.isComplex,m=a.isUnit,h=s.isCollection;e.equal=function g(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("equal",arguments.length,2);if(u(n)){if(u(t))return f(n,t,r.epsilon);if(p(t))return f(n,t.re,r.epsilon)&&f(t.im,0,r.epsilon)}if(p(n)){if(u(t))return f(n.re,t,r.epsilon)&&f(n.im,0,r.epsilon);if(p(t))return f(n.re,t.re,r.epsilon)&&f(n.im,t.im,r.epsilon)}if(n instanceof i)return u(t)?t=i.convert(t):c(t)&&(t=new i(t?1:0)),t instanceof i?n.eq(t):g(n.toNumber(),t);if(t instanceof i)return u(n)?n=i.convert(n):c(n)&&(n=new i(n?1:0)),n instanceof i?n.eq(t):g(n,t.toNumber());if(m(n)&&m(t)){if(!n.equalBase(t))throw new Error("Cannot compare units with different base");return n.value==t.value}if(h(n)||h(t))return s.deepMap2(n,t,g);if(l(n)||l(t))return n==t;if(c(n))return g(+n,t);if(c(t))return g(n,+t);if(null===n)return null===t;if(null===t)return null===n;if(void 0===n)return void 0===t;if(void 0===t)return void 0===n;throw new e.error.UnsupportedTypeError("equal",e["typeof"](n),e["typeof"](t))}}},function(e,r,n){"use strict";e.exports=function(e,r){var t=n(143),i=e.type.BigNumber,o=n(6),a=n(10),s=n(13),u=t.number.isNumber,f=t.number.nearlyEqual,c=t["boolean"].isBoolean,l=t.string.isString,p=o.isComplex,m=a.isUnit,h=s.isCollection;e.larger=function g(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("larger",arguments.length,2);if(u(n)&&u(t))return!f(n,t,r.epsilon)&&n>t;if(n instanceof i)return u(t)?t=i.convert(t):(c(t)||null===t)&&(t=new i(t?1:0)),t instanceof i?n.gt(t):g(n.toNumber(),t);if(t instanceof i)return u(n)?n=i.convert(n):(c(n)||null===n)&&(n=new i(n?1:0)),n instanceof i?n.gt(t):g(n,t.toNumber());if(m(n)&&m(t)){if(!n.equalBase(t))throw new Error("Cannot compare units with different base");return n.value>t.value}if(h(n)||h(t))return s.deepMap2(n,t,g);if(l(n)||l(t))return n>t;if(c(n)||null===n)return g(+n,t);if(c(t)||null===t)return g(n,+t);if(p(n)||p(t))throw new TypeError("No ordering relation is defined for complex numbers");throw new e.error.UnsupportedTypeError("larger",e["typeof"](n),e["typeof"](t))}}},function(e,r,n){"use strict";e.exports=function(e,r){var t=n(143),i=e.type.BigNumber,o=n(6),a=n(10),s=n(13),u=t.number.isNumber,f=t.number.nearlyEqual,c=t["boolean"].isBoolean,l=t.string.isString,p=o.isComplex,m=a.isUnit,h=s.isCollection;e.largerEq=function g(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("largerEq",arguments.length,2);if(u(n)&&u(t))return f(n,t,r.epsilon)||n>t;if(n instanceof i)return u(t)?t=i.convert(t):(c(t)||null===t)&&(t=new i(t?1:0)),t instanceof i?n.gte(t):g(n.toNumber(),t);if(t instanceof i)return u(n)?n=i.convert(n):(c(n)||null===n)&&(n=new i(n?1:0)),n instanceof i?n.gte(t):g(n,t.toNumber());if(m(n)&&m(t)){if(!n.equalBase(t))throw new Error("Cannot compare units with different base");return n.value>=t.value}if(h(n)||h(t))return s.deepMap2(n,t,g);if(l(n)||l(t))return n>=t;if(c(n)||null===n)return g(+n,t);if(c(t)||null===t)return g(n,+t);if(p(n)||p(t))throw new TypeError("No ordering relation is defined for complex numbers");throw new e.error.UnsupportedTypeError("largerEq",e["typeof"](n),e["typeof"](t))},e.largereq=function(){throw new Error("Function largereq is renamed to largerEq")}}},function(e,r,n){"use strict";e.exports=function(e,r){var t=n(143),i=e.type.BigNumber,o=n(6),a=n(10),s=n(13),u=t.number.isNumber,f=t.number.nearlyEqual,c=t["boolean"].isBoolean,l=t.string.isString,p=o.isComplex,m=a.isUnit,h=s.isCollection;e.smaller=function g(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("smaller",arguments.length,2);if(u(n)&&u(t))return!f(n,t,r.epsilon)&&t>n;if(n instanceof i)return u(t)?t=i.convert(t):(c(t)||null===t)&&(t=new i(t?1:0)),t instanceof i?n.lt(t):g(n.toNumber(),t);if(t instanceof i)return u(n)?n=i.convert(n):(c(n)||null===n)&&(n=new i(n?1:0)),n instanceof i?n.lt(t):g(n,t.toNumber());if(m(n)&&m(t)){if(!n.equalBase(t))throw new Error("Cannot compare units with different base");return n.value<t.value}if(h(n)||h(t))return s.deepMap2(n,t,g);if(l(n)||l(t))return t>n;if(c(n)||null===n)return g(+n,t);if(c(t)||null===t)return g(n,+t);if(p(n)||p(t))throw new TypeError("No ordering relation is defined for complex numbers");throw new e.error.UnsupportedTypeError("smaller",e["typeof"](n),e["typeof"](t))}}},function(e,r,n){"use strict";e.exports=function(e,r){var t=n(143),i=e.type.BigNumber,o=n(6),a=n(10),s=n(13),u=t.number.isNumber,f=t.number.nearlyEqual,c=t["boolean"].isBoolean,l=t.string.isString,p=o.isComplex,m=a.isUnit,h=s.isCollection;e.smallerEq=function g(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("smallerEq",arguments.length,2);if(u(n)&&u(t))return f(n,t,r.epsilon)||t>n;if(n instanceof i)return u(t)?t=i.convert(t):(c(t)||null===t)&&(t=new i(t?1:0)),t instanceof i?n.lte(t):g(n.toNumber(),t);if(t instanceof i)return u(n)?n=i.convert(n):(c(n)||null===n)&&(n=new i(n?1:0)),n instanceof i?n.lte(t):g(n,t.toNumber());if(m(n)&&m(t)){if(!n.equalBase(t))throw new Error("Cannot compare units with different base");return n.value<=t.value}if(h(n)||h(t))return s.deepMap2(n,t,g);if(l(n)||l(t))return t>=n;if(c(n)||null===n)return g(+n,t);if(c(t)||null===t)return g(n,+t);if(p(n)||p(t))throw new TypeError("No ordering relation is defined for complex numbers");throw new e.error.UnsupportedTypeError("smallerEq",e["typeof"](n),e["typeof"](t))},e.smallereq=function(){throw new Error("Function smallereq is renamed to smallerEq")}}},function(e,r,n){"use strict";e.exports=function(e,r){var t=n(143),i=e.type.BigNumber,o=n(6),a=n(10),s=n(13),u=t.number.isNumber,f=t.number.nearlyEqual,c=t["boolean"].isBoolean,l=t.string.isString,p=o.isComplex,m=a.isUnit,h=s.isCollection;e.unequal=function g(n,t){if(2!=arguments.length)throw new e.error.ArgumentsError("unequal",arguments.length,2);if(u(n)){if(u(t))return!f(n,t,r.epsilon);if(p(t))return!f(n,t.re,r.epsilon)||!f(t.im,0,r.epsilon)}if(p(n)){if(u(t))return!f(n.re,t,r.epsilon)||!f(n.im,0,r.epsilon);if(p(t))return!f(n.re,t.re,r.epsilon)||!f(n.im,t.im,r.epsilon)}if(n instanceof i)return u(t)?t=i.convert(t):c(t)&&(t=new i(t?1:0)),t instanceof i?!n.eq(t):g(n.toNumber(),t);if(t instanceof i)return u(n)?n=i.convert(n):c(n)&&(n=new i(n?1:0)),n instanceof i?!n.eq(t):g(n,t.toNumber());if(m(n)&&m(t)){if(!n.equalBase(t))throw new Error("Cannot compare units with different base");return n.value!=t.value}if(h(n)||h(t))return s.deepMap2(n,t,g);if(l(n)||l(t))return n!=t;if(c(n))return g(+n,t);if(c(t))return g(n,+t);if(null===n)return null!==t;if(null===t)return null!==n;if(void 0===n)return void 0!==t;if(void 0===t)return void 0!==n;throw new e.error.UnsupportedTypeError("unequal",e["typeof"](n),e["typeof"](t))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=o.isCollection,f=i.isComplex;e.arg=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("arg",arguments.length,1);if(a(r))return Math.atan2(0,r);if(f(r))return Math.atan2(r.im,r.re);if(u(r))return o.deepMap(r,c);if(s(r)||null===r)return c(+r);if(r instanceof t)return c(r.toNumber());throw new e.error.UnsupportedTypeError("arg",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.object,s=r.number.isNumber,u=r["boolean"].isBoolean,f=o.isCollection,c=i.isComplex;e.conj=function l(r){if(1!=arguments.length)throw new e.error.ArgumentsError("conj",arguments.length,1);return s(r)?r:r instanceof t?new t(r):c(r)?new i(r.re,-r.im):f(r)?o.deepMap(r,l):u(r)||null===r?+r:a.clone(r)}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.object,s=r.number.isNumber,u=r["boolean"].isBoolean,f=o.isCollection,c=i.isComplex;e.re=function l(r){if(1!=arguments.length)throw new e.error.ArgumentsError("re",arguments.length,1);return s(r)?r:r instanceof t?new t(r):c(r)?r.re:f(r)?o.deepMap(r,l):u(r)||null===r?+r:a.clone(r)}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=o.isCollection,f=i.isComplex;e.im=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("im",arguments.length,1);return a(r)?0:r instanceof t?new t(0):f(r)?r.im:u(r)?o.deepMap(r,c):s(r)||null===r?0:0}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(13),o=i.isCollection,a=r.number.isNumber,s=r.string.isString,u=r["boolean"].isBoolean;e.bignumber=function f(r){if(arguments.length>1)throw new e.error.ArgumentsError("bignumber",arguments.length,0,1);if(r instanceof t||a(r)||s(r))return new t(r);if(u(r)||null===r)return new t(+r);if(o(r))return i.deepMap(r,f);if(0==arguments.length)return new t(0);throw new e.error.UnsupportedTypeError("bignumber",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(13),o=i.isCollection,a=r.number.isNumber,s=r.string.isString;e["boolean"]=function u(r){if(1!=arguments.length)throw new e.error.ArgumentsError("boolean",arguments.length,0,1);if("true"===r||r===!0)return!0;if("false"===r||r===!1||null===r)return!1;if(r instanceof Boolean)return 1==r;if(a(r))return 0!==r;if(r instanceof t)return!r.isZero();if(s(r)){var n=r.toLowerCase();if("true"===n)return!0;if("false"===n)return!1;var f=Number(r);if(""!=r&&!isNaN(f))return 0!==f}if(o(r))return i.deepMap(r,u);throw new SyntaxError(r.toString()+" is no valid boolean")}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=o.isCollection,s=r.number.isNumber,u=r.string.isString,f=i.isComplex;e.complex=function c(){switch(arguments.length){case 0:return new i(0,0);case 1:var r=arguments[0];if(s(r))return new i(r,0);if(r instanceof t)return new i(r.toNumber(),0);if(f(r))return r.clone();if(u(r)){var n=i.parse(r);if(n)return n;throw new SyntaxError('String "'+r+'" is no valid complex number')}if(a(r))return o.deepMap(r,c);if("object"==typeof r){if("re"in r&&"im"in r)return new i(r.re,r.im);if("r"in r&&"phi"in r)return i.fromPolar(r.r,r.phi)}throw new TypeError("Two numbers, single string or an fitting object expected in function complex");case 2:var l=arguments[0],p=arguments[1];if(l instanceof t&&(l=l.toNumber()),p instanceof t&&(p=p.toNumber()),s(l)&&s(p))return new i(l,p);throw new TypeError("Two numbers or a single string expected in function complex");default:throw new e.error.ArgumentsError("complex",arguments.length,0,2)}}}},function(e,r,n){"use strict";e.exports=function(e){var r=(n(143),e.type.BigNumber),t=n(8);e.index=function(){var e=Array.prototype.slice.apply(arguments).map(function(e){return e instanceof r?e.toNumber():Array.isArray(e)?e.map(function(e){return e instanceof r?e.toNumber():e}):e}),n=new t;return t.apply(n,e),n}}},function(e,r,n){"use strict";e.exports=function(e){var r=(n(143),n(9));e.matrix=function(n){if(arguments.length>1)throw new e.error.ArgumentsError("matrix",arguments.length,0,1);return new r(n)}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(13),o=i.isCollection,a=r.number.isNumber,s=r["boolean"].isBoolean,u=r.string.isString;e.number=function f(r){switch(arguments.length){case 0:return 0;case 1:if(o(r))return i.deepMap(r,f);if(r instanceof t)return r.toNumber();if(u(r)){var n=Number(r);if(isNaN(n)&&(n=Number(r.valueOf())),isNaN(n))throw new SyntaxError(r.toString()+" is no valid number");return n}if(s(r)||null===r)return+r;if(a(r))return r;throw new e.error.UnsupportedTypeError("number",e["typeof"](r));default:throw new e.error.ArgumentsError("number",arguments.length,0,1)}}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(15);e.parser=function(){return new r(e)}}},function(e){"use strict";e.exports=function(e){e.select=function(r){return new e.chaining.Selector(r)}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=n(13),i=r.number,o=r.number.isNumber,a=t.isCollection;e.string=function s(r){switch(arguments.length){case 0:return"";case 1:return o(r)?i.format(r):a(r)?t.deepMap(r,s):null===r?"null":r.toString();default:throw new e.error.ArgumentsError("string",arguments.length,0,1)}}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(10),o=n(13),a=o.isCollection,s=r.string.isString;e.unit=function u(r){switch(arguments.length){case 1:var n=arguments[0];if(n instanceof i)return n.clone();if(s(n)){if(i.isValuelessUnit(n))return new i(null,n);var f=i.parse(n);if(f)return f;throw new SyntaxError('String "'+n+'" is no valid unit')}if(a(r))return o.deepMap(r,u);throw new TypeError("A string or a number and string expected in function unit");case 2:return arguments[0]instanceof t?new i(arguments[0].toNumber(),arguments[1]):new i(arguments[0],arguments[1]);default:throw new e.error.ArgumentsError("unit",arguments.length,1,2)}}}},function(e,r,n){"use strict";e.exports=function(e){function r(n,t,i,o){if(i>o){if(n.length!=t.length)throw new e.error.DimensionError(n.length,t.length);for(var a=[],s=0;s<n.length;s++)a[s]=r(n[s],t[s],i,o+1);return a}return n.concat(t)}var t=n(143),i=n(142),o=n(9),a=n(13),s=t.object,u=t.array,f=t.number.isNumber,c=t.number.isInteger,l=a.isCollection;e.concat=function(){var n,t,a=arguments.length,p=-1,m=!1,h=[];for(n=0;a>n;n++){var g=arguments[n];if(g instanceof o&&(m=!0),n==a-1&&(f(g)||g instanceof i)){if(t=p,p=g.valueOf(),!c(p))throw new TypeError("Integer number expected for dimension");if(0>p)throw new e.error.IndexError(p);if(n>0&&p>t)throw new e.error.IndexError(p,t+1)}else{if(!l(g))throw new e.error.UnsupportedTypeError("concat",e["typeof"](g));var d=s.clone(g).valueOf(),x=u.size(g.valueOf());if(h[n]=d,t=p,p=x.length-1,n>0&&p!=t)throw new e.error.DimensionError(t+1,p+1)}}if(0==h.length)throw new SyntaxError("At least one matrix expected");for(var y=h.shift();h.length;)y=r(y,h.shift(),p,0);return m?new o(y):y}}},function(e,r,n){"use strict";e.exports=function(e){function r(r,n){if(1==n)return o.clone(r[0][0]);if(2==n)return e.subtract(e.multiply(r[0][0],r[1][1]),e.multiply(r[1][0],r[0][1]));for(var t=function(r){var n,t,i=new Array(r.length),o=0;for(n=1;n<r.length;n++)o=e.add(o,r[n][n]);for(n=0;n<r.length;n++){for(i[n]=new Array(r.length),i[n][n]=e.unaryMinus(o),t=0;n>t;t++)i[n][t]=0;for(t=n+1;t<r.length;t++)i[n][t]=r[n][t];n+1<r.length&&(o=e.subtract(o,r[n+1][n+1]))}return i},i=r,a=0;n-1>a;a++)i=e.multiply(t(i),r);return n%2==0?e.unaryMinus(i[0][0]):i[0][0]}var t=n(143),i=n(9),o=t.object,a=t.string;e.det=function(n){if(1!=arguments.length)throw new e.error.ArgumentsError("det",arguments.length,1);var t;switch(n instanceof i?t=n.size():n instanceof Array?(n=new i(n),t=n.size()):t=[],t.length){case 0:return o.clone(n);case 1:if(1==t[0])return o.clone(n.valueOf()[0]);throw new RangeError("Matrix must be square (size: "+a.format(t)+")");case 2:var s=t[0],u=t[1];if(s==u)return r(n.clone().valueOf(),s,u);throw new RangeError("Matrix must be square (size: "+a.format(t)+")");default:throw new RangeError("Matrix must be two dimensional (size: "+a.format(t)+")")}}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(9),o=r.object,a=r.array.isArray,s=r.number.isNumber,u=r.number.isInteger;e.diag=function(r,n){var f,c,l,p;if(1!=arguments.length&&2!=arguments.length)throw new e.error.ArgumentsError("diag",arguments.length,1,2);if(n){if(n instanceof t&&(n=n.toNumber()),!s(n)||!u(n))throw new TypeError("Second parameter in function diag must be an integer")}else n=0;var m,h=n>0?n:0,g=0>n?-n:0;if(r instanceof i)m=!1;else{if(!a(r))throw new TypeError("First parameter in function diag must be a Matrix or Array");r=new i(r),m=!0}var d=r.size();switch(d.length){case 1:c=r.valueOf();var x=new i,y=c[0]instanceof t?new t(0):0;for(x.resize([c.length+g,c.length+h],y),f=x.valueOf(),p=c.length,l=0;p>l;l++)f[l+g][l+h]=o.clone(c[l]);return m?x.valueOf():x;case 2:for(c=[],f=r.valueOf(),p=Math.min(d[0]-g,d[1]-h),l=0;p>l;l++)c[l]=o.clone(f[l+g][l+h]);return m?c:new i(c);default:throw new RangeError("Matrix for function diag must be 2 dimensional")}}}},function(e,r,n){"use strict";e.exports=function(e,r){var t=n(143),i=e.type.BigNumber,o=n(9),a=n(13),s=t.number.isNumber,u=t.number.isInteger,f=Array.isArray;e.eye=function(n){var t=a.argsToArray(arguments),c=n instanceof o?!0:f(n)?!1:"matrix"===r.matrix;if(0==t.length)return c?new o:[];if(1==t.length)t[1]=t[0];else if(t.length>2)throw new e.error.ArgumentsError("eye",t.length,0,2);var l=t[0],p=t[1];if(l instanceof i&&(l=l.toNumber()),p instanceof i&&(p=p.toNumber()),!s(l)||!u(l)||1>l)throw new Error("Parameters in function eye must be positive integers");if(!s(p)||!u(p)||1>p)throw new Error("Parameters in function eye must be positive integers");var m=!1;t=t.map(function(e){return e instanceof i?(m=!0,e.toNumber()):e});var h=new o,g=m?new i(1):1,d=m?new i(0):0;h.resize(t,d);for(var x=e.min(t),y=h.valueOf(),w=0;x>w;w++)y[w][w]=g;return c?h:h.valueOf()}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=n(9),i=r.object,o=r.array,a=Array.isArray;e.flatten=function(r){if(1!==arguments.length)throw new e.error.ArgumentsError("flatten",arguments.length,1);if(r instanceof t){var n=i.clone(r.toArray()),s=o.flatten(n);return new t(s)}if(a(r))return o.flatten(i.clone(r));throw new e.error.UnsupportedTypeError("flatten",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){function r(r,n,t){var i,o,a,s,u;if(1==n){if(s=r[0][0],0==s)throw Error("Cannot calculate inverse, determinant is zero");return[[e.divide(1,s)]]}if(2==n){var f=e.det(r);if(0==f)throw Error("Cannot calculate inverse, determinant is zero");return[[e.divide(r[1][1],f),e.divide(e.unaryMinus(r[0][1]),f)],[e.divide(e.unaryMinus(r[1][0]),f),e.divide(r[0][0],f)]]}var c=r.concat();for(i=0;n>i;i++)c[i]=c[i].concat();for(var l=e.eye(n).valueOf(),p=0;t>p;p++){for(i=p;n>i&&0==c[i][p];)i++;if(i==n||0==c[i][p])throw Error("Cannot calculate inverse, determinant is zero");i!=p&&(u=c[p],c[p]=c[i],c[i]=u,u=l[p],l[p]=l[i],l[i]=u);var m=c[p],h=l[p];for(i=0;n>i;i++){var g=c[i],d=l[i];if(i!=p){if(0!=g[p]){for(a=e.divide(e.unaryMinus(g[p]),m[p]),o=p;t>o;o++)g[o]=e.add(g[o],e.multiply(a,m[o]));for(o=0;t>o;o++)d[o]=e.add(d[o],e.multiply(a,h[o]))}}else{for(a=m[p],o=p;t>o;o++)g[o]=e.divide(g[o],a);for(o=0;t>o;o++)d[o]=e.divide(d[o],a)}}}return l}var t=n(143),i=t.string,o=n(9);e.inv=function(n){if(1!=arguments.length)throw new e.error.ArgumentsError("inv",arguments.length,1);var t=e.size(n).valueOf();switch(t.length){case 0:return e.divide(1,n);case 1:if(1==t[0])return n instanceof o?new o([e.divide(1,n.valueOf()[0])]):[e.divide(1,n[0])];throw new RangeError("Matrix must be square (size: "+i.format(t)+")");case 2:var a=t[0],s=t[1];if(a==s)return n instanceof o?new o(r(n.valueOf(),a,s)):r(n,a,s);throw new RangeError("Matrix must be square (size: "+i.format(t)+")");default:throw new RangeError("Matrix must be two dimensional (size: "+i.format(t)+")")}}}},function(e,r,n){"use strict";e.exports=function(e,r){var t=n(143),i=e.type.BigNumber,o=n(9),a=n(13),s=t.array,u=Array.isArray;e.ones=function(e){var n=a.argsToArray(arguments),t=e instanceof o?!0:u(e)?!1:"matrix"===r.matrix;if(0==n.length)return t?new o:[];var f=!1;n=n.map(function(e){return e instanceof i?(f=!0,e.toNumber()):e});var c=[],l=f?new i(1):1;return c=s.resize(c,n,l),t?new o(c):c}}},function(e,r,n){"use strict";e.exports=function(e,r){function t(e,r,n){var t=[],i=e;if(n>0)for(;r>i;)t.push(i),i+=n;else if(0>n)for(;i>r;)t.push(i),i+=n;return t}function i(e,r,n){var t=[],i=e;if(n>0)for(;r>=i;)t.push(i),i+=n;else if(0>n)for(;i>=r;)t.push(i),i+=n;return t}function o(e,r,n){var t=[],i=e.clone(),o=new f(0);if(n.gt(o))for(;i.lt(r);)t.push(i),i=i.plus(n);else if(n.lt(o))for(;i.gt(r);)t.push(i),i=i.plus(n);return t}function a(e,r,n){var t=[],i=e.clone(),o=new f(0);if(n.gt(o))for(;i.lte(r);)t.push(i),i=i.plus(n);else if(n.lt(o))for(;i.gte(r);)t.push(i),i=i.plus(n);return t}function s(e){var n=e.split(":"),t=null;if("bignumber"===r.number)try{t=n.map(function(e){return new f(e)})}catch(i){return null}else{t=n.map(function(e){return Number(e)});var o=t.some(function(e){return isNaN(e)});if(o)return null}switch(t.length){case 2:return{start:t[0],end:t[1],step:1};case 3:return{start:t[0],end:t[2],step:t[1]};default:return null}}var u=n(143),f=e.type.BigNumber,c=n(9),l=(n(13),u["boolean"].isBoolean),p=u.string.isString,m=u.number.isNumber;e.range=function(){var n,u,h,g=Array.prototype.slice.call(arguments),d=!1;
switch(l(g[g.length-1])&&(d=g.pop()?!0:!1),g.length){case 1:if(!p(g[0]))throw new TypeError("Two or three numbers or a single string expected in function range");var x=s(g[0]);if(!x)throw new SyntaxError('String "'+g[0]+'" is no valid range');n=x.start,u=x.end,h=x.step;break;case 2:n=g[0],u=g[1],h=1;break;case 3:n=g[0],u=g[1],h=g[2];break;case 4:throw new TypeError("Parameter includeEnd must be a boolean");default:throw new e.error.ArgumentsError("range",arguments.length,2,4)}if(!(m(n)||n instanceof f))throw new TypeError("Parameter start must be a number");if(!(m(u)||u instanceof f))throw new TypeError("Parameter end must be a number");if(!(m(h)||h instanceof f))throw new TypeError("Parameter step must be a number");if(n instanceof f||u instanceof f||h instanceof f){var y=!0;n instanceof f||(n=f.convert(n)),u instanceof f||(u=f.convert(u)),h instanceof f||(h=f.convert(h)),n instanceof f&&u instanceof f&&h instanceof f||(y=!1,n instanceof f&&(n=n.toNumber()),u instanceof f&&(u=u.toNumber()),h instanceof f&&(h=h.toNumber()))}var w=y?d?a:o:d?i:t,v=w(n,u,h);return"array"===r.matrix?v:new c(v)}}},function(e,r,n){"use strict";e.exports=function(e,r){function t(r,n,t){if(void 0!==t){if(!c(t)||1!==t.length)throw new TypeError("Single character expected as defaultValue")}else t=" ";if(1!==n.length)throw new e.error.DimensionError(n.length,1);var i=n[0];if(!l(i)||!p(i))throw new TypeError("Invalid size, must contain positive integers (size: "+f.format(n)+")");if(r.length>i)return r.substring(0,i);if(r.length<i){for(var o=r,a=0,s=i-r.length;s>a;a++)o+=t;return o}return r}var i=n(143),o=e.type.BigNumber,a=n(9),s=i.array,u=i.object.clone,f=i.string,c=i.string.isString,l=i.number.isNumber,p=i.number.isInteger,m=s.isArray;e.resize=function(n,i,f){if(2!=arguments.length&&3!=arguments.length)throw new e.error.ArgumentsError("resize",arguments.length,2,3);var l=n instanceof a?!0:m(n)?!1:"array"!==r.matrix;if(n instanceof a&&(n=n.valueOf()),i instanceof a&&(i=i.valueOf()),i.length&&i[0]instanceof o&&(i=i.map(function(e){return e instanceof o?e.toNumber():e})),c(n))return t(n,i,f);if(0==i.length){for(;m(n);)n=n[0];return u(n)}m(n)||(n=[n]),n=u(n);var p=s.resize(n,i,f);return l?new a(p):p}}},function(e,r,n){"use strict";e.exports=function(e,r){var t=n(143),i=e.type.BigNumber,o=n(6),a=n(10),s=n(9),u=t.array,f=t.number.isNumber,c=t["boolean"].isBoolean,l=t.string.isString,p=o.isComplex,m=a.isUnit;e.size=function(n){if(1!=arguments.length)throw new e.error.ArgumentsError("size",arguments.length,1);var t="array"===r.matrix;if(f(n)||p(n)||m(n)||c(n)||null==n||n instanceof i)return t?[]:new s([]);if(l(n))return t?[n.length]:new s([n.length]);if(Array.isArray(n))return u.size(n);if(n instanceof s)return new s(n.size());throw new e.error.UnsupportedTypeError("size",e["typeof"](n))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=n(9),i=r.object,o=r.array,a=Array.isArray;e.squeeze=function(r){if(1!=arguments.length)throw new e.error.ArgumentsError("squeeze",arguments.length,1);if(a(r))return o.squeeze(i.clone(r));if(r instanceof t){var n=o.squeeze(r.toArray());return a(n)?new t(n):n}return i.clone(r)}}},function(e,r,n){"use strict";e.exports=function(e){function r(r,n){var i,o;if(l(r))return i=new s(r),o=i.subset(n),o.valueOf();if(r instanceof s)return r.subset(n);if(c(r))return t(r,n);throw new e.error.UnsupportedTypeError("subset",e["typeof"](r))}function t(r,n){if(!(n instanceof u))throw new TypeError("Index expected");if(1!=n.size().length)throw new e.error.DimensionError(n.size().length,1);var t=r.length;f.validateIndex(n.min()[0],t),f.validateIndex(n.max()[0],t);var i=n.range(0),o="";return i.forEach(function(e){o+=r.charAt(e)}),o}function i(r,n,t,i){var a;if(l(r))return a=new s(e.clone(r)),a.subset(n,t,i),a.valueOf();if(r instanceof s)return r.clone().subset(n,t,i);if(c(r))return o(r,n,t,i);throw new e.error.UnsupportedTypeError("subset",e["typeof"](r))}function o(r,n,t,i){if(!(n instanceof u))throw new TypeError("Index expected");if(1!=n.size().length)throw new e.error.DimensionError(n.size().length,1);if(void 0!==i){if(!c(i)||1!==i.length)throw new TypeError("Single character expected as defaultValue")}else i=" ";var o=n.range(0),a=o.size()[0];if(a!=t.length)throw new e.error.DimensionError(o.size()[0],t.length);var s=r.length;f.validateIndex(n.min()[0]),f.validateIndex(n.max()[0]);for(var l=[],p=0;s>p;p++)l[p]=r.charAt(p);if(o.forEach(function(e,r){l[e]=t.charAt(r)}),l.length>s)for(p=s-1,a=l.length;a>p;p++)l[p]||(l[p]=i);return l.join("")}var a=n(143),s=n(9),u=n(8),f=a.array,c=a.string.isString,l=Array.isArray;e.subset=function(){switch(arguments.length){case 2:return r(arguments[0],arguments[1]);case 3:case 4:return i(arguments[0],arguments[1],arguments[2],arguments[3]);default:throw new e.error.ArgumentsError("subset",arguments.length,2,4)}}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=n(9),i=r.object,o=r.string;e.transpose=function(r){if(1!=arguments.length)throw new e.error.ArgumentsError("transpose",arguments.length,1);var n=e.size(r).valueOf();switch(n.length){case 0:return i.clone(r);case 1:return i.clone(r);case 2:var a,s=n[1],u=n[0],f=r instanceof t,c=r.valueOf(),l=[],p=i.clone;if(0===s)throw new RangeError("Cannot transpose a 2D matrix with no rows(size: "+o.format(n)+")");for(var m=0;s>m;m++){a=l[m]=[];for(var h=0;u>h;h++)a[h]=p(c[h][m])}return f?new t(l):l;default:throw new RangeError("Matrix must be two dimensional (size: "+o.format(n)+")")}}}},function(e,r,n){"use strict";e.exports=function(e,r){var t=n(143),i=e.type.BigNumber,o=n(9),a=n(13),s=t.array,u=Array.isArray;e.zeros=function(e){var n=a.argsToArray(arguments),t=e instanceof o?!0:u(e)?!1:"matrix"===r.matrix;if(0==n.length)return t?new o:[];var f=!1;n=n.map(function(e){return e instanceof i?(f=!0,e.toNumber()):e});var c=[],l=f?new i(0):0;return c=s.resize(c,n,l),t?new o(c):c}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(9),t=n(136),i=n(13),o=i.isCollection;e.distribution=function(n){if(!a.hasOwnProperty(n))throw new Error("Unknown distribution "+n);var i=Array.prototype.slice.call(arguments,1),s=a[n].apply(this,i);return function(n){var i={random:function(n,t,i){var s,f,c;if(arguments.length>3)throw new e.error.ArgumentsError("random",arguments.length,0,3);if(1===arguments.length?o(n)?s=n:c=n:2===arguments.length?o(n)?(s=n,c=t):(f=n,c=t):(s=n,f=t,c=i),void 0===c&&(c=1),void 0===f&&(f=0),void 0!==s){var l=u(s.valueOf(),f,c,a);return s instanceof r?new r(l):l}return a(f,c)},randomInt:function(n,t,i){var a,f,c;if(arguments.length>3||arguments.length<1)throw new e.error.ArgumentsError("randomInt",arguments.length,1,3);if(1===arguments.length?o(n)?a=n:c=n:2===arguments.length?o(n)?(a=n,c=t):(f=n,c=t):(a=n,f=t,c=i),void 0===f&&(f=0),void 0!==a){var l=u(a.valueOf(),f,c,s);return a instanceof r?new r(l):l}return s(f,c)},pickRandom:function(n){if(1!==arguments.length)throw new e.error.ArgumentsError("pickRandom",arguments.length,1);if(n instanceof r)n=n.valueOf();else if(!Array.isArray(n))throw new e.error.UnsupportedTypeError("pickRandom",e["typeof"](n));if(t.size(n).length>1)throw new Error("Only one dimensional vectors supported");return n[Math.floor(Math.random()*n.length)]}},a=function(e,r){return e+n()*(r-e)},s=function(e,r){return Math.floor(e+n()*(r-e))},u=function(e,r,n,t){var i,o,a=[];if(e=e.slice(0),e.length>1)for(o=0,i=e.shift();i>o;o++)a.push(u(e,r,n,t));else for(o=0,i=e.shift();i>o;o++)a.push(t(r,n));return a};return i}(s)};var a={uniform:function(){return Math.random},normal:function(){return function(){for(var e,r,n=-1;0>n||n>1;)e=Math.random(),r=Math.random(),n=1/6*Math.pow(-2*Math.log(e),.5)*Math.cos(2*Math.PI*r)+.5;return n}}}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(13),o=r.number.isNumber,a=r["boolean"].isBoolean,s=r.number.isInteger,u=i.isCollection;e.factorial=function c(r){var n,l;if(1!=arguments.length)throw new e.error.ArgumentsError("factorial",arguments.length,1);if(o(r)){if(!s(r)||0>r)throw new TypeError("Positive integer value expected in function factorial");for(n=r-1,l=r;n>1;)l*=n,n--;return 0==l&&(l=1),l}if(r instanceof t){if(!f(r))throw new TypeError("Positive integer value expected in function factorial");var p=new t(1);for(n=r.minus(p),l=r;n.gt(p);)l=l.times(n),n=n.minus(p);return l.equals(0)&&(l=p),l}if(a(r)||null===r)return 1;if(u(r))return i.deepMap(r,c);throw new e.error.UnsupportedTypeError("factorial",e["typeof"](r))};var f=function(e){return e.isInteger()&&e.gte(0)}}},function(e){"use strict";e.exports=function(e){e.random=e.distribution("uniform").random}},function(e){"use strict";e.exports=function(e){e.randomInt=e.distribution("uniform").randomInt}},function(e){"use strict";e.exports=function(e){e.distribution("uniform");e.pickRandom=e.distribution("uniform").pickRandom}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=r.number.isNumber,o=r.number.isInteger;e.permutations=function(r,n){var s,u,f=arguments.length;if(f>2)throw new e.error.ArgumentsError("permutations",arguments.length,2);if(i(r)){if(!o(r)||0>r)throw new TypeError("Positive integer value expected in function permutations");if(1==f)return e.factorial(r);if(2==f&&i(n)){if(!o(n)||0>n)throw new TypeError("Positive integer value expected in function permutations");if(n>r)throw new TypeError("second argument k must be less than or equal to first argument n");for(s=1,u=r-n+1;r>=u;u++)s*=u;return s}}if(r instanceof t){if(void 0===n&&a(r))return e.factorial(r);if(n=t.convert(n),!(n instanceof t&&a(r)&&a(n)))throw new TypeError("Positive integer value expected in function permutations");if(n.gt(r))throw new TypeError("second argument k must be less than or equal to first argument n");for(s=new t(1),u=r.minus(n).plus(1);u.lte(r);u=u.plus(1))s=s.times(u);return s}throw new e.error.UnsupportedTypeError("permutations",e["typeof"](r))};var a=function(e){return e.isInteger()&&e.gte(0)}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=(n(13),r.number.isNumber),o=r.number.isInteger;e.combinations=function(r,n){var s,u,f,c,l=arguments.length;if(2!=l)throw new e.error.ArgumentsError("combinations",arguments.length,2);if(i(r)){if(!o(r)||0>r)throw new TypeError("Positive integer value enpected in function combinations");if(n>r)throw new TypeError("k must be less than or equal to n");for(s=Math.max(n,r-n),u=1,f=1;r-s>=f;f++)u=u*(s+f)/f;return u}if(r instanceof t){if(n=t.convert(n),!(n instanceof t&&a(r)&&a(n)))throw new TypeError("Positive integer value expected in function combinations");if(n.gt(r))throw new TypeError("k must be less than n in function combinations");for(s=r.minus(n),n.lt(s)&&(s=n),u=new t(1),f=new t(1),c=r.minus(s);f.lte(c);f=f.plus(1))u=u.times(s.plus(f)).dividedBy(f);return u}throw new e.error.UnsupportedTypeError("combinations",e["typeof"](r))};var a=function(e){return e.isInteger()&&e.gte(0)}}},function(e,r,n){"use strict";e.exports=function(e){function r(r,n){return e.smaller(r,n)?r:n}function t(r){var n=void 0;if(i.deepForEach(r,function(r){(void 0===n||e.smaller(r,n))&&(n=r)}),void 0===n)throw new Error("Cannot calculate min of an empty array");return n}var i=(n(9),n(13)),o=i.isCollection;e.min=function(e){if(0==arguments.length)throw new SyntaxError("Function min requires one or more parameters (0 provided)");if(o(e)){if(1==arguments.length)return t(e);if(2==arguments.length)return i.reduce(arguments[0],arguments[1],r);throw new SyntaxError("Wrong number of parameters")}return t(arguments)}}},function(e,r,n){"use strict";e.exports=function(e){function r(r,n){return e.larger(r,n)?r:n}function t(r){var n=void 0;if(i.deepForEach(r,function(r){(void 0===n||e.larger(r,n))&&(n=r)}),void 0===n)throw new Error("Cannot calculate max of an empty array");return n}var i=(n(9),n(13)),o=i.isCollection;e.max=function(e){if(0==arguments.length)throw new SyntaxError("Function max requires one or more parameters (0 provided)");if(o(e)){if(1==arguments.length)return t(e);if(2==arguments.length)return i.reduce(arguments[0],arguments[1],r);throw new SyntaxError("Wrong number of parameters")}return t(arguments)}}},function(e,r,n){"use strict";e.exports=function(e){function r(r,n){var t=i.reduce(r,n,e.add),o=s(r)?a(r):r.size();return e.divide(t,o[n])}function t(r){var n=0,t=0;if(i.deepForEach(r,function(r){n=e.add(n,r),t++}),0===t)throw new Error("Cannot calculate mean of an empty array");return e.divide(n,t)}var i=(n(9),n(13)),o=i.isCollection,a=n(136).size,s=Array.isArray;e.mean=function(e){if(0==arguments.length)throw new SyntaxError("Function mean requires one or more parameters (0 provided)");if(o(e)){if(1==arguments.length)return t(e);if(2==arguments.length)return r(arguments[0],arguments[1]);throw new SyntaxError("Wrong number of parameters")}return t(arguments)}}},function(e,r,n){"use strict";e.exports=function(e){function r(r){var n=u(r);n.sort(e.compare);var o=n.length;if(0==o)throw new Error("Cannot calculate median of an empty array");if(o%2==0){var s=n[o/2-1],f=n[o/2];if(!(a(s)||s instanceof i||s instanceof t))throw new e.error.UnsupportedTypeError("median",e["typeof"](s));if(!(a(f)||f instanceof i||f instanceof t))throw new e.error.UnsupportedTypeError("median",e["typeof"](f));return e.divide(e.add(s,f),2)}var c=n[(o-1)/2];if(!(a(c)||c instanceof i||c instanceof t))throw new e.error.UnsupportedTypeError("median",e["typeof"](c));return c}var t=(n(9),n(10)),i=e.type.BigNumber,o=n(13),a=n(4).isNumber,s=o.isCollection,u=n(136).flatten;e.median=function(e){if(0==arguments.length)throw new SyntaxError("Function median requires one or more parameters (0 provided)");if(s(e)){if(1==arguments.length)return r(e.valueOf());throw 2==arguments.length?new Error("median(A, dim) is not yet supported"):new SyntaxError("Wrong number of parameters")}return r(Array.prototype.slice.call(arguments))}}},function(e,r,n){"use strict";e.exports=function(e){function r(r){var n=void 0;if(t.deepForEach(r,function(r){n=void 0===n?r:e.multiply(n,r)}),void 0===n)throw new Error("Cannot calculate prod of an empty array");return n}var t=(n(9),n(13)),i=t.isCollection;e.prod=function(e){if(0==arguments.length)throw new SyntaxError("Function prod requires one or more parameters (0 provided)");if(i(e)){if(1==arguments.length)return r(e);throw 2==arguments.length?new Error("prod(A, dim) is not yet supported"):new SyntaxError("Wrong number of parameters")}return r(arguments)}}},function(e){"use strict";e.exports=function(e){e.std=function(){if(0==arguments.length)throw new SyntaxError("Function std requires one or more parameters (0 provided)");var r=e["var"].apply(null,arguments);return e.sqrt(r)}}},function(e,r,n){"use strict";e.exports=function(e){function r(r){var n=void 0;if(t.deepForEach(r,function(r){n=void 0===n?r:e.add(n,r)}),void 0===n)throw new Error("Cannot calculate sum of an empty array");return n}var t=(n(9),n(13)),i=t.isCollection;e.sum=function(e){if(0==arguments.length)throw new SyntaxError("Function sum requires one or more parameters (0 provided)");if(i(e)){if(1==arguments.length)return r(e);throw 2==arguments.length?new Error("sum(A, dim) is not yet supported"):new SyntaxError("Wrong number of parameters")}return r(arguments)}}},function(e,r,n){"use strict";e.exports=function(e){function r(r,n){var o=0,a=0;if(i.deepForEach(r,function(r){o=e.add(o,r),a++}),0===a)throw new Error("Cannot calculate var of an empty array");var s=e.divide(o,a);switch(o=0,i.deepForEach(r,function(r){var n=e.subtract(r,s);o=e.add(o,e.multiply(n,n))}),n){case"uncorrected":return e.divide(o,a);case"biased":return e.divide(o,a+1);case"unbiased":var u=o instanceof t?new t(0):0;return 1==a?u:e.divide(o,a-1);default:throw new Error('Unknown normalization "'+n+'". Choose "unbiased" (default), "uncorrected", or "biased".')}}var t=(n(9),e.type.BigNumber),i=n(13),o=i.isCollection,a=n(159).isString,s="unbiased";e["var"]=function(e,n){if(0==arguments.length)throw new SyntaxError("Function var requires one or more parameters (0 provided)");if(o(e)){if(1==arguments.length)return r(e,s);if(2==arguments.length){if(!a(n))throw new Error("String expected for parameter normalization");return r(e,n)}throw new SyntaxError("Wrong number of parameters")}return r(arguments,s)}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=i.isComplex,f=o.isCollection;e.acos=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("acos",arguments.length,1);if(a(r))return r>=-1&&1>=r?Math.acos(r):c(new i(r,0));if(u(r)){var n=new i(r.im*r.im-r.re*r.re+1,-2*r.re*r.im),l=e.sqrt(n),p=new i(l.re-r.im,l.im+r.re),m=e.log(p);return new i(1.5707963267948966-m.im,m.re)}if(f(r))return o.deepMap(r,c);if(s(r)||null===r)return Math.acos(r);if(r instanceof t)return c(r.toNumber());throw new e.error.UnsupportedTypeError("acos",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=i.isComplex,f=o.isCollection;e.asin=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("asin",arguments.length,1);if(a(r))return r>=-1&&1>=r?Math.asin(r):c(new i(r,0));if(u(r)){var n=r.re,l=r.im,p=new i(l*l-n*n+1,-2*n*l),m=e.sqrt(p),h=new i(m.re-l,m.im+n),g=e.log(h);return new i(g.im,-g.re)}if(f(r))return o.deepMap(r,c);if(s(r)||null===r)return Math.asin(r);if(r instanceof t)return c(r.toNumber());throw new e.error.UnsupportedTypeError("asin",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=i.isComplex,f=o.isCollection;e.atan=function c(r){if(1!=arguments.length)throw new e.error.ArgumentsError("atan",arguments.length,1);if(a(r))return Math.atan(r);if(u(r)){var n=r.re,l=r.im,p=n*n+(1-l)*(1-l),m=new i((1-l*l-n*n)/p,-2*n/p),h=e.log(m);return new i(-.5*h.im,.5*h.re)}if(f(r))return o.deepMap(r,c);if(s(r)||null===r)return Math.atan(r);if(r instanceof t)return c(r.toNumber());throw new e.error.UnsupportedTypeError("atan",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(13),a=r.number.isNumber,s=r["boolean"].isBoolean,u=(i.isComplex,o.isCollection);e.atan2=function f(r,n){if(2!=arguments.length)throw new e.error.ArgumentsError("atan2",arguments.length,2);if(a(r)&&a(n))return Math.atan2(r,n);if(u(r)||u(n))return o.deepMap2(r,n,f);if(s(r)||null===r)return f(+r,n);if(s(n)||null===n)return f(r,+n);if(r instanceof t)return f(r.toNumber(),n);if(n instanceof t)return f(r,n.toNumber());throw new e.error.UnsupportedTypeError("atan2",e["typeof"](r),e["typeof"](n))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(10),a=n(13),s=r.number.isNumber,u=r["boolean"].isBoolean,f=i.isComplex,c=o.isUnit,l=a.isCollection;e.cos=function p(r){if(1!=arguments.length)throw new e.error.ArgumentsError("cos",arguments.length,1);if(s(r))return Math.cos(r);if(f(r))return new i(.5*Math.cos(r.re)*(Math.exp(-r.im)+Math.exp(r.im)),.5*Math.sin(r.re)*(Math.exp(-r.im)-Math.exp(r.im)));if(c(r)){if(!r.hasBase(o.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cos is no angle");return Math.cos(r.value)}if(l(r))return a.deepMap(r,p);if(u(r)||null===r)return Math.cos(r);if(r instanceof t)return p(r.toNumber());throw new e.error.UnsupportedTypeError("cos",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(10),a=n(13),s=r.number.isNumber,u=r["boolean"].isBoolean,f=i.isComplex,c=o.isUnit,l=a.isCollection;e.cosh=function p(r){if(1!=arguments.length)throw new e.error.ArgumentsError("cosh",arguments.length,1);if(s(r))return(Math.exp(r)+Math.exp(-r))/2;if(f(r)){var n=Math.exp(r.re),m=Math.exp(-r.re);return new i(Math.cos(r.im)*(n+m)/2,Math.sin(r.im)*(n-m)/2)}if(c(r)){if(!r.hasBase(o.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cosh is no angle");return p(r.value)}if(l(r))return a.deepMap(r,p);if(u(r)||null===r)return p(r?1:0);if(r instanceof t)return p(r.toNumber());throw new e.error.UnsupportedTypeError("cosh",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(10),a=n(13),s=r.number.isNumber,u=r["boolean"].isBoolean,f=i.isComplex,c=o.isUnit,l=a.isCollection;e.cot=function p(r){if(1!=arguments.length)throw new e.error.ArgumentsError("cot",arguments.length,1);if(s(r))return 1/Math.tan(r);if(f(r)){var n=Math.exp(-4*r.im)-2*Math.exp(-2*r.im)*Math.cos(2*r.re)+1;return new i(2*Math.exp(-2*r.im)*Math.sin(2*r.re)/n,(Math.exp(-4*r.im)-1)/n)}if(c(r)){if(!r.hasBase(o.BASE_UNITS.ANGLE))throw new TypeError("Unit in function cot is no angle");return 1/Math.tan(r.value)}if(l(r))return a.deepMap(r,p);if(u(r)||null===r)return p(+r);if(r instanceof t)return p(r.toNumber());throw new e.error.UnsupportedTypeError("cot",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(10),a=n(13),s=r.number.isNumber,u=r["boolean"].isBoolean,f=i.isComplex,c=o.isUnit,l=a.isCollection;e.coth=function p(r){if(1!=arguments.length)throw new e.error.ArgumentsError("coth",arguments.length,1);if(s(r)){var n=Math.exp(2*r);return(n+1)/(n-1)}if(f(r)){var m=Math.exp(2*r.re),h=m*Math.cos(2*r.im),g=m*Math.sin(2*r.im),d=(h-1)*(h-1)+g*g;return new i(((h+1)*(h-1)+g*g)/d,-2*g/d)}if(c(r)){if(!r.hasBase(o.BASE_UNITS.ANGLE))throw new TypeError("Unit in function coth is no angle");return p(r.value)}if(l(r))return a.deepMap(r,p);if(u(r)||null===r)return p(r?1:0);if(r instanceof t)return p(r.toNumber());throw new e.error.UnsupportedTypeError("coth",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(10),a=n(13),s=r.number.isNumber,u=r["boolean"].isBoolean,f=i.isComplex,c=o.isUnit,l=a.isCollection;e.csc=function p(r){if(1!=arguments.length)throw new e.error.ArgumentsError("csc",arguments.length,1);if(s(r))return 1/Math.sin(r);if(f(r)){var n=.25*(Math.exp(-2*r.im)+Math.exp(2*r.im))-.5*Math.cos(2*r.re);return new i(.5*Math.sin(r.re)*(Math.exp(-r.im)+Math.exp(r.im))/n,.5*Math.cos(r.re)*(Math.exp(-r.im)-Math.exp(r.im))/n)}if(c(r)){if(!r.hasBase(o.BASE_UNITS.ANGLE))throw new TypeError("Unit in function csc is no angle");return 1/Math.sin(r.value)}if(l(r))return a.deepMap(r,p);if(u(r)||null===r)return p(+r);if(r instanceof t)return p(r.toNumber());throw new e.error.UnsupportedTypeError("csc",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(10),a=n(13),s=r.number,u=r.number.isNumber,f=r["boolean"].isBoolean,c=i.isComplex,l=o.isUnit,p=a.isCollection;e.csch=function m(r){if(1!=arguments.length)throw new e.error.ArgumentsError("csch",arguments.length,1);if(u(r))return 0==r?Number.NaN:Math.abs(2/(Math.exp(r)-Math.exp(-r)))*s.sign(r);if(c(r)){var n=Math.exp(r.re),h=Math.exp(-r.re),g=Math.cos(r.im)*(n-h),d=Math.sin(r.im)*(n+h),x=g*g+d*d;return new i(2*g/x,-2*d/x)}if(l(r)){if(!r.hasBase(o.BASE_UNITS.ANGLE))throw new TypeError("Unit in function csch is no angle");return m(r.value)}if(p(r))return a.deepMap(r,m);if(f(r)||null===r)return m(r?1:0);if(r instanceof t)return m(r.toNumber());throw new e.error.UnsupportedTypeError("csch",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(10),a=n(13),s=r.number.isNumber,u=r["boolean"].isBoolean,f=i.isComplex,c=o.isUnit,l=a.isCollection;e.sec=function p(r){if(1!=arguments.length)throw new e.error.ArgumentsError("sec",arguments.length,1);if(s(r))return 1/Math.cos(r);if(f(r)){var n=.25*(Math.exp(-2*r.im)+Math.exp(2*r.im))+.5*Math.cos(2*r.re);return new i(.5*Math.cos(r.re)*(Math.exp(-r.im)+Math.exp(r.im))/n,.5*Math.sin(r.re)*(Math.exp(r.im)-Math.exp(-r.im))/n)}if(c(r)){if(!r.hasBase(o.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sec is no angle");return 1/Math.cos(r.value)}if(l(r))return a.deepMap(r,p);if(u(r)||null===r)return p(+r);if(r instanceof t)return p(r.toNumber());throw new e.error.UnsupportedTypeError("sec",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(10),a=n(13),s=r.number.isNumber,u=r["boolean"].isBoolean,f=i.isComplex,c=o.isUnit,l=a.isCollection;e.sech=function p(r){if(1!=arguments.length)throw new e.error.ArgumentsError("sech",arguments.length,1);if(s(r))return 2/(Math.exp(r)+Math.exp(-r));if(f(r)){var n=Math.exp(r.re),m=Math.exp(-r.re),h=Math.cos(r.im)*(n+m),g=Math.sin(r.im)*(n-m),d=h*h+g*g;return new i(2*h/d,-2*g/d)}if(c(r)){if(!r.hasBase(o.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sech is no angle");return p(r.value)}if(l(r))return a.deepMap(r,p);if(u(r)||null===r)return p(r?1:0);if(r instanceof t)return p(r.toNumber());throw new e.error.UnsupportedTypeError("sech",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(10),a=n(13),s=r.number.isNumber,u=r["boolean"].isBoolean,f=i.isComplex,c=o.isUnit,l=a.isCollection;e.sin=function p(r){if(1!=arguments.length)throw new e.error.ArgumentsError("sin",arguments.length,1);if(s(r))return Math.sin(r);if(f(r))return new i(.5*Math.sin(r.re)*(Math.exp(-r.im)+Math.exp(r.im)),.5*Math.cos(r.re)*(Math.exp(r.im)-Math.exp(-r.im)));if(c(r)){if(!r.hasBase(o.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sin is no angle");return Math.sin(r.value)}if(l(r))return a.deepMap(r,p);if(u(r)||null===r)return Math.sin(r);if(r instanceof t)return p(r.toNumber());throw new e.error.UnsupportedTypeError("sin",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(10),a=n(13),s=r.number.isNumber,u=r["boolean"].isBoolean,f=i.isComplex,c=o.isUnit,l=a.isCollection;e.sinh=function p(r){if(1!=arguments.length)throw new e.error.ArgumentsError("sinh",arguments.length,1);if(s(r))return(Math.exp(r)-Math.exp(-r))/2;if(f(r)){var n=Math.cos(r.im),m=Math.sin(r.im),h=Math.exp(r.re),g=Math.exp(-r.re);return new i(n*(h-g)/2,m*(h+g)/2)}if(c(r)){if(!r.hasBase(o.BASE_UNITS.ANGLE))throw new TypeError("Unit in function sinh is no angle");return p(r.value)}if(l(r))return a.deepMap(r,p);if(u(r)||null===r)return p(r?1:0);if(r instanceof t)return p(r.toNumber());throw new e.error.UnsupportedTypeError("sinh",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(10),a=n(13),s=r.number.isNumber,u=r["boolean"].isBoolean,f=i.isComplex,c=o.isUnit,l=a.isCollection;e.tan=function p(r){if(1!=arguments.length)throw new e.error.ArgumentsError("tan",arguments.length,1);if(s(r))return Math.tan(r);if(f(r)){var n=Math.exp(-4*r.im)+2*Math.exp(-2*r.im)*Math.cos(2*r.re)+1;return new i(2*Math.exp(-2*r.im)*Math.sin(2*r.re)/n,(1-Math.exp(-4*r.im))/n)}if(c(r)){if(!r.hasBase(o.BASE_UNITS.ANGLE))throw new TypeError("Unit in function tan is no angle");return Math.tan(r.value)}if(l(r))return a.deepMap(r,p);if(u(r)||null===r)return Math.tan(r);if(r instanceof t)return p(r.toNumber());throw new e.error.UnsupportedTypeError("tan",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=e.type.BigNumber,i=n(6),o=n(10),a=n(13),s=r.number.isNumber,u=r["boolean"].isBoolean,f=i.isComplex,c=o.isUnit,l=a.isCollection;e.tanh=function p(r){if(1!=arguments.length)throw new e.error.ArgumentsError("tanh",arguments.length,1);if(s(r)){var n=Math.exp(2*r);return(n-1)/(n+1)}if(f(r)){var m=Math.exp(2*r.re),h=m*Math.cos(2*r.im),g=m*Math.sin(2*r.im),d=(h+1)*(h+1)+g*g;return new i(((h-1)*(h+1)+g*g)/d,2*g/d)}if(c(r)){if(!r.hasBase(o.BASE_UNITS.ANGLE))throw new TypeError("Unit in function tanh is no angle");return p(r.value)}if(l(r))return a.deepMap(r,p);if(u(r)||null===r)return p(r?1:0);if(r instanceof t)return p(r.toNumber());throw new e.error.UnsupportedTypeError("tanh",e["typeof"](r))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=n(10),i=n(13),o=r.string.isString,a=t.isUnit,s=i.isCollection;e.to=function u(r,n){if(2!=arguments.length)throw new e.error.ArgumentsError("to",arguments.length,2);if(a(r)&&(a(n)||o(n)))return r.to(n);if(s(r)||s(n))return i.deepMap2(r,n,u);throw new e.error.UnsupportedTypeError("to",e["typeof"](r),e["typeof"](n))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=r.object;e.clone=function(r){if(1!=arguments.length)throw new e.error.ArgumentsError("clone",arguments.length,1);return t.clone(r)}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=r.string;e.format=function(r,n){var i=arguments.length;if(1!==i&&2!==i)throw new e.error.ArgumentsError("format",i,1,2);return t.format(r,n)}}},function(e,r,n){"use strict";e.exports=function(e){function r(r,n,t){(t.override||void 0===e[r])&&(e[r]=t.wrap&&"function"==typeof n?function(){for(var r=[],t=0,i=arguments.length;i>t;t++){var o=arguments[t];r[t]=o&&o.valueOf()}return n.apply(e,r)}:n,e.chaining.Selector.createProxy(r,n))}function t(e){return"function"==typeof e||s(e)||u(e)||f(e)||c(e)}var i=n(143),o=n(6),a=n(10),s=i.number.isNumber,u=i.string.isString,f=o.isComplex,c=a.isUnit;e["import"]=function l(i,o){var a=arguments.length;if(1!=a&&2!=a)throw new e.error.ArgumentsError("import",a,1,2);var s,f={override:o&&o.override||!1,wrap:o&&o.wrap||!1};if(u(i)){var c=n(177)(i);l(c,o)}else{if("object"!=typeof i)throw new TypeError("Object or module name expected");for(s in i)if(i.hasOwnProperty(s)){var p=i[s];t(p)?r(s,p,f):l(p,o)}}}}},function(e,r,n){"use strict";e.exports=function(e){function r(e,r){var n=[],t=function(i,o){return Array.isArray(i)?i.map(function(e,r){return n[o]=r,t(e,o+1)}):r(i,n,e)};return t(e,0)}var t=n(9).isMatrix;e.map=function(n,i){if(2!=arguments.length)throw new e.error.ArgumentsError("map",arguments.length,2);if(Array.isArray(n))return r(n,i);if(t(n))return n.map(i);throw new e.error.UnsupportedTypeError("map",e["typeof"](n))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(143),t=r.string.isString;e.print=function(r,n,i){var o=arguments.length;if(2!=o&&3!=o)throw new e.error.ArgumentsError("print",o,2,3);if(!t(r))throw new TypeError("String expected as first parameter in function format");if(!(n instanceof Object))throw new TypeError("Object expected as second parameter in function format");return r.replace(/\$([\w\.]+)/g,function(r,o){for(var a=o.split("."),s=n[a.shift()];a.length&&void 0!==s;){var u=a.shift();s=u?s[u]:s+"."}return void 0!==s?t(s)?s:e.format(s,i):r})}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(9);e.sort=function(n,t){var i=null;if(1===arguments.length)i=e.compare;else{if(2!==arguments.length)throw new e.error.ArgumentsError("sort",arguments.length,1,2);if("function"==typeof t)i=t;else if("asc"===t)i=e.compare;else{if("desc"!==t)throw new e.error.UnsupportedTypeError("sort",e["typeof"](n),e["typeof"](t));i=function(r,n){return-e.compare(r,n)}}}if(n instanceof r){var o=n.size();if(o.length>1)throw new Error("Only one dimensional matrices supported");return new r(n.toArray().sort(i))}if(Array.isArray(n))return n.sort(i);throw new e.error.UnsupportedTypeError("sort",e["typeof"](n),e["typeof"](t))}}},function(e,r,n){"use strict";e.exports=function(e){var r=n(178),t=n(6),i=n(9),o=n(10),a=n(8),s=n(7),u=n(11);e["typeof"]=function(n){if(1!=arguments.length)throw new e.error.ArgumentsError("typeof",arguments.length,1);var f=r.type(n);if("object"===f){if(n instanceof t)return"complex";if(n instanceof i)return"matrix";if(n instanceof o)return"unit";if(n instanceof a)return"index";if(n instanceof s)return"range";if(n instanceof u)return"help";if(n instanceof e.type.BigNumber)return"bignumber";if(n instanceof e.chaining.Selector)return"selector"}return f}}},function(e,r,n){"use strict";e.exports=function(e){function r(e,r){var n=[],t=function(i,o){Array.isArray(i)?i.forEach(function(e,r){n[o]=r,t(e,o+1)}):r(i,n,e)};t(e,0)}var t=n(9).isMatrix;e.forEach=function(n,i){if(2!=arguments.length)throw new e.error.ArgumentsError("forEach",arguments.length,2);
if(Array.isArray(n))return r(n,i);if(t(n))return n.forEach(i);throw new e.error.UnsupportedTypeError("forEach",e["typeof"](n))}}},function(e,r,n){"use strict";{var t=n(142),i=n(4).isNumber;n(4).digits}r.isBigNumber=function(e){return e instanceof t},r.format=function(e,n){if("function"==typeof n)return n(e);if(!e.isFinite())return e.isNaN()?"NaN":e.gt(0)?"Infinity":"-Infinity";var t="auto",o=void 0;switch(void 0!==n&&(n.notation&&(t=n.notation),i(n)?o=n:n.precision&&(o=n.precision)),t){case"fixed":return r.toFixed(e,o);case"exponential":return r.toExponential(e,o);case"auto":var a=.001,s=1e5;n&&n.exponential&&(void 0!==n.exponential.lower&&(a=n.exponential.lower),void 0!==n.exponential.upper&&(s=n.exponential.upper));{({toExpNeg:e.constructor.toExpNeg,toExpPos:e.constructor.toExpPos})}if(e.constructor.config({toExpNeg:Math.round(Math.log(a)/Math.LN10),toExpPos:Math.round(Math.log(s)/Math.LN10)}),e.isZero())return"0";var u,f=e.abs();return u=f.gte(a)&&f.lt(s)?e.toSignificantDigits(o).toFixed():r.toExponential(e,o),u.replace(/((\.\d*?)(0+))($|e)/,function(){var e=arguments[2],r=arguments[4];return"."!==e?e+r:r});default:throw new Error('Unknown notation "'+t+'". Choose "auto", "exponential", or "fixed".')}},r.toExponential=function(e,r){return void 0!==r?e.toExponential(r-1):e.toExponential()},r.toFixed=function(e,r){return e.toFixed(r||0)}},function(e,r,n){"use strict";function t(e){for(var r=[];m(e);)r.push(e.length),e=e[0];return r}function i(e,r,n){var t,o=e.length;if(o!=r[n])throw new l(o,r[n]);if(n<r.length-1){var a=n+1;for(t=0;o>t;t++){var s=e[t];if(!m(s))throw new l(r.length-1,r.length,"<");i(e[t],r,a)}}else for(t=0;o>t;t++)if(m(e[t]))throw new l(r.length+1,r.length,">")}function o(e,n,t,i){var a,s,u=e.length,f=n[t],l=Math.min(u,f);if(e.length=f,t<n.length-1){var p=t+1;for(a=0;l>a;a++)s=e[a],m(s)||(s=[s],e[a]=s),o(s,n,p,i);for(a=l;f>a;a++)s=[],e[a]=s,o(s,n,p,i)}else{for(a=0;l>a;a++)for(;m(e[a]);)e[a]=e[a][0];if(i!==r.UNINITIALIZED)for(a=l;f>a;a++)e[a]=c.clone(i)}}function a(e,r,n){var t,i;if(r>n){var o=n+1;for(t=0,i=e.length;i>t;t++)e[t]=a(e[t],r,o)}else for(;m(e);)e=e[0];return e}function s(e,r,n){var t,i;if(m(e)){var o=n+1;for(t=0,i=e.length;i>t;t++)e[t]=s(e[t],r,o)}else for(var a=n;r>a;a++)e=[e];return e}var u=n(4),f=n(159),c=n(3),l=(n(178),n(139)),p=n(140),m=Array.isArray;r.size=function(e){var n=t(e);return r.validate(e,n),n},r.validate=function(e,r){var n=0==r.length;if(n){if(m(e))throw new l(e.length,0)}else i(e,r,0)},r.validateIndex=function(e,r){if(!u.isNumber(e)||!u.isInteger(e))throw new TypeError("Index must be an integer (value: "+e+")");if(0>e)throw new p(e);if(void 0!==r&&e>=r)throw new p(e,r)},r.UNINITIALIZED={},r.resize=function(e,r,n){if(!m(e)||!m(r))throw new TypeError("Array expected");if(0===r.length)throw new Error("Resizing to scalar is not supported");r.forEach(function(e){if(!u.isNumber(e)||!u.isInteger(e)||0>e)throw new TypeError("Invalid size, must contain positive integers (size: "+f.format(r)+")")});var t=void 0!==n?n:0;return o(e,r,0,t),e},r.squeeze=function(e,n){for(var t=n||r.size(e);m(e)&&1===e.length;)e=e[0],t.shift();for(var i=t.length;1===t[i-1];)i--;return i<t.length&&(e=a(e,i,0),t.length=i),e},r.unsqueeze=function(e,n,t,i){var o=i||r.size(e);if(t)for(var a=0;t>a;a++)e=[e],o.unshift(1);for(e=s(e,n,0);o.length<n;)o.push(1);return e},r.flatten=function(e){for(var r=e,n=Array.isArray;n(r[0]);){for(var t=[],i=0,o=r.length;o>i;i++)t=t.concat.apply(t,r[i]);r=t}return r},r.argsToArray=function(e){for(var r=[],n=0,t=e.length;t>n;n++)r[n]=e[n];return r},r.isArray=m},function(e){e.exports="0.27.0"},function(e){"use strict";function r(e,n,t,i){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");this.fn=e,this.count=n,this.min=t,this.max=i,this.message="Wrong number of arguments in function "+e+" ("+n+" provided, "+t+(void 0!=i?"-"+i:"")+" expected)",this.stack=(new Error).stack}r.prototype=new Error,r.prototype.constructor=Error,r.prototype.name="ArgumentsError",e.exports=r},function(e){"use strict";function r(e,n,t){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");this.actual=e,this.expected=n,this.relation=t,this.message="Dimension mismatch ("+(Array.isArray(e)?"["+e.join(", ")+"]":e)+" "+(this.relation||"!=")+" "+(Array.isArray(n)?"["+n.join(", ")+"]":n)+")",this.stack=(new Error).stack}r.prototype=new RangeError,r.prototype.constructor=RangeError,r.prototype.name="DimensionError",e.exports=r},function(e){"use strict";function r(e,n,t){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");this.index=e,arguments.length<3?(this.min=0,this.max=n):(this.min=n,this.max=t),this.message=void 0!==this.min&&this.index<this.min?"Index out of range ("+this.index+" < "+this.min+")":void 0!==this.max&&this.index>=this.max?"Index out of range ("+this.index+" > "+(this.max-1)+")":"Index out of range ("+this.index+")",this.stack=(new Error).stack}r.prototype=new RangeError,r.prototype.constructor=RangeError,r.prototype.name="IndexError",e.exports=r},function(e){"use strict";function r(e){if(!(this instanceof r))throw new SyntaxError("Constructor must be called with the new operator");this.fn=e,this.types=Array.prototype.splice.call(arguments,1),this.message=e?0==this.types.length?"Unsupported type of argument in function "+e:"Function "+e+"("+this.types.join(", ")+") not supported":"Unsupported type of argument",this.stack=(new Error).stack}r.prototype=new TypeError,r.prototype.constructor=TypeError,r.prototype.name="UnsupportedTypeError",e.exports=r},function(e,r,n){var t;!function(i){"use strict";function o(e){for(var r,n,t=1,i=e.length,o=e[0]+"";i>t;t++){for(r=e[t]+"",n=T-r.length;n--;)r="0"+r;o+=r}for(i=o.length;"0"==o.charAt(--i););return o.slice(0,i+1||1)}function a(e,r,n,t){var i,o,a,s,u;for(o=1,a=e[0];a>=10;a/=10,o++);return a=r-o,0>a?(a+=T,i=0):(i=Math.ceil((a+1)/T),a%=T),o=N(10,T-a),u=e[i]%o|0,null==t?3>a?(0==a?u=u/100|0:1==a&&(u=u/10|0),s=4>n&&99999==u||n>3&&49999==u||5e4==u||0==u):s=(4>n&&u+1==o||n>3&&u+1==o/2)&&(e[i+1]/o/100|0)==N(10,a-2)-1||(u==o/2||0==u)&&0==(e[i+1]/o/100|0):4>a?(0==a?u=u/1e3|0:1==a?u=u/100|0:2==a&&(u=u/10|0),s=(t||4>n)&&9999==u||!t&&n>3&&4999==u):s=((t||4>n)&&u+1==o||!t&&n>3&&u+1==o/2)&&(e[i+1]/o/1e3|0)==N(10,a-3)-1,s}function s(e,r,n){var t=e.constructor;return null==r||((y=0>r||r>8)||0!==r&&(t.errors?parseInt:parseFloat)(r)!=r)&&!p(t,"rounding mode",r,n,0)?t.rounding:0|r}function u(e,r,n,t){var i=e.constructor;return!(y=(t||0)>r||r>=U+1)&&(0===r||(i.errors?parseInt:parseFloat)(r)==r)||p(i,"argument",r,n,0)}function f(e,r){var n,t,i,s,u,f,c,l=0,p=0,m=0,h=e.constructor,d=h.ONE,x=h.rounding,y=h.precision;if(!e.c||!e.c[0]||e.e>17)return new h(e.c?e.c[0]?e.s<0?0:1/0:d:e.s?e.s<0?0:e:0/0);for(null==r?(v=!1,u=y):u=r,c=new h(.03125);e.e>-2;)e=e.times(c),m+=5;for(t=Math.log(N(2,m))/Math.LN10*2+5|0,u+=t,n=s=f=new h(d),h.precision=u;;){if(s=g(s.times(e),u,1),n=n.times(++p),c=f.plus(z(s,n,u,1)),o(c.c).slice(0,u)===o(f.c).slice(0,u)){for(i=m;i--;)f=g(f.times(f),u,1);if(null!=r)return h.precision=y,f;if(!(3>l&&a(f.c,u-t,x,l)))return g(f,h.precision=y,x,v=!0);h.precision=u+=10,n=s=c=new h(d),p=0,l++}f=c}}function c(e,r,n,t){var i,a,s=e.constructor,u=(e=new s(e)).e;if(null==r?n=0:(g(e,++r,n),n=t?r:r+e.e-u),u=e.e,i=o(e.c),1==t||2==t&&(u>=r||u<=s.toExpNeg)){for(;i.length<n;i+="0");i.length>1&&(i=i.charAt(0)+"."+i.slice(1)),i+=(0>u?"e":"e+")+u}else{if(t=i.length,0>u){for(a=n-t;++u;i="0"+i);i="0."+i}else if(++u>t){for(a=n-u,u-=t;u--;i+="0");a>0&&(i+=".")}else a=n-t,t>u?i=i.slice(0,u)+"."+i.slice(u):a>0&&(i+=".");if(a>0)for(;a--;i+="0");}return e.s<0&&e.c[0]?"-"+i:i}function l(e){var r=e.length-1,n=r*T+1;if(r=e[r]){for(;r%10==0;r/=10,n--);for(r=e[0];r>=10;r/=10,n++);}return n}function p(e,r,n,t,i){if(e.errors){var o=new Error((t||["new Decimal","cmp","div","eq","gt","gte","lt","lte","minus","mod","plus","times","toFraction","pow","random","log","sqrt","toNearest","divToInt"][b?0>b?-b:b:0>1/b?1:0])+"() "+(["number type has more than 15 significant digits","LN10 out of digits"][r]||r+([y?" out of range":" not an integer"," not a boolean or binary digit"][i]||""))+": "+n);throw o.name="Decimal Error",y=b=0,o}}function m(e,r,n){var t=new e(e.ONE);for(v=!1;1&n&&(t=t.times(r)),n>>=1,n;)r=r.times(r);return v=!0,t}function h(e,r){var n,t,i,s,u,f,c,l,m,d,x,y=1,w=10,b=e,E=b.c,N=b.constructor,M=N.ONE,A=N.rounding,T=N.precision;if(b.s<0||!E||!E[0]||!b.e&&1==E[0]&&1==E.length)return new N(E&&!E[0]?-1/0:1!=b.s?0/0:E?0:b);if(null==r?(v=!1,c=T):c=r,N.precision=c+=w,n=o(E),t=n.charAt(0),!(Math.abs(s=b.e)<15e14))return b=new N(t+"."+n.slice(1)),c+2>B.length&&p(N,1,c+2,"ln"),b=h(b,c-w).plus(new N(B.slice(0,c+2)).times(s+"")),N.precision=T,null==r?g(b,T,A,v=!0):b;for(;7>t&&1!=t||1==t&&n.charAt(1)>3;)b=b.times(e),n=o(b.c),t=n.charAt(0),y++;for(s=b.e,t>1?(b=new N("0."+n),s++):b=new N(t+"."+n.slice(1)),d=b,l=u=b=z(b.minus(M),b.plus(M),c,1),x=g(b.times(b),c,1),i=3;;){if(u=g(u.times(x),c,1),m=l.plus(z(u,new N(i),c,1)),o(m.c).slice(0,c)===o(l.c).slice(0,c)){if(l=l.times(2),0!==s&&(c+2>B.length&&p(N,1,c+2,"ln"),l=l.plus(new N(B.slice(0,c+2)).times(s+""))),l=z(l,new N(y),c,1),null!=r)return N.precision=T,l;if(!a(l.c,c-w,A,f))return g(l,N.precision=T,A,v=!0);N.precision=c+=w,m=u=b=z(d.minus(M),d.plus(M),c,1),x=g(b.times(b),c,1),i=f=1}l=m,i+=2}}function g(e,r,n,t){var i,o,a,s,u,f,c,l,p=e.constructor;e:if(r!=o){if(!(c=e.c))return e;for(i=1,s=c[0];s>=10;s/=10,i++);if(o=r-i,0>o)o+=T,a=r,u=c[l=0],f=u/N(10,i-a-1)%10|0;else if(l=Math.ceil((o+1)/T),l>=c.length){if(!t)break e;for(;c.length<=l;c.push(0));u=f=0,i=1,o%=T,a=o-T+1}else{for(u=s=c[l],i=1;s>=10;s/=10,i++);o%=T,a=o-T+i,f=0>a?0:E(u/N(10,i-a-1)%10)}if(t=t||0>r||null!=c[l+1]||(0>a?u:u%N(10,i-a-1)),t=4>n?(f||t)&&(0==n||n==(e.s<0?3:2)):f>5||5==f&&(4==n||t||6==n&&(o>0?a>0?u/N(10,i-a):0:c[l-1])%10&1||n==(e.s<0?8:7)),1>r||!c[0])return c.length=0,t?(r-=e.e+1,c[0]=N(10,r%T),e.e=-r||0):c[0]=e.e=0,e;if(0==o?(c.length=l,s=1,l--):(c.length=l+1,s=N(10,T-o),c[l]=a>0?(u/N(10,i-a)%N(10,a)|0)*s:0),t)for(;;){if(0==l){for(o=1,a=c[0];a>=10;a/=10,o++);for(a=c[0]+=s,s=1;a>=10;a/=10,s++);o!=s&&(e.e++,c[0]==A&&(c[0]=1));break}if(c[l]+=s,c[l]!=A)break;c[l--]=0,s=1}for(o=c.length;0===c[--o];c.pop());}return v&&(e.e>p.maxE?e.c=e.e=null:e.e<p.minE&&(e.c=[e.e=0])),e}var d,x,y,w=i.crypto,v=!0,b=0,E=Math.floor,N=Math.pow,M=Object.prototype.toString,A=1e7,T=7,S="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_",O={},C=9e15,U=1e9,q=3e3,B="2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058";O.absoluteValue=O.abs=function(){var e=new this.constructor(this);return e.s<0&&(e.s=1),g(e)},O.ceil=function(){return g(new this.constructor(this),this.e+1,2)},O.comparedTo=O.cmp=function(e,r){var n,t=this,i=t.c,o=(b=-b,e=new t.constructor(e,r),e.c),a=t.s,s=e.s,u=t.e,f=e.e;if(!a||!s)return null;if(n=i&&!i[0],r=o&&!o[0],n||r)return n?r?0:-s:a;if(a!=s)return a;if(n=0>a,!i||!o)return u==f?0:!i^n?1:-1;if(u!=f)return u>f^n?1:-1;for(a=-1,s=(u=i.length)<(f=o.length)?u:f;++a<s;)if(i[a]!=o[a])return i[a]>o[a]^n?1:-1;return u==f?0:u>f^n?1:-1},O.decimalPlaces=O.dp=function(){var e,r,n=null;if(e=this.c){if(n=((r=e.length-1)-E(this.e/T))*T,r=e[r])for(;r%10==0;r/=10,n--);0>n&&(n=0)}return n},O.dividedBy=O.div=function(e,r){return b=2,z(this,new this.constructor(e,r))},O.dividedToIntegerBy=O.divToInt=function(e,r){var n=this,t=n.constructor;return b=18,g(z(n,new t(e,r),0,1,1),t.precision,t.rounding)},O.equals=O.eq=function(e,r){return b=3,0===this.cmp(e,r)},O.exponential=O.exp=function(){return f(this)},O.floor=function(){return g(new this.constructor(this),this.e+1,3)},O.greaterThan=O.gt=function(e,r){return b=4,this.cmp(e,r)>0},O.greaterThanOrEqualTo=O.gte=function(e,r){return b=5,r=this.cmp(e,r),1==r||0===r},O.isFinite=function(){return!!this.c},O.isInteger=O.isInt=function(){return!!this.c&&E(this.e/T)>this.c.length-2},O.isNaN=function(){return!this.s},O.isNegative=O.isNeg=function(){return this.s<0},O.isZero=function(){return!!this.c&&0==this.c[0]},O.lessThan=O.lt=function(e,r){return b=6,this.cmp(e,r)<0},O.lessThanOrEqualTo=O.lte=function(e,r){return b=7,r=this.cmp(e,r),-1==r||0===r},O.logarithm=O.log=function(e,r){var n,t,i,s,u,f,c,l,m,d=this,x=d.constructor,y=x.precision,w=x.rounding,E=5;if(null==e)e=new x(10),n=!0;else{if(b=15,e=new x(e,r),t=e.c,e.s<0||!t||!t[0]||!e.e&&1==t[0]&&1==t.length)return new x(0/0);n=e.eq(10)}if(t=d.c,d.s<0||!t||!t[0]||!d.e&&1==t[0]&&1==t.length)return new x(t&&!t[0]?-1/0:1!=d.s?0/0:t?0:1/0);if(u=n&&(s=t[0],t.length>1||1!=s&&10!=s&&100!=s&&1e3!=s&&1e4!=s&&1e5!=s&&1e6!=s),v=!1,c=y+E,l=c+10,f=h(d,c),n?(l>B.length&&p(x,1,l,"log"),i=new x(B.slice(0,l))):i=h(e,c),m=z(f,i,c,1),a(m.c,s=y,w))do if(c+=10,f=h(d,c),n?(l=c+10,l>B.length&&p(x,1,l,"log"),i=new x(B.slice(0,l))):i=h(e,c),m=z(f,i,c,1),!u){+o(m.c).slice(s+1,s+15)+1==1e14&&(m=g(m,y+1,0));break}while(a(m.c,s+=10,w));return v=!0,g(m,y,w)},O.minus=function(e,r){var n,t,i,o,a=this,s=a.constructor,u=a.s;if(b=8,e=new s(e,r),r=e.s,!u||!r)return new s(0/0);if(u!=r)return e.s=-r,a.plus(e);var f=a.c,c=e.c,l=E(e.e/T),p=E(a.e/T),m=s.precision,h=s.rounding;if(!p||!l){if(!f||!c)return f?(e.s=-r,e):new s(c?a:0/0);if(!f[0]||!c[0])return a=c[0]?(e.s=-r,e):new s(f[0]?a:3==h?-0:0),v?g(a,m,h):a}if(f=f.slice(),t=f.length,u=p-l){for((o=0>u)?(u=-u,n=f,t=c.length):(l=p,n=c),(p=Math.ceil(m/T))>t&&(t=p),u>(t+=2)&&(u=t,n.length=1),n.reverse(),r=u;r--;n.push(0));n.reverse()}else for((o=t<(i=c.length))&&(i=t),u=r=0;i>r;r++)if(f[r]!=c[r]){o=f[r]<c[r];break}if(o&&(n=f,f=c,c=n,e.s=-e.s),(r=-((i=f.length)-c.length))>0)for(;r--;f[i++]=0);for(p=A-1,r=c.length;r>u;){if(f[--r]<c[r]){for(t=r;t&&!f[--t];f[t]=p);--f[t],f[r]+=A}f[r]-=c[r]}for(;0==f[--i];f.pop());for(;0==f[0];f.shift(),--l);for(f[0]||(f=[l=0],e.s=3==h?-1:1),e.c=f,u=1,r=f[0];r>=10;r/=10,u++);return e.e=u+l*T-1,v?g(e,m,h):e},O.modulo=O.mod=function(e,r){var n,t,i=this,o=i.constructor,a=o.modulo;return b=9,e=new o(e,r),r=e.s,n=!i.c||!r||e.c&&!e.c[0],n||!e.c||i.c&&!i.c[0]?n?new o(0/0):g(new o(i),o.precision,o.rounding):(v=!1,9==a?(e.s=1,t=z(i,e,0,3,1),e.s=r,t.s*=r):t=z(i,e,0,a,1),t=t.times(e),v=!0,i.minus(t))},O.naturalLogarithm=O.ln=function(){return h(this)},O.negated=O.neg=function(){var e=new this.constructor(this);return e.s=-e.s||null,g(e)},O.plus=function(e,r){var n,t=this,i=t.constructor,o=t.s;if(b=10,e=new i(e,r),r=e.s,!o||!r)return new i(0/0);if(o!=r)return e.s=-r,t.minus(e);var a=t.c,s=e.c,u=E(e.e/T),f=E(t.e/T),c=i.precision,l=i.rounding;if(!f||!u){if(!a||!s)return new i(o/0);if(!a[0]||!s[0])return t=s[0]?e:new i(a[0]?t:0*o),v?g(t,c,l):t}if(a=a.slice(),o=f-u){for(0>o?(o=-o,n=a,r=s.length):(u=f,n=s,r=a.length),(f=Math.ceil(c/T))>r&&(r=f),o>++r&&(o=r,n.length=1),n.reverse();o--;n.push(0));n.reverse()}for(a.length-s.length<0&&(n=s,s=a,a=n),o=s.length,r=0,f=A;o;a[o]%=f)r=(a[--o]=a[o]+s[o]+r)/f|0;for(r&&(a.unshift(r),++u),o=a.length;0==a[--o];a.pop());for(e.c=a,o=1,r=a[0];r>=10;r/=10,o++);return e.e=o+u*T-1,v?g(e,c,l):e},O.precision=O.sd=function(e){var r=null,n=this;return e!=r&&e!==!!e&&1!==e&&0!==e&&p(n.constructor,"argument",e,"precision",1),n.c&&(r=l(n.c),e&&n.e+1>r&&(r=n.e+1)),r},O.round=function(){var e=this,r=e.constructor;return g(new r(e),e.e+1,r.rounding)},O.squareRoot=O.sqrt=function(){var e,r,n,t,i,a,s=this,u=s.c,f=s.s,c=s.e,l=s.constructor,p=new l(.5);if(1!==f||!u||!u[0])return new l(!f||0>f&&(!u||u[0])?0/0:u?s:1/0);for(v=!1,f=Math.sqrt(+s),0==f||f==1/0?(r=o(u),(r.length+c)%2==0&&(r+="0"),f=Math.sqrt(r),c=E((c+1)/2)-(0>c||c%2),f==1/0?r="1e"+c:(r=f.toExponential(),r=r.slice(0,r.indexOf("e")+1)+c),t=new l(r)):t=new l(f.toString()),n=(c=l.precision)+3;;)if(a=t,t=p.times(a.plus(z(s,a,n+2,1))),o(a.c).slice(0,n)===(r=o(t.c)).slice(0,n)){if(r=r.slice(n-3,n+1),"9999"!=r&&(i||"4999"!=r)){(!+r||!+r.slice(1)&&"5"==r.charAt(0))&&(g(t,c+1,1),e=!t.times(t).eq(s));break}if(!i&&(g(a,c+1,0),a.times(a).eq(s))){t=a;break}n+=4,i=1}return v=!0,g(t,c,l.rounding,e)},O.times=function(e,r){var n,t,i=this,o=i.constructor,a=i.c,s=(b=11,e=new o(e,r),e.c),u=E(i.e/T),f=E(e.e/T),c=i.s;if(r=e.s,e.s=c==r?1:-1,!((u||a&&a[0])&&(f||s&&s[0])))return new o(!c||!r||a&&!a[0]&&!s||s&&!s[0]&&!a?0/0:a&&s?0*e.s:e.s/0);for(t=u+f,c=a.length,r=s.length,r>c&&(n=a,a=s,s=n,f=c,c=r,r=f),f=c+r,n=[];f--;n.push(0));for(u=r-1;u>-1;u--){for(r=0,f=c+u;f>u;r=r/A|0)r=n[f]+s[u]*a[f-u-1]+r,n[f--]=r%A|0;r&&(n[f]=(n[f]+r)%A)}for(r&&++t,n[0]||n.shift(),f=n.length;!n[--f];n.pop());for(e.c=n,c=1,r=n[0];r>=10;r/=10,c++);return e.e=c+t*T-1,v?g(e,o.precision,o.rounding):e},O.toDecimalPlaces=O.toDP=function(e,r){var n=this;return n=new n.constructor(n),null!=e&&u(n,e,"toDP")?g(n,(0|e)+n.e+1,s(n,r,"toDP")):n},O.toExponential=function(e,r){var n=this;return n.c?c(n,null!=e&&u(n,e,"toExponential")?0|e:null,null!=e&&s(n,r,"toExponential"),1):n.toString()},O.toFixed=function(e,r){var n,t=this,i=t.constructor,o=i.toExpNeg,a=i.toExpPos;return null!=e&&(e=u(t,e,n="toFixed")?t.e+(0|e):null,r=s(t,r,n)),i.toExpNeg=-(i.toExpPos=1/0),null!=e&&t.c?(n=c(t,e,r),t.s<0&&t.c&&(t.c[0]?n.indexOf("-")<0&&(n="-"+n):n=n.replace("-",""))):n=t.toString(),i.toExpNeg=o,i.toExpPos=a,n},O.toFormat=function(e,r,n){var t=this.toFixed(r).split(".");return t[0].replace(/\B(?=(\d{3})+$)/g,null==e?",":e+"")+(t[1]?"."+(n?t[1].replace(/\d{5}\B/g,"$&"+n):t[1]):"")},O.toFraction=function(e){var r,n,t,i,a,s,u,f,c=this,m=c.constructor,h=r=new m(m.ONE),g=s=new m(0),d=c.c,x=new m(g);if(!d)return c.toString();for(t=x.e=l(d)-c.e-1,x.c[0]=N(10,(u=t%T)<0?T+u:u),(null==e||(!(b=12,a=new m(e)).s||(y=a.cmp(h)<0||!a.c)||m.errors&&E(a.e/T)<a.c.length-1)&&!p(m,"max denominator",e,"toFraction",0)||(e=a).cmp(x)>0)&&(e=t>0?x:h),v=!1,a=new m(o(d)),u=m.precision,m.precision=t=d.length*T*2;f=z(a,x,0,1,1),n=r.plus(f.times(g)),1!=n.cmp(e);)r=g,g=n,h=s.plus(f.times(n=h)),s=n,x=a.minus(f.times(n=x)),a=n;return n=z(e.minus(r),g,0,1,1),s=s.plus(n.times(h)),r=r.plus(n.times(g)),s.s=h.s=c.s,i=z(h,g,t,1).minus(c).abs().cmp(z(s,r,t,1).minus(c).abs())<1?[h+"",g+""]:[s+"",r+""],v=!0,m.precision=u,i},O.toNearest=function(e,r){var n=this,t=n.constructor;return n=new t(n),null==e?(e=new t(t.ONE),r=t.rounding):(b=17,e=new t(e),r=s(n,r,"toNearest")),e.c?n.c&&(e.c[0]?(v=!1,n=z(n,e,0,4>r?[4,5,7,8][r]:r,1).times(e),v=!0,g(n)):n.c=[n.e=0]):n.s&&(e.s&&(e.s=n.s),n=e),n},O.toNumber=function(){var e=this;return+e||(e.s?0*e.s:0/0)},O.toPower=O.pow=function(e,r){var n,t,i,s,u=this,c=u.constructor,l=u.s,p=(b=13,+(e=new c(e,r))),d=0>p?-p:p,x=c.precision,y=c.rounding;if(!u.c||!e.c||(i=!u.c[0])||!e.c[0])return new c(N(i?0*l:+u,p));if(u=new c(u),n=u.c.length,!u.e&&u.c[0]==u.s&&1==n)return u;if(r=e.c.length-1,e.e||e.c[0]!=e.s||r)if(t=E(e.e/T),i=t>=r,!i&&0>l)s=new c(0/0);else{if(i&&q>n*T*d){if(s=m(c,u,d),e.s<0)return c.ONE.div(s)}else{if(l=0>l&&1&e.c[Math.max(t,r)]?-1:1,r=N(+u,p),t=0!=r&&isFinite(r)?new c(r+"").e:E(p*(Math.log("0."+o(u.c))/Math.LN10+u.e+1)),t>c.maxE+1||t<c.minE-1)return new c(t>0?l/0:0);v=!1,c.rounding=u.s=1,d=Math.min(12,(t+"").length),s=f(e.times(h(u,x+d)),x),s=g(s,x+5,1),a(s.c,x,y)&&(t=x+10,s=g(f(e.times(h(u,t+d)),t),t+5,1),+o(s.c).slice(x+1,x+15)+1==1e14&&(s=g(s,x+1,0))),s.s=l,v=!0,c.rounding=y}s=g(s,x,y)}else s=g(u,x,y);return s},O.toPrecision=function(e,r){var n=this;return null!=e&&u(n,e,"toPrecision",1)&&n.c?c(n,0|--e,s(n,r,"toPrecision"),2):n.toString()},O.toSignificantDigits=O.toSD=function(e,r){var n=this,t=n.constructor;return n=new t(n),null!=e&&u(n,e,"toSD",1)?g(n,0|e,s(n,r,"toSD")):g(n,t.precision,t.rounding)},O.toString=function(e){var r,n,t,i=this,a=i.constructor,s=i.e;if(null===s)n=i.s?"Infinity":"NaN";else{if(e===r&&(s<=a.toExpNeg||s>=a.toExpPos))return c(i,null,a.rounding,1);if(n=o(i.c),0>s){for(;++s;n="0"+n);n="0."+n}else if(t=n.length,s>0)if(++s>t)for(s-=t;s--;n+="0");else t>s&&(n=n.slice(0,s)+"."+n.slice(s));else if(r=n.charAt(0),t>1)n=r+"."+n.slice(1);else if("0"==r)return r;if(null!=e)if((y=!(e>=2&&65>e))||e!=(0|e)&&a.errors)p(a,"base",e,"toString",0);else if(n=d(a,n,0|e,10,i.s),"0"==n)return n}return i.s<0?"-"+n:n},O.truncated=O.trunc=function(){return g(new this.constructor(this),this.e+1,1)},O.valueOf=O.toJSON=function(){return this.toString()},d=function(){function e(e,r,n){for(var t,i,o=[0],a=0,s=e.length;s>a;){for(i=o.length;i--;o[i]*=r);for(o[t=0]+=S.indexOf(e.charAt(a++));t<o.length;t++)o[t]>n-1&&(null==o[t+1]&&(o[t+1]=0),o[t+1]+=o[t]/n|0,o[t]%=n)}return o.reverse()}return function(r,n,t,i,o){var a,s,u,f,c,l,p=n.indexOf("."),h=r.precision,g=r.rounding;for(37>i&&(n=n.toLowerCase()),p>=0&&(n=n.replace(".",""),l=new r(i),f=m(r,l,n.length-p),l.c=e(f.toFixed(),10,t),l.e=l.c.length),c=e(n,i,t),a=s=c.length;0==c[--s];c.pop());if(!c[0])return"0";if(0>p?a--:(f.c=c,f.e=a,f.s=o,f=z(f,l,h,g,0,t),c=f.c,u=f.r,a=f.e),p=c[h],s=t/2,u=u||null!=c[h+1],4>g?(null!=p||u)&&(0==g||g==(f.s<0?3:2)):p>s||p==s&&(4==g||u||6==g&&1&c[h-1]||g==(f.s<0?8:7)))for(c.length=h,--t;++c[--h]>t;)c[h]=0,h||(++a,c.unshift(1));else c.length=h;for(s=c.length;!c[--s];);for(p=0,n="";s>=p;n+=S.charAt(c[p++]));if(0>a){for(;++a;n="0"+n);n="0."+n}else if(p=n.length,++a>p)for(a-=p;a--;n+="0");else p>a&&(n=n.slice(0,a)+"."+n.slice(a));return n}}();var z=function(){function e(e,r,n){var t,i=0,o=e.length;for(e=e.slice();o--;)t=e[o]*r+i,e[o]=t%n|0,i=t/n|0;return i&&e.unshift(i),e}function r(e,r,n,t){var i,o;if(n!=t)o=n>t?1:-1;else for(i=o=0;n>i;i++)if(e[i]!=r[i]){o=e[i]>r[i]?1:-1;break}return o}function n(e,r,n,t){for(var i=0;n--;)e[n]-=i,i=e[n]<r[n]?1:0,e[n]=i*t+e[n]-r[n];for(;!e[0]&&e.length>1;e.shift());}return function(t,i,o,a,s,u){var f,c,l,p,m,h,d,x,y,w,v,b,N,M,S,O,C,U,q,B=t.constructor,z=t.s==i.s?1:-1,I=t.c,_=i.c;if(!(I&&I[0]&&_&&_[0]))return new B(t.s&&i.s&&(I?!_||I[0]!=_[0]:_)?I&&0==I[0]||!_?0*z:z/0:0/0);for(u?(p=1,c=t.e-i.e):(u=A,p=T,c=E(t.e/p)-E(i.e/p)),U=_.length,O=I.length,y=new B(z),w=y.c=[],l=0;_[l]==(I[l]||0);l++);if(_[l]>(I[l]||0)&&c--,null==o?(z=o=B.precision,a=B.rounding):z=s?o+(t.e-i.e)+1:o,0>z)w.push(1),m=!0;else{if(z=z/p+2|0,l=0,1==U){for(h=0,_=_[0],z++;(O>l||h)&&z--;l++)M=h*u+(I[l]||0),w[l]=M/_|0,h=M%_|0;m=h||O>l}else{for(h=u/(_[0]+1)|0,h>1&&(_=e(_,h,u),I=e(I,h,u),U=_.length,O=I.length),S=U,v=I.slice(0,U),b=v.length;U>b;v[b++]=0);q=_.slice(),q.unshift(0),C=_[0],_[1]>=u/2&&C++;do h=0,f=r(_,v,U,b),0>f?(N=v[0],U!=b&&(N=N*u+(v[1]||0)),h=N/C|0,h>1?(h>=u&&(h=u-1),d=e(_,h,u),x=d.length,b=v.length,f=r(d,v,x,b),1==f&&(h--,n(d,x>U?q:_,x,u))):(0==h&&(f=h=1),d=_.slice()),x=d.length,b>x&&d.unshift(0),n(v,d,b,u),-1==f&&(b=v.length,f=r(_,v,U,b),1>f&&(h++,n(v,b>U?q:_,b,u))),b=v.length):0===f&&(h++,v=[0]),w[l++]=h,f&&v[0]?v[b++]=I[S]||0:(v=[I[S]],b=1);while((S++<O||null!=v[0])&&z--);m=null!=v[0]}w[0]||w.shift()}if(1==p)y.e=c,y.r=+m;else{for(l=1,z=w[0];z>=10;z/=10,l++);y.e=l+c*p-1,g(y,s?o+y.e+1:o,a,m)}return y}}();x=function(){function e(e){var r,n,t,i=this,o="config",a=i.errors?parseInt:parseFloat;return e==n||"object"!=typeof e&&!p(i,"object expected",e,o)?i:((t=e[r="precision"])!=n&&((y=1>t||t>U)||a(t)!=t?p(i,r,t,o,0):i[r]=0|t),(t=e[r="rounding"])!=n&&((y=0>t||t>8)||a(t)!=t?p(i,r,t,o,0):i[r]=0|t),(t=e[r="toExpNeg"])!=n&&((y=-C>t||t>0)||a(t)!=t?p(i,r,t,o,0):i[r]=E(t)),(t=e[r="toExpPos"])!=n&&((y=0>t||t>C)||a(t)!=t?p(i,r,t,o,0):i[r]=E(t)),(t=e[r="minE"])!=n&&((y=-C>t||t>0)||a(t)!=t?p(i,r,t,o,0):i[r]=E(t)),(t=e[r="maxE"])!=n&&((y=0>t||t>C)||a(t)!=t?p(i,r,t,o,0):i[r]=E(t)),(t=e[r="errors"])!=n&&(t===!!t||1===t||0===t?(y=b=0,i[r]=!!t):p(i,r,t,o,1)),(t=e[r="crypto"])!=n&&(t===!!t||1===t||0===t?i[r]=!(!t||!w||"object"!=typeof w):p(i,r,t,o,1)),(t=e[r="modulo"])!=n&&((y=0>t||t>9)||a(t)!=t?p(i,r,t,o,0):i[r]=0|t),i)}function r(e){return new this(e).exp()}function n(e){return new this(e).ln()}function t(e,r){return new this(e).log(r)}function i(e,r,n){var t,i,o=0;for("[object Array]"==M.call(r[0])&&(r=r[0]),t=new e(r[0]);++o<r.length;){if(i=new e(r[o]),!i.s){t=i;break}t[n](i)&&(t=i)}return t}function o(){return i(this,arguments,"lt")}function a(){return i(this,arguments,"gt")}function s(e,r){return new this(e).pow(r)}function f(e){var r,n,t,i=0,o=[],a=this,s=new a(a.ONE);if(null!=e&&u(s,e,"random")?e|=0:e=a.precision,n=Math.ceil(e/T),a.crypto)if(w&&w.getRandomValues)for(r=w.getRandomValues(new Uint32Array(n));n>i;)t=r[i],t>=429e7?r[i]=w.getRandomValues(new Uint32Array(1))[0]:o[i++]=t%1e7;else if(w&&w.randomBytes){for(r=w.randomBytes(n*=4);n>i;)t=r[i]+(r[i+1]<<8)+(r[i+2]<<16)+((127&r[i+3])<<24),t>=214e7?w.randomBytes(4).copy(r,i):(o.push(t%1e7),i+=4);i=n/4}else p(a,"crypto unavailable",w,"random");if(!i)for(;n>i;)o[i++]=1e7*Math.random()|0;for(n=o[--i],e%=T,n&&e&&(t=N(10,T-e),o[i]=(n/t|0)*t);0===o[i];i--)o.pop();if(0>i)o=[n=0];else{for(n=-1;0===o[0];)o.shift(),n-=T;for(i=1,t=o[0];t>=10;)t/=10,i++;T>i&&(n-=T-i)}return s.e=n,s.c=o,s}function c(e){return new this(e).sqrt()}function l(i){function u(e,r){var n=this;if(!(n instanceof u))return p(u,"Decimal called without new",e),new u(e,r);if(e instanceof u){if(null==r)return b=0,n.constructor=e.constructor,n.s=e.s,n.e=e.e,void(n.c=(e=e.c)?e.slice():e);if(10==r)return g(new u(e),u.precision,u.rounding);e+=""}return m(n.constructor=u,n,e,r)}return u.precision=20,u.rounding=4,u.modulo=1,u.toExpNeg=-7,u.toExpPos=21,u.minE=-C,u.maxE=C,u.errors=!0,u.crypto=!1,u.prototype=O,u.ONE=new u(1),u.ROUND_UP=0,u.ROUND_DOWN=1,u.ROUND_CEIL=2,u.ROUND_FLOOR=3,u.ROUND_HALF_UP=4,u.ROUND_HALF_DOWN=5,u.ROUND_HALF_EVEN=6,u.ROUND_HALF_CEIL=7,u.ROUND_HALF_FLOOR=8,u.EUCLID=9,u.config=e,u.constructor=l,u.exp=r,u.ln=n,u.log=t,u.max=o,u.min=a,u.pow=s,u.sqrt=c,u.random=f,null!=i&&u.config(i),u}var m=function(){var e=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,r=String.prototype.trim||function(){return this.replace(/^\s+|\s+$/g,"")};return function(n,t,i,o){var a,s,u,f,c,l;if("string"!=typeof i&&(i=(f="number"==typeof i||"[object Number]"==M.call(i))&&0===i&&0>1/i?"-0":i+""),c=i,o==s&&e.test(i))t.s="-"==i.charAt(0)?(i=i.slice(1),-1):1;else{if(10==o)return g(new n(i),n.precision,n.rounding);if(i=r.call(i).replace(/^\+(?!-)/,""),t.s="-"==i.charAt(0)?(i=i.replace(/^-(?!-)/,""),-1):1,o!=s?o!=(0|o)&&n.errors||(y=!(o>=2&&65>o))?(p(n,"base",o,0,0),l=e.test(i)):(a="["+S.slice(0,o=0|o)+"]+",i=i.replace(/\.$/,"").replace(/^\./,"0."),(l=new RegExp("^"+a+"(?:\\."+a+")?$",37>o?"i":"").test(i))?(f&&(i.replace(/^0\.0*|\./,"").length>15&&p(n,0,c),f=!f),i=d(n,i,10,o,t.s)):"Infinity"!=i&&"NaN"!=i&&(p(n,"not a base "+o+" number",c),i="NaN")):l=e.test(i),!l)return t.c=t.e=null,"Infinity"!=i&&("NaN"!=i&&p(n,"not a number",c),t.s=null),b=0,t}for((s=i.indexOf("."))>-1&&(i=i.replace(".","")),(u=i.search(/e/i))>0?(0>s&&(s=u),s+=+i.slice(u+1),i=i.substring(0,u)):0>s&&(s=i.length),u=0;"0"==i.charAt(u);u++);for(o=i.length;"0"==i.charAt(--o););if(i=i.slice(u,o+1)){if(o=i.length,f&&o>15&&p(n,0,c),t.e=s=s-u-1,t.c=[],u=(s+1)%T,0>s&&(u+=T),o>u){for(u&&t.c.push(+i.slice(0,u)),o-=T;o>u;)t.c.push(+i.slice(u,u+=T));i=i.slice(u),u=T-i.length}else u-=o;for(;u--;i+="0");t.c.push(+i),v&&(t.e>n.maxE?t.c=t.e=null:t.e<n.minE&&(t.c=[t.e=0]))}else t.c=[t.e=0];b=0}}();return l()}(),t=function(){return x}.call(r,n,r,e),!(void 0!==t&&(e.exports=t))}(this)},function(e,r,n){"use strict";r.array=n(136),r["boolean"]=n(158),r.number=n(4),r.bignumber=n(135),r.object=n(3),r.string=n(159),r.types=n(178)},function(e,r,n){"use strict";function t(e){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(this.nodes=e||[],!a(this.nodes)||!this.nodes.every(s))throw new TypeError("Array containing Nodes expected")}var i=n(152),o=(n(3),n(159)),a=(n(13),n(143),Array.isArray),s=i.isNode;t.prototype=new i,t.prototype.type="ArrayNode",t.prototype._compile=function(e){var r="array"!==e.math.config().matrix,n=this.nodes.map(function(r){return r._compile(e)});return(r?"math.matrix([":"[")+n.join(",")+(r?"])":"]")},t.prototype.find=function(e){var r=[];this.match(e)&&r.push(this);for(var n=this.nodes,t=0,i=n.length;i>t;t++)r=r.concat(n[t].find(e));return r},t.prototype.toString=function(){return o.format(this.nodes)},t.prototype.toTex=function(e){e=e||"bmatrix";var r="\\begin{"+e+"}";return this.nodes.forEach(function(e){r+=e.nodes?e.nodes.map(function(e){return e.toTex()}).join("&"):e.toTex(),r+="\\\\"}),r+="\\end{"+e+"}"},e.exports=t},function(e,r,n){"use strict";function t(e,r){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(!u(e))throw new TypeError('String expected for parameter "name"');if(!(r instanceof i))throw new TypeError('Node expected for parameter "expr"');if(e in a)throw new Error('Illegal symbol name, "'+e+'" is a reserved keyword');this.name=e,this.expr=r}var i=n(152),o=n(144),a=n(281),s=n(282),u=n(159).isString;t.prototype=new i,t.prototype.type="AssignmentNode",t.prototype._compile=function(e){return'scope["'+this.name+'"] = '+this.expr._compile(e)},t.prototype.find=function(e){var r=[];return this.match(e)&&r.push(this),r=r.concat(this.expr.find(e))},t.prototype.toString=function(){return this.name+" = "+this.expr.toString()},t.prototype.toTex=function(){var e;return this.expr instanceof o&&(e=["\\mathbf{","}"]),s.addBraces(s.toSymbol(this.name),e)+"="+s.addBraces(this.expr.toTex())},e.exports=t},function(e,r,n){"use strict";function t(){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");this.params=[]}var i=n(152),o=n(12),a=n(158).isBoolean;t.prototype=new i,t.prototype.type="BlockNode",t.prototype.add=function(e,r){if(void 0===r&&(r=!0),!(e instanceof i))throw new TypeError('Node expected for parameter "expr"');if(!a(r))throw new TypeError('Boolean expected for parameter "visible"');var n=this.params.length;this.params[n]={node:e,visible:r}},t.prototype._compile=function(e){e.ResultSet=o;var r=this.params.map(function(r){var n=r.node._compile(e);return r.visible?"results.push("+n+");":n+";"});return"(function () {var results = [];"+r.join("")+"return new ResultSet(results);})()"},t.prototype.find=function(e){var r=[];this.match(e)&&r.push(this);for(var n=this.params,t=0,i=n.length;i>t;t++)r=r.concat(n[t].node.find(e));return r},t.prototype.toString=function(){return this.params.map(function(e){return e.node.toString()+(e.visible?"":";")}).join("\n")},t.prototype.toTex=function(){return this.params.map(function(e){return e.node.toTex()+(e.visible?"":";")}).join("\n")},e.exports=t},function(e,r,n){"use strict";function t(e,r,n){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(!(e instanceof i))throw new TypeError("Parameter condition must be a Node");if(!(r instanceof i))throw new TypeError("Parameter trueExpr must be a Node");if(!(n instanceof i))throw new TypeError("Parameter falseExpr must be a Node");this.condition=e,this.trueExpr=r,this.falseExpr=n}var i=n(152),o=n(282),a=n(142),s=n(6),u=n(10),f=n(143),c=f.string.isString,l=f.number.isNumber,p=f["boolean"].isBoolean;t.prototype=new i,t.prototype.type="ConditionalNode",t.prototype._compile=function(e){return e.testCondition=function(r){if(l(r)||p(r)||c(r))return r?!0:!1;if(r instanceof a)return r.isZero()?!1:!0;if(r instanceof s)return r.re||r.im?!0:!1;if(r instanceof u)return r.value?!0:!1;if(null===r||void 0===r)return!1;throw new TypeError('Unsupported type of condition "'+e.math["typeof"](r)+'"')
},"testCondition("+this.condition._compile(e)+") ? ( "+this.trueExpr._compile(e)+") : ( "+this.falseExpr._compile(e)+")"},t.prototype.find=function(e){var r=[];return this.match(e)&&r.push(this),r=r.concat(this.condition.find(e),this.trueExpr.find(e),this.falseExpr.find(e))},t.prototype.toString=function(){return"("+this.condition.toString()+") ? ("+this.trueExpr.toString()+") : ("+this.falseExpr.toString()+")"},t.prototype.toTex=function(){var e=o.addBraces(this.trueExpr.toTex())+", &\\quad"+o.addBraces("\\text{if}\\;"+this.condition.toTex())+"\\\\"+(o.addBraces(this.falseExpr.toTex())+", &\\quad"+o.addBraces("\\text{otherwise}"));return o.addBraces(e,["\\left\\{\\begin{array}{l l}","\\end{array}\\right."])},e.exports=t},function(e,r,n){"use strict";function t(e,r){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(r){if(!a(r))throw new TypeError('String expected for parameter "valueType"');if(!a(e))throw new TypeError('String expected for parameter "value"');this.value=e,this.valueType=r}else this.value=e+"",this.valueType=o(e);if(!s[this.valueType])throw new TypeError('Unsupported type of value "'+this.valueType+'"')}var i=n(152),o=(n(142),n(178).type),a=n(159).isString,s={number:!0,string:!0,"boolean":!0,undefined:!0,"null":!0};t.prototype=new i,t.prototype.type="ConstantNode",t.prototype._compile=function(e){switch(this.valueType){case"number":return"bignumber"===e.math.config().number?'math.bignumber("'+this.value+'")':this.value.replace(/^(0*)[0-9]/,function(e,r){return e.substring(r.length)});case"string":return'"'+this.value+'"';case"boolean":return this.value;case"undefined":return this.value;case"null":return this.value;default:throw new TypeError('Unsupported type of constant "'+this.valueType+'"')}},t.prototype.toString=function(){switch(this.valueType){case"string":return'"'+this.value+'"';default:return this.value}},t.prototype.toTex=function(){var e,r=this.value;switch(this.valueType){case"string":return"\\text{"+r+"}";case"number":return e=r.toLowerCase().indexOf("e"),-1!==e?r.substring(0,e)+" \\cdot 10^{"+r.substring(e+1)+"}":r;default:return r}},e.exports=t},function(e,r,n){"use strict";function t(e,r){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(!(e instanceof i))throw new TypeError('Node expected for parameter "object"');if(!u(r)||!r.every(s))throw new TypeError('Array containing Nodes expected for parameter "ranges"');this.object=e,this.ranges=r}var i=n(152),o=n(154),a=n(155),s=i.isNode,u=Array.isArray;t.prototype=new i,t.prototype.type="IndexNode",t.prototype._compile=function(e){return this.compileSubset(e)},t.prototype.compileSubset=function(e,r){var n={type:a,properties:{name:"end"}},t=!1,i=this.ranges.map(function(e){var r=e.find(n).length>0;return t=r?r:t,r}),s=this.ranges.map(function(r,n){var t=i[n];return r instanceof o?t?'(function (scope) {  scope = Object.create(scope);   scope["end"] = size['+n+"];  return [    "+r.start._compile(e)+",     "+r.end._compile(e)+",     "+(r.step?r.step._compile(e):"1")+"  ];})(scope)":"(function () {  return [    "+r.start._compile(e)+",     "+r.end._compile(e)+",     "+(r.step?r.step._compile(e):"1")+"  ];})()":t?'(function (scope) {  scope = Object.create(scope);   scope["end"] = size['+n+"];  return "+r._compile(e)+";})(scope)":r._compile(e)});return t?"(function () {  var obj = "+this.object._compile(e)+";  var size = math.size(obj).valueOf();  return math.subset(    obj,     math.index("+s.join(", ")+")    "+(r?", "+r:"")+"  );})()":"math.subset("+this.object._compile(e)+",math.index("+s.join(", ")+")"+(r?", "+r:"")+")"},t.prototype.find=function(e){var r=[];this.match(e)&&r.push(this),r=r.concat(this.object.find(e));for(var n=this.ranges,t=0,i=n.length;i>t;t++)r=r.concat(n[t].find(e));return r},t.prototype.objectName=function(){return this.object.name},t.prototype.toString=function(){return this.object.toString()+"["+this.ranges.join(", ")+"]"},t.prototype.toTex=function(){return this.object.toTex()+"["+this.ranges.join(", ")+"]"},e.exports=t},function(e,r,n){"use strict";function t(e,r,n){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(!s(e))throw new TypeError('String expected for parameter "name"');if(!u(r)||!r.every(s))throw new TypeError('Array containing strings expected for parameter "args"');if(!(n instanceof i))throw new TypeError('Node expected for parameter "expr"');if(e in o)throw new Error('Illegal function name, "'+e+'" is a reserved keyword');this.name=e,this.args=r,this.expr=n}var i=n(152),o=n(281),a=n(282),s=n(159).isString,u=Array.isArray;t.prototype=new i,t.prototype.type="FunctionAssignmentNode",t.prototype._compile=function(e){return'scope["'+this.name+'"] =   (function (scope) {    scope = Object.create(scope);     var fn = function '+this.name+"("+this.args.join(",")+") {      if (arguments.length != "+this.args.length+') {        throw new SyntaxError("Wrong number of arguments in function '+this.name+' (" + arguments.length + " provided, '+this.args.length+' expected)");      }'+this.args.map(function(e,r){return'scope["'+e+'"] = arguments['+r+"];"}).join("")+"      return "+this.expr._compile(e)+'    };    fn.syntax = "'+this.name+"("+this.args.join(", ")+')";    return fn;  })(scope);'},t.prototype.find=function(e){var r=[];return this.match(e)&&r.push(this),r=r.concat(this.expr.find(e))},t.prototype.toString=function(){return"function "+this.name+"("+this.args.join(", ")+") = "+this.expr.toString()},t.prototype.toTex=function(){return this.name+a.addBraces(this.args.map(a.toSymbol).join(", "),!0)+"="+a.addBraces(this.expr.toTex())},e.exports=t},function(e,r,n){"use strict";function t(e,r){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(!(e instanceof i))throw new TypeError('SymbolNode expected for parameter "symbol"');if(!s(r)||!r.every(a))throw new TypeError('Array containing Nodes expected for parameter "params"');this.symbol=e,this.params=r}var i=n(152),o=n(282),a=i.isNode,s=Array.isArray;t.prototype=new i,t.prototype.type="FunctionNode",t.prototype._compile=function(e){var r=e.math[this.symbol.name],n="function"==typeof r&&1==r.rawArgs,t=this.params.map(function(r){return r._compile(e)});if(n){var i,o=this.symbol.name;do i="p"+Math.round(1e4*Math.random());while(i in e);return e[i]=this.params,'("'+o+'" in scope ? scope["'+o+'"]('+t.join(", ")+') : math["'+o+'"]('+i+", math, scope))"}return this.symbol._compile(e)+"("+t.join(", ")+")"},t.prototype.find=function(e){var r=[];this.match(e)&&r.push(this),r=r.concat(this.symbol.find(e));for(var n=this.params,t=0,i=n.length;i>t;t++)r=r.concat(n[t].find(e));return r},t.prototype.toString=function(){return this.symbol.toString()+"("+this.params.join(", ")+")"},t.prototype.toTex=function(){return o.toParams(this)},e.exports=t},function(e,r,n){"use strict";function t(){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator")}function i(e){for(var r in e)if(e.hasOwnProperty(r)&&r in a)throw new Error('Scope contains an illegal symbol, "'+r+'" is a reserved keyword')}function o(e){var r=Object.create(e);for(var n in e)if(e.hasOwnProperty(n)){var t=e[n],i=t&&t.transform;i&&(r[n]=i)}return r}var a=n(281);t.prototype.eval=function(){throw new Error("Node.eval is deprecated. Use Node.compile(math).eval([scope]) instead.")},t.prototype.type="Node",t.prototype.compile=function(e){if(!(e instanceof Object))throw new TypeError("Object expected for parameter math");var r={math:o(e),_validateScope:i},n=this._compile(r),t=Object.keys(r).map(function(e){return"    var "+e+' = defs["'+e+'"];'}),a=t.join(" ")+'return {  "eval": function (scope) {    if (scope) _validateScope(scope);    scope = scope || {};    return '+n+";  }};",s=new Function("defs",a);return s(r)},t.prototype._compile=function(){throw new Error("Cannot compile a Node interface")},t.prototype.find=function(e){return this.match(e)?[this]:[]},t.prototype.match=function(e){var r=!0;if(e){!e.type||this instanceof e.type||(r=!1);var n=e.properties;if(r&&n)for(var t in n)if(n.hasOwnProperty(t)&&this[t]!==n[t]){r=!1;break}}return r},t.prototype.toString=function(){return""},t.prototype.toTex=function(){return""},t.isNode=function(e){return e instanceof t},e.exports=t},function(e,r,n){"use strict";function t(e,r,n){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");this.op=e,this.fn=r,this.params=n}var i=n(152),o=n(148),a=n(155),s=n(151),u=n(282);t.prototype=new i,t.prototype.type="OperatorNode",t.prototype._compile=function(e){if(!(this.fn in e.math))throw new Error("Function "+this.fn+' missing in provided namespace "math"');var r=this.params.map(function(r){return r._compile(e)});return"math."+this.fn+"("+r.join(", ")+")"},t.prototype.find=function(e){var r=[];this.match(e)&&r.push(this);var n=this.params;if(n)for(var t=0,i=n.length;i>t;t++)r=r.concat(n[t].find(e));return r},t.prototype.toString=function(){var e=this.params;switch(e.length){case 1:return"-"==this.op?"-"+e[0].toString():e[0].toString()+this.op;case 2:var r=e[0].toString();e[0]instanceof t&&(r="("+r+")");var n=e[1].toString();return e[1]instanceof t&&(n="("+n+")"),r+" "+this.op+" "+n;default:return this.op+"("+this.params.join(", ")+")"}},t.prototype.toTex=function(){var e=this.params,r=u.toOperator(this.op),n=e[0],i=e[1];switch(e.length){case 1:return"-"===this.op||"+"===this.op?this.op+n.toTex():n.toTex()+this.op;case 2:var f=n.toTex(),c=!1,l=i.toTex(),p=!1,m="",h="";switch(this.op){case"/":m=r,r="";break;case"*":n instanceof t&&("+"===n.op||"-"===n.op)&&(c=!0),i instanceof t&&("+"===i.op||"-"===i.op?p=!0:"*"===i.op&&(p=!0)),r=(n instanceof o||n instanceof t)&&(i instanceof o||i instanceof t)?" \\cdot ":" \\, ";break;case"^":n instanceof t||n instanceof s?c=!0:n instanceof a&&(c=null);break;case"to":l=u.toUnit(l,!0)}return f=u.addBraces(f,c),l=u.addBraces(l,p),m+f+r+l+h;default:return r+"("+this.params.map(u.toSymbol).join(", ")+")"}},e.exports=t},function(e,r,n){"use strict";function t(e){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(!Array.isArray(e)||2!=e.length&&3!=e.length||!e.every(o))throw new TypeError('Expected an Array containing 2 or 3 Nodes as parameter "params"');this.start=e[0],this.end=e[1],this.step=e[2]}var i=n(152),o=i.isNode;t.prototype=new i,t.prototype.type="RangeNode",t.prototype._compile=function(e){return"math.range("+this.start._compile(e)+", "+this.end._compile(e)+(this.step?", "+this.step._compile(e):"")+")"},t.prototype.find=function(e){var r=[];return this.match(e)&&r.push(this),r=r.concat(this.start.find(e)),this.step&&(r=r.concat(this.step.find(e))),r=r.concat(this.end.find(e))},t.prototype.toString=function(){var e=this.start.toString();return this.step&&(e+=":"+this.step.toString()),e+=":"+this.end.toString()},t.prototype.toTex=function(){var e=this.start.toTex();return this.step&&(e+=":"+this.step.toTex()),e+=":"+this.end.toTex()},e.exports=t},function(e,r,n){"use strict";function t(e){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(!u(e))throw new TypeError('String expected for parameter "name"');this.name=e}function i(e){throw new Error("Undefined symbol "+e)}var o=n(152),a=n(10),s=n(282),u=n(159).isString;t.prototype=new o,t.prototype.type="SymbolNode",t.prototype._compile=function(e){return e.undef=i,e.Unit=a,this.name in e.math?'("'+this.name+'" in scope ? scope["'+this.name+'"] : math["'+this.name+'"])':'("'+this.name+'" in scope ? scope["'+this.name+'"] : '+(a.isValuelessUnit(this.name)?'new Unit(null, "'+this.name+'")':'undef("'+this.name+'")')+")"},t.prototype.toString=function(){return this.name},t.prototype.toTex=function(){return s.toSymbol(this.name)},e.exports=t},function(e,r,n){"use strict";function t(e,r){if(!(this instanceof t))throw new SyntaxError("Constructor must be called with the new operator");if(!(e instanceof o))throw new TypeError('Expected IndexNode for parameter "index"');if(!(r instanceof i))throw new TypeError('Expected Node for parameter "expr"');this.index=e,this.expr=r}var i=n(152),o=n(149);t.prototype=new i,t.prototype.type="UpdateNode",t.prototype._compile=function(e){return'scope["'+this.index.objectName()+'"] = '+this.index.compileSubset(e,this.expr._compile(e))},t.prototype.find=function(e){var r=[];return this.match(e)&&r.push(this),r=r.concat(this.index.find(e)),r=r.concat(this.expr.find(e))},t.prototype.toString=function(){return this.index.toString()+" = "+this.expr.toString()},t.prototype.toTex=function(){return this.index.toTex()+" = "+this.expr.toTex()},e.exports=t},function(e,r,n){var t=(n(139),n(140));r.transform=function(e){return e instanceof t?new t(e.index+1,e.min+1,e.max+1):e}},function(e,r){"use strict";r.isBoolean=function(e){return e instanceof Boolean||"boolean"==typeof e}},function(e,r,n){"use strict";function t(e,n){if(Array.isArray(e)){for(var i="[",o=e.length,a=0;o>a;a++)0!=a&&(i+=", "),i+=t(e[a],n);return i+="]"}return r.format(e,n)}var i=n(4),o=n(135),a=n(142);r.isString=function(e){return e instanceof String||"string"==typeof e},r.endsWith=function(e,r){var n=e.length-r.length,t=e.length;return e.substring(n,t)===r},r.format=function(e,n){return i.isNumber(e)?i.format(e,n):e instanceof a?o.format(e,n):Array.isArray(e)?t(e,n):r.isString(e)?'"'+e+'"':"function"==typeof e?e.syntax?e.syntax+"":"function":e instanceof Object?"function"==typeof e.format?e.format(n):e.toString():String(e)}},function(e){e.exports={name:"e",category:"Constants",syntax:["e"],description:"Euler's number, the base of the natural logarithm. Approximately equal to 2.71828",examples:["e","e ^ 2","exp(2)","log(e)"],seealso:["exp"]}},function(e){e.exports={name:"false",category:"Constants",syntax:["false"],description:"Boolean value false",examples:["false"],seealso:["true"]}},function(e){e.exports={name:"i",category:"Constants",syntax:["i"],description:"Imaginary unit, defined as i*i=-1. A complex number is described as a + b*i, where a is the real part, and b is the imaginary part.",examples:["i","i * i","sqrt(-1)"],seealso:[]}},function(e){e.exports={name:"Infinity",category:"Constants",syntax:["Infinity"],description:"Infinity, a number which is larger than the maximum number that can be handled by a floating point number.",examples:["Infinity","1 / 0"],seealso:[]}},function(e){e.exports={name:"LN2",category:"Constants",syntax:["LN2"],description:"Returns the natural logarithm of 2, approximately equal to 0.693",examples:["LN2","log(2)"],seealso:[]}},function(e){e.exports={name:"LN10",category:"Constants",syntax:["LN10"],description:"Returns the natural logarithm of 10, approximately equal to 2.302",examples:["LN10","log(10)"],seealso:[]}},function(e){e.exports={name:"LOG2E",category:"Constants",syntax:["LOG2E"],description:"Returns the base-2 logarithm of E, approximately equal to 1.442",examples:["LOG2E","log(e, 2)"],seealso:[]}},function(e){e.exports={name:"LOG10E",category:"Constants",syntax:["LOG10E"],description:"Returns the base-10 logarithm of E, approximately equal to 0.434",examples:["LOG10E","log(e, 10)"],seealso:[]}},function(e){e.exports={name:"NaN",category:"Constants",syntax:["NaN"],description:"Not a number",examples:["NaN","0 / 0"],seealso:[]}},function(e){e.exports={name:"null",category:"Constants",syntax:["null"],description:"Value null",examples:["null"],seealso:["true","false"]}},function(e){e.exports={name:"pi",category:"Constants",syntax:["pi"],description:"The number pi is a mathematical constant that is the ratio of a circle's circumference to its diameter, and is approximately equal to 3.14159",examples:["pi","sin(pi/2)"],seealso:["tau"]}},function(e){e.exports={name:"phi",category:"Constants",syntax:["phi"],description:"Phi is the golden ratio. Two quantities are in the golden ratio if their ratio is the same as the ratio of their sum to the larger of the two quantities. Phi is defined as `(1 + sqrt(5)) / 2` and is approximately 1.618034...",examples:["tau"],seealso:[]}},function(e){e.exports={name:"SQRT1_2",category:"Constants",syntax:["SQRT1_2"],description:"Returns the square root of 1/2, approximately equal to 0.707",examples:["SQRT1_2","sqrt(1/2)"],seealso:[]}},function(e){e.exports={name:"SQRT2",category:"Constants",syntax:["SQRT2"],description:"Returns the square root of 2, approximately equal to 1.414",examples:["SQRT2","sqrt(2)"],seealso:[]}},function(e){e.exports={name:"tau",category:"Constants",syntax:["tau"],description:"Tau is the ratio constant of a circle's circumference to radius, equal to 2 * pi, approximately 6.2832.",examples:["tau","2 * pi"],seealso:["pi"]}},function(e){e.exports={name:"true",category:"Constants",syntax:["true"],description:"Boolean value true",examples:["true"],seealso:["false"]}},function(e){e.exports={name:"version",category:"Constants",syntax:["version"],description:"A string with the version number of math.js",examples:["version"],seealso:[]}},function(e,r,n){function t(e){return n(i(e))}function i(e){return o[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var o={"./clone":127,"./clone.js":127,"./forEach":134,"./forEach.js":134,"./format":128,"./format.js":128,"./import":129,"./import.js":129,"./map":130,"./map.js":130,"./print":131,"./print.js":131,"./sort":132,"./sort.js":132,"./typeof":133,"./typeof.js":133};t.keys=function(){return Object.keys(o)},t.resolve=i,e.exports=t},function(e,r){"use strict";r.type=function(e){var r=typeof e;if("object"===r){if(null===e)return"null";if(e instanceof Boolean)return"boolean";if(e instanceof Number)return"number";if(e instanceof String)return"string";if(Array.isArray(e))return"array";if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return r}},function(e){e.exports={name:"abs",category:"Arithmetic",syntax:["abs(x)"],description:"Compute the absolute value.",examples:["abs(3.5)","abs(-4.2)"],seealso:["sign"]}},function(e){e.exports={name:"add",category:"Operators",syntax:["x + y","add(x, y)"],description:"Add two values.",examples:["a = 2.1 + 3.6","a - 3.6","3 + 2i",'"hello" + " world"',"3 cm + 2 inch"],seealso:["subtract"]}},function(e){e.exports={name:"ceil",category:"Arithmetic",syntax:["ceil(x)"],description:"Round a value towards plus infinity. If x is complex, both real and imaginary part are rounded towards plus infinity.",examples:["ceil(3.2)","ceil(3.8)","ceil(-4.2)"],seealso:["floor","fix","round"]}},function(e){e.exports={name:"cube",category:"Arithmetic",syntax:["cube(x)"],description:"Compute the cube of a value. The cube of x is x * x * x.",examples:["cube(2)","2^3","2 * 2 * 2"],seealso:["multiply","square","pow"]}},function(e){e.exports={name:"divide",category:"Operators",syntax:["x / y","divide(x, y)"],description:"Divide two values.",examples:["a = 2 / 3","a * 3","4.5 / 2","3 + 4 / 2","(3 + 4) / 2","18 km / 4.5"],seealso:["multiply"]}},function(e){e.exports={name:"dotDivide",category:"Operators",syntax:["x ./ y","dotDivide(x, y)"],description:"Divide two values element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","b = [2, 1, 1; 3, 2, 5]","a ./ b"],seealso:["multiply","dotMultiply","divide"]}},function(e){e.exports={name:"dotMultiply",category:"Operators",syntax:["x .* y","dotMultiply(x, y)"],description:"Multiply two values element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","b = [2, 1, 1; 3, 2, 5]","a .* b"],seealso:["multiply","divide","dotDivide"]}},function(e){e.exports={name:"dotpow",category:"Operators",syntax:["x .^ y","dotpow(x, y)"],description:"Calculates the power of x to y element wise.",examples:["a = [1, 2, 3; 4, 5, 6]","a .^ 2"],seealso:["pow"]}},function(e){e.exports={name:"exp",category:"Arithmetic",syntax:["exp(x)"],description:"Calculate the exponent of a value.",examples:["exp(1.3)","e ^ 1.3","log(exp(1.3))","x = 2.4","(exp(i*x) == cos(x) + i*sin(x))   # Euler's formula"],seealso:["pow","log"]}},function(e){e.exports={name:"fix",category:"Arithmetic",syntax:["fix(x)"],description:"Round a value towards zero. If x is complex, both real and imaginary part are rounded towards zero.",examples:["fix(3.2)","fix(3.8)","fix(-4.2)","fix(-4.8)"],seealso:["ceil","floor","round"]}},function(e){e.exports={name:"floor",category:"Arithmetic",syntax:["floor(x)"],description:"Round a value towards minus infinity.If x is complex, both real and imaginary part are rounded towards minus infinity.",examples:["floor(3.2)","floor(3.8)","floor(-4.2)"],seealso:["ceil","fix","round"]}},function(e){e.exports={name:"gcd",category:"Arithmetic",syntax:["gcd(a, b)","gcd(a, b, c, ...)"],description:"Compute the greatest common divisor.",examples:["gcd(8, 12)","gcd(-4, 6)","gcd(25, 15, -10)"],seealso:["lcm","xgcd"]}},function(e){e.exports={name:"lcm",category:"Arithmetic",syntax:["lcm(x, y)"],description:"Compute the least common multiple.",examples:["lcm(4, 6)","lcm(6, 21)","lcm(6, 21, 5)"],seealso:["gcd"]}},function(e){e.exports={name:"log",category:"Arithmetic",syntax:["log(x)","log(x, base)"],description:"Compute the logarithm of a value. If no base is provided, the natural logarithm of x is calculated. If base if provided, the logarithm is calculated for the specified base. log(x, base) is defined as log(x) / log(base).",examples:["log(3.5)","a = log(2.4)","exp(a)","10 ^ 4","log(10000, 10)","log(10000) / log(10)","b = log(1024, 2)","2 ^ b"],seealso:["exp","log10"]}},function(e){e.exports={name:"log10",category:"Arithmetic",syntax:["log10(x)"],description:"Compute the 10-base logarithm of a value.",examples:["log10(0.00001)","log10(10000)","10 ^ 4","log(10000) / log(10)","log(10000, 10)"],seealso:["exp","log"]}},function(e){e.exports={name:"mod",category:"Operators",syntax:["x % y","x mod y","mod(x, y)"],description:"Calculates the modulus, the remainder of an integer division.",examples:["7 % 3","11 % 2","10 mod 4","function isOdd(x) = x % 2","isOdd(2)","isOdd(3)"],seealso:["divide"]}},function(e){e.exports={name:"multiply",category:"Operators",syntax:["x * y","multiply(x, y)"],description:"multiply two values.",examples:["a = 2.1 * 3.4","a / 3.4","2 * 3 + 4","2 * (3 + 4)","3 * 2.1 km"],seealso:["divide"]}},function(e){e.exports={name:"norm",category:"Arithmetic",syntax:["norm(x)","norm(x, p)"],description:"Calculate the norm of a number, vector or matrix.",examples:["abs(-3.5)","norm(-3.5)","norm(3 - 4i))","norm([1, 2, -3], Infinity)","norm([1, 2, -3], -Infinity)","norm([3, 4], 2)","norm([[1, 2], [3, 4]], 1)","norm([[1, 2], [3, 4]], 'inf')","norm([[1, 2], [3, 4]], 'fro')"]}},function(e){e.exports={name:"pow",category:"Operators",syntax:["x ^ y","pow(x, y)"],description:"Calculates the power of x to y, x^y.",examples:["2^3 = 8","2*2*2","1 + e ^ (pi * i)"],seealso:["multiply"]}},function(e){e.exports={name:"round",category:"Arithmetic",syntax:["round(x)","round(x, n)"],description:"round a value towards the nearest integer.If x is complex, both real and imaginary part are rounded towards the nearest integer. When n is specified, the value is rounded to n decimals.",examples:["round(3.2)","round(3.8)","round(-4.2)","round(-4.8)","round(pi, 3)","round(123.45678, 2)"],seealso:["ceil","floor","fix"]}},function(e){e.exports={name:"sign",category:"Arithmetic",syntax:["sign(x)"],description:"Compute the sign of a value. The sign of a value x is 1 when x>1, -1 when x<0, and 0 when x=0.",examples:["sign(3.5)","sign(-4.2)","sign(0)"],seealso:["abs"]}},function(e){e.exports={name:"sqrt",category:"Arithmetic",syntax:["sqrt(x)"],description:"Compute the square root value. If x = y * y, then y is the square root of x.",examples:["sqrt(25)","5 * 5","sqrt(-1)"],seealso:["square","multiply"]}},function(e){e.exports={name:"square",category:"Arithmetic",syntax:["square(x)"],description:"Compute the square of a value. The square of x is x * x.",examples:["square(3)","sqrt(9)","3^2","3 * 3"],seealso:["multiply","pow","sqrt","cube"]}},function(e){e.exports={name:"subtract",category:"Operators",syntax:["x - y","subtract(x, y)"],description:"subtract two values.",examples:["a = 5.3 - 2","a + 2","2/3 - 1/6","2 * 3 - 3","2.1 km - 500m"],seealso:["add"]}},function(e){e.exports={name:"unaryMinus",category:"Operators",syntax:["-x","unaryMinus(x)"],description:"Inverse the sign of a value. Converts booleans and strings to numbers.",examples:["-4.5","-(-5.6)",'-"22"'],seealso:["add","subtract","unaryPlus"]}},function(e){e.exports={name:"unaryPlus",category:"Operators",syntax:["+x","unaryPlus(x)"],description:"Converts booleans and strings to numbers.",examples:["+true",'+"2"'],seealso:["add","subtract","unaryMinus"]}},function(e){e.exports={name:"xgcd",category:"Arithmetic",syntax:["xgcd(a, b)"],description:"Calculate the extended greatest common divisor for two values",examples:["xgcd(8, 12)","gcd(8, 12)","xgcd(36163, 21199)"],seealso:["gcd","lcm"]}},function(e){e.exports={name:"compare",category:"Relational",syntax:["compare(x, y)"],description:"Compare two values. Returns 1 if x is larger than y, -1 if x is smaller than y, and 0 if x and y are equal.",examples:["compare(2, 3)","compare(3, 2)","compare(2, 2)","compare(5cm, 40mm)","compare(2, [1, 2, 3])"],seealso:["equal","unequal","smaller","smallerEq","largerEq"]}},function(e){e.exports={name:"deepEqual",category:"Relational",syntax:["deepEqual(x, y)"],description:"Check equality of two matrices element wise. Returns true if the size of both matrices is equal and when and each of the elements are equal.",examples:["[1,3,4] == [1,3,4]","[1,3,4] == [1,3]"],seealso:["equal","unequal","smaller","larger","smallerEq","largerEq","compare"]}},function(e){e.exports={name:"equal",category:"Relational",syntax:["x == y","equal(x, y)"],description:"Check equality of two values. Returns true if the values are equal, and false if not.",examples:["2+2 == 3","2+2 == 4","a = 3.2","b = 6-2.8","a == b","50cm == 0.5m"],seealso:["unequal","smaller","larger","smallerEq","largerEq","compare","deepEqual"]}},function(e){e.exports={name:"larger",category:"Relational",syntax:["x > y","larger(x, y)"],description:"Check if value x is larger than y. Returns true if x is larger than y, and false if not.",examples:["2 > 3","5 > 2*2","a = 3.3","b = 6-2.8","(a > b)","(b < a)","5 cm > 2 inch"],seealso:["equal","unequal","smaller","smallerEq","largerEq","compare"]}},function(e){e.exports={name:"largerEq",category:"Relational",syntax:["x >= y","largerEq(x, y)"],description:"Check if value x is larger or equal to y. Returns true if x is larger or equal to y, and false if not.",examples:["2 > 1+1","2 >= 1+1","a = 3.2","b = 6-2.8","(a > b)"],seealso:["equal","unequal","smallerEq","smaller","largerEq","compare"]}},function(e){e.exports={name:"smaller",category:"Relational",syntax:["x < y","smaller(x, y)"],description:"Check if value x is smaller than value y. Returns true if x is smaller than y, and false if not.",examples:["2 < 3","5 < 2*2","a = 3.3","b = 6-2.8","(a < b)","5 cm < 2 inch"],seealso:["equal","unequal","larger","smallerEq","largerEq","compare"]}},function(e){e.exports={name:"smallerEq",category:"Relational",syntax:["x <= y","smallerEq(x, y)"],description:"Check if value x is smaller or equal to value y. Returns true if x is smaller than y, and false if not.",examples:["2 < 1+1","2 <= 1+1","a = 3.2","b = 6-2.8","(a < b)"],seealso:["equal","unequal","larger","smaller","largerEq","compare"]}},function(e){e.exports={name:"unequal",category:"Relational",syntax:["x != y","unequal(x, y)"],description:"Check unequality of two values. Returns true if the values are unequal, and false if they are equal.",examples:["2+2 != 3","2+2 != 4","a = 3.2","b = 6-2.8","a != b","50cm != 0.5m","5 cm != 2 inch"],seealso:["equal","smaller","larger","smallerEq","largerEq","compare","deepEqual"]}},function(e){e.exports={name:"arg",category:"Complex",syntax:["arg(x)"],description:"Compute the argument of a complex value. If x = a+bi, the argument is computed as atan2(b, a).",examples:["arg(2 + 2i)","atan2(3, 2)","arg(2 + 3i)"],seealso:["re","im","conj","abs"]}},function(e){e.exports={name:"conj",category:"Complex",syntax:["conj(x)"],description:"Compute the complex conjugate of a complex value. If x = a+bi, the complex conjugate is a-bi.",examples:["conj(2 + 3i)","conj(2 - 3i)","conj(-5.2i)"],seealso:["re","im","abs","arg"]}},function(e){e.exports={name:"re",category:"Complex",syntax:["re(x)"],description:"Get the real part of a complex number.",examples:["re(2 + 3i)","im(2 + 3i)","re(-5.2i)","re(2.4)"],seealso:["im","conj","abs","arg"]}},function(e){e.exports={name:"im",category:"Complex",syntax:["im(x)"],description:"Get the imaginary part of a complex number.",examples:["im(2 + 3i)","re(2 + 3i)","im(-5.2i)","im(2.4)"],seealso:["re","conj","abs","arg"]}},function(e){e.exports={name:"bignumber",category:"Type",syntax:["bignumber(x)"],description:"Create a big number from a number or string.",examples:["0.1 + 0.2","bignumber(0.1) + bignumber(0.2)",'bignumber("7.2")','bignumber("7.2e500")',"bignumber([0.1, 0.2, 0.3])"],seealso:["boolean","complex","index","matrix","string","unit"]}},function(e){e.exports={name:"boolean",category:"Type",syntax:["x","boolean(x)"],description:"Convert a string or number into a boolean.",examples:["boolean(0)","boolean(1)","boolean(3)",'boolean("true")','boolean("false")',"boolean([1, 0, 1, 1])"],seealso:["bignumber","complex","index","matrix","number","string","unit"]}},function(e){e.exports={name:"complex",category:"Type",syntax:["complex()","complex(re, im)","complex(string)"],description:"Create a complex number.",examples:["complex()","complex(2, 3)",'complex("7 - 2i")'],seealso:["bignumber","boolean","index","matrix","number","string","unit"]}},function(e){e.exports={name:"index",category:"Type",syntax:["[start]","[start:end]","[start:step:end]","[start1, start 2, ...]","[start1:end1, start2:end2, ...]","[start1:step1:end1, start2:step2:end2, ...]"],description:"Create an index to get or replace a subset of a matrix",examples:["[]","[1, 2, 3]","A = [1, 2, 3; 4, 5, 6]","A[1, :]","A[1, 2] = 50","A[0:2, 0:2] = ones(2, 2)"],seealso:["bignumber","boolean","complex","matrix,","number","range","string","unit"]}},function(e){e.exports={name:"matrix",category:"Type",syntax:["[]","[a1, b1, ...; a2, b2, ...]","matrix()","matrix([...])"],description:"Create a matrix.",examples:["[]","[1, 2, 3]","[1, 2, 3; 4, 5, 6]","matrix()","matrix([3, 4])"],seealso:["bignumber","boolean","complex","index","number","string","unit"]}},function(e){e.exports={name:"number",category:"Type",syntax:["x","number(x)"],description:"Create a number or convert a string or boolean into a number.",examples:["2","2e3","4.05","number(2)",'number("7.2")',"number(true)","number([true, false, true, true])"],seealso:["bignumber","boolean","complex","index","matrix","string","unit"]}},function(e){e.exports={name:"string",category:"Type",syntax:['"text"',"string(x)"],description:"Create a string or convert a value to a string",examples:['"Hello World!"',"string(4.2)","string(3 + 2i)"],seealso:["bignumber","boolean","complex","index","matrix","number","unit"]}},function(e){e.exports={name:"unit",category:"Type",syntax:["value unit","unit(value, unit)","unit(string)"],description:"Create a unit.",examples:["5.5 mm","3 inch",'unit(7.1, "kilogram")','unit("23 deg")'],seealso:["bignumber","boolean","complex","index","matrix","number","string"]}},function(e){e.exports={name:"eval",category:"Expression",syntax:["eval(expression)","eval([expr1, expr2, expr3, ...])"],description:"Evaluate an expression or an array with expressions.",examples:['eval("2 + 3")','eval("sqrt(" + 4 + ")")'],seealso:[]}},function(e){e.exports={name:"help",category:"Expression",syntax:["help(object)","help(string)"],description:"Display documentation on a function or data type.",examples:["help(sqrt)",'help("complex")'],seealso:[]}},function(e){e.exports={name:"concat",category:"Matrix",syntax:["concat(A, B, C, ...)","concat(A, B, C, ..., dim)"],description:"Concatenate matrices. By default, the matrices are concatenated by the last dimension. The dimension on which to concatenate can be provided as last argument.",examples:["A = [1, 2; 5, 6]","B = [3, 4; 7, 8]","concat(A, B)","concat(A, B, 1)","concat(A, B, 2)"],seealso:["det","diag","eye","inv","ones","range","size","squeeze","subset","transpose","zeros"]}
},function(e){e.exports={name:"det",category:"Matrix",syntax:["det(x)"],description:"Calculate the determinant of a matrix",examples:["det([1, 2; 3, 4])","det([-2, 2, 3; -1, 1, 3; 2, 0, -1])"],seealso:["concat","diag","eye","inv","ones","range","size","squeeze","subset","transpose","zeros"]}},function(e){e.exports={name:"diag",category:"Matrix",syntax:["diag(x)","diag(x, k)"],description:"Create a diagonal matrix or retrieve the diagonal of a matrix. When x is a vector, a matrix with the vector values on the diagonal will be returned. When x is a matrix, a vector with the diagonal values of the matrix is returned. When k is provided, the k-th diagonal will be filled in or retrieved, if k is positive, the values are placed on the super diagonal. When k is negative, the values are placed on the sub diagonal.",examples:["diag(1:3)","diag(1:3, 1)","a = [1, 2, 3; 4, 5, 6; 7, 8, 9]","diag(a)"],seealso:["concat","det","eye","inv","ones","range","size","squeeze","subset","transpose","zeros"]}},function(e){e.exports={name:"eye",category:"Matrix",syntax:["eye(n)","eye(m, n)","eye([m, n])","eye"],description:"Returns the identity matrix with size m-by-n. The matrix has ones on the diagonal and zeros elsewhere.",examples:["eye(3)","eye(3, 5)","a = [1, 2, 3; 4, 5, 6]","eye(size(a))"],seealso:["concat","det","diag","inv","ones","range","size","squeeze","subset","transpose","zeros"]}},function(e){e.exports={name:"flatten",category:"Matrix",syntax:["flatten(x)"],description:"Flatten a multi dimensional matrix into a single dimensional matrix.",examples:["a = [1, 2, 3; 4, 5, 6]","size(a)","b = flatten(a)","size(b)"],seealso:["concat","resize","size","squeeze"]}},function(e){e.exports={name:"inv",category:"Matrix",syntax:["inv(x)"],description:"Calculate the inverse of a matrix",examples:["inv([1, 2; 3, 4])","inv(4)","1 / 4"],seealso:["concat","det","diag","eye","ones","range","size","squeeze","subset","transpose","zeros"]}},function(e){e.exports={name:"ones",category:"Matrix",syntax:["ones(m)","ones(m, n)","ones(m, n, p, ...)","ones([m])","ones([m, n])","ones([m, n, p, ...])","ones"],description:"Create a matrix containing ones.",examples:["ones(3)","ones(3, 5)","ones([2,3]) * 4.5","a = [1, 2, 3; 4, 5, 6]","ones(size(a))"],seealso:["concat","det","diag","eye","inv","range","size","squeeze","subset","transpose","zeros"]}},function(e){e.exports={name:"range",category:"Type",syntax:["start:end","start:step:end","range(start, end)","range(start, end, step)","range(string)"],description:"Create a range. Lower bound of the range is included, upper bound is excluded.",examples:["1:5","3:-1:-3","range(3, 7)","range(0, 12, 2)",'range("4:10")',"a = [1, 2, 3, 4; 5, 6, 7, 8]","a[1:2, 1:2]"],seealso:["concat","det","diag","eye","inv","ones","size","squeeze","subset","transpose","zeros"]}},function(e){e.exports={name:"resize",category:"Matrix",syntax:["resize(x, size)","resize(x, size, defaultValue)"],description:"Resize a matrix.",examples:["resize([1,2,3,4,5], [3])","resize([1,2,3], [5])","resize([1,2,3], [5], -1)","resize(2, [2, 3])",'resize("hello", [8], "!")'],seealso:["size","subset","squeeze"]}},function(e){e.exports={name:"size",category:"Matrix",syntax:["size(x)"],description:"Calculate the size of a matrix.",examples:["size(2.3)",'size("hello world")',"a = [1, 2; 3, 4; 5, 6]","size(a)","size(1:6)"],seealso:["concat","det","diag","eye","inv","ones","range","squeeze","subset","transpose","zeros"]}},function(e){e.exports={name:"squeeze",category:"Matrix",syntax:["squeeze(x)"],description:"Remove inner and outer singleton dimensions from a matrix.",examples:["a = zeros(3,2,1)","size(squeeze(a))","b = zeros(1,1,3)","size(squeeze(b))"],seealso:["concat","det","diag","eye","inv","ones","range","size","subset","transpose","zeros"]}},function(e){e.exports={name:"subset",category:"Matrix",syntax:["value(index)","value(index) = replacement","subset(value, [index])","subset(value, [index], replacement)"],description:"Get or set a subset of a matrix or string. Indexes are one-based. Both the ranges lower-bound and upper-bound are included.",examples:["d = [1, 2; 3, 4]","e = []","e[1, 1:2] = [5, 6]","e[2, :] = [7, 8]","f = d * e","f[2, 1]","f[:, 1]"],seealso:["concat","det","diag","eye","inv","ones","range","size","squeeze","transpose","zeros"]}},function(e){e.exports={name:"transpose",category:"Matrix",syntax:["x'","transpose(x)"],description:"Transpose a matrix",examples:["a = [1, 2, 3; 4, 5, 6]","a'","transpose(a)"],seealso:["concat","det","diag","eye","inv","ones","range","size","squeeze","subset","zeros"]}},function(e){e.exports={name:"zeros",category:"Matrix",syntax:["zeros(m)","zeros(m, n)","zeros(m, n, p, ...)","zeros([m])","zeros([m, n])","zeros([m, n, p, ...])","zeros"],description:"Create a matrix containing zeros.",examples:["zeros(3)","zeros(3, 5)","a = [1, 2, 3; 4, 5, 6]","zeros(size(a))"],seealso:["concat","det","diag","eye","inv","ones","range","size","squeeze","subset","transpose"]}},function(e){e.exports={name:"combinations",category:"Probability",syntax:["combinations(n, k)"],description:"Compute the number of combinations of n items taken k at a time",examples:["combinations(7, 5)"],seealso:["permutations","factorial"]}},function(e){e.exports={name:"distribution",category:"Probability",syntax:["distribution(name)","distribution(name, arg1, arg2, ...)"],description:'Create a distribution object of a specific type. A distribution object contains functions `random([size,] [min,] [max])`, `randomInt([size,] [min,] [max])`, and `pickRandom(array)`. Available types of distributions: "uniform", "normal". Note that the function distribution is currently not available via the expression parser.',examples:[],seealso:["random","randomInt"]}},function(e){e.exports={name:"factorial",category:"Probability",syntax:["n!","factorial(n)"],description:"Compute the factorial of a value",examples:["5!","5*4*3*2*1","3!"],seealso:["combinations","permutations"]}},function(e){e.exports={name:"permutations",category:"Probability",syntax:["permutations(n)","permutations(n, k)"],description:"Compute the number of permutations of n items taken k at a time",examples:["permutations(5)","permutations(5, 3)"],seealso:["combinations","factorial"]}},function(e){e.exports={name:"pickRandom",category:"Probability",syntax:["pickRandom(array)"],description:"Pick a random entry from a given array.",examples:["pickRandom(0:10)","pickRandom([1, 3, 1, 6])"],seealso:["distribution","random","randomInt"]}},function(e){e.exports={name:"random",category:"Probability",syntax:["random()","random(max)","random(min, max)","random(size)","random(size, max)","random(size, min, max)"],description:"Return a random number.",examples:["random()","random(10, 20)","random([2, 3])"],seealso:["distribution","pickRandom","randomInt"]}},function(e){e.exports={name:"randInt",category:"Probability",syntax:["randInt()","randInt(max)","randInt(min, max)","randInt(size)","randInt(size, max)","randInt(size, min, max)"],description:"Return a random integer number",examples:["randInt()","randInt(10, 20)","randInt([2, 3], 10)"],seealso:["distribution","pickRandom","random"]}},function(e){e.exports={name:"max",category:"Statistics",syntax:["max(a, b, c, ...)","max(A)","max(A, dim)"],description:"Compute the maximum value of a list of values.",examples:["max(2, 3, 4, 1)","max([2, 3, 4, 1])","max([2, 5; 4, 3], 0)","max([2, 5; 4, 3], 1)","max(2.7, 7.1, -4.5, 2.0, 4.1)","min(2.7, 7.1, -4.5, 2.0, 4.1)"],seealso:["mean","median","min","prod","std","sum","var"]}},function(e){e.exports={name:"mean",category:"Statistics",syntax:["mean(a, b, c, ...)","mean(A)","mean(A, dim)"],description:"Compute the arithmetic mean of a list of values.",examples:["mean(2, 3, 4, 1)","mean([2, 3, 4, 1])","mean([2, 5; 4, 3], 0)","mean([2, 5; 4, 3], 1)","mean([1.0, 2.7, 3.2, 4.0])"],seealso:["max","median","min","prod","std","sum","var"]}},function(e){e.exports={name:"median",category:"Statistics",syntax:["median(a, b, c, ...)","median(A)"],description:"Compute the median of all values. The values are sorted and the middle value is returned. In case of an even number of values, the average of the two middle values is returned.",examples:["median(5, 2, 7)","median([3, -1, 5, 7])"],seealso:["max","mean","min","prod","std","sum","var"]}},function(e){e.exports={name:"min",category:"Statistics",syntax:["min(a, b, c, ...)","min(A)","min(A, dim)"],description:"Compute the minimum value of a list of values.",examples:["min(2, 3, 4, 1)","min([2, 3, 4, 1])","min([2, 5; 4, 3], 0)","min([2, 5; 4, 3], 1)","min(2.7, 7.1, -4.5, 2.0, 4.1)","max(2.7, 7.1, -4.5, 2.0, 4.1)"],seealso:["max","mean","median","prod","std","sum","var"]}},function(e){e.exports={name:"prod",category:"Statistics",syntax:["prod(a, b, c, ...)","prod(A)"],description:"Compute the product of all values.",examples:["prod(2, 3, 4)","prod([2, 3, 4])","prod([2, 5; 4, 3])"],seealso:["max","mean","min","median","min","std","sum","var"]}},function(e){e.exports={name:"std",category:"Statistics",syntax:["std(a, b, c, ...)","std(A)","std(A, normalization)"],description:'Compute the standard deviation of all values, defined as std(A) = sqrt(var(A)). Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["std(2, 4, 6)","std([2, 4, 6, 8])",'std([2, 4, 6, 8], "uncorrected")','std([2, 4, 6, 8], "biased")',"std([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","min","prod","sum","var"]}},function(e){e.exports={name:"sum",category:"Statistics",syntax:["sum(a, b, c, ...)","sum(A)"],description:"Compute the sum of all values.",examples:["sum(2, 3, 4, 1)","sum([2, 3, 4, 1])","sum([2, 5; 4, 3])"],seealso:["max","mean","median","min","prod","std","sum","var"]}},function(e){e.exports={name:"var",category:"Statistics",syntax:["var(a, b, c, ...)","var(A)","var(A, normalization)"],description:'Compute the variance of all values. Optional parameter normalization can be "unbiased" (default), "uncorrected", or "biased".',examples:["var(2, 4, 6)","var([2, 4, 6, 8])",'var([2, 4, 6, 8], "uncorrected")','var([2, 4, 6, 8], "biased")',"var([1, 2, 3; 4, 5, 6])"],seealso:["max","mean","min","median","min","prod","std","sum"]}},function(e){e.exports={name:"acos",category:"Trigonometry",syntax:["acos(x)"],description:"Compute the inverse cosine of a value in radians.",examples:["acos(0.5)","acos(cos(2.3))"],seealso:["cos","atan","asin"]}},function(e){e.exports={name:"asin",category:"Trigonometry",syntax:["asin(x)"],description:"Compute the inverse sine of a value in radians.",examples:["asin(0.5)","asin(sin(2.3))"],seealso:["sin","acos","atan"]}},function(e){e.exports={name:"atan",category:"Trigonometry",syntax:["atan(x)"],description:"Compute the inverse tangent of a value in radians.",examples:["atan(0.5)","atan(tan(2.3))"],seealso:["tan","acos","asin"]}},function(e){e.exports={name:"atan2",category:"Trigonometry",syntax:["atan2(y, x)"],description:"Computes the principal value of the arc tangent of y/x in radians.",examples:["atan2(2, 2) / pi","angle = 60 deg in rad","x = cos(angle)","y = sin(angle)","atan2(y, x)"],seealso:["sin","cos","tan"]}},function(e){e.exports={name:"cos",category:"Trigonometry",syntax:["cos(x)"],description:"Compute the cosine of x in radians.",examples:["cos(2)","cos(pi / 4) ^ 2","cos(180 deg)","cos(60 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["acos","sin","tan"]}},function(e){e.exports={name:"cosh",category:"Trigonometry",syntax:["cosh(x)"],description:"Compute the hyperbolic cosine of x in radians.",examples:["cosh(0.5)"],seealso:["sinh","tanh","coth"]}},function(e){e.exports={name:"cot",category:"Trigonometry",syntax:["cot(x)"],description:"Compute the cotangent of x in radians. Defined as 1/tan(x)",examples:["cot(2)","1 / tan(2)"],seealso:["sec","csc","tan"]}},function(e){e.exports={name:"coth",category:"Trigonometry",syntax:["coth(x)"],description:"Compute the hyperbolic cotangent of x in radians.",examples:["coth(2)","1 / tanh(2)"],seealso:["sech","csch","tanh"]}},function(e){e.exports={name:"csc",category:"Trigonometry",syntax:["csc(x)"],description:"Compute the cosecant of x in radians. Defined as 1/sin(x)",examples:["csc(2)","1 / sin(2)"],seealso:["sec","cot","sin"]}},function(e){e.exports={name:"csch",category:"Trigonometry",syntax:["csch(x)"],description:"Compute the hyperbolic cosecant of x in radians. Defined as 1/sinh(x)",examples:["csch(2)","1 / sinh(2)"],seealso:["sech","coth","sinh"]}},function(e){e.exports={name:"sec",category:"Trigonometry",syntax:["sec(x)"],description:"Compute the secant of x in radians. Defined as 1/cos(x)",examples:["sec(2)","1 / cos(2)"],seealso:["cot","csc","cos"]}},function(e){e.exports={name:"sech",category:"Trigonometry",syntax:["sech(x)"],description:"Compute the hyperbolic secant of x in radians. Defined as 1/cosh(x)",examples:["sech(2)","1 / cosh(2)"],seealso:["coth","csch","cosh"]}},function(e){e.exports={name:"sin",category:"Trigonometry",syntax:["sin(x)"],description:"Compute the sine of x in radians.",examples:["sin(2)","sin(pi / 4) ^ 2","sin(90 deg)","sin(30 deg)","sin(0.2)^2 + cos(0.2)^2"],seealso:["asin","cos","tan"]}},function(e){e.exports={name:"sinh",category:"Trigonometry",syntax:["sinh(x)"],description:"Compute the hyperbolic sine of x in radians.",examples:["sinh(0.5)"],seealso:["cosh","tanh"]}},function(e){e.exports={name:"tan",category:"Trigonometry",syntax:["tan(x)"],description:"Compute the tangent of x in radians.",examples:["tan(0.5)","sin(0.5) / cos(0.5)","tan(pi / 4)","tan(45 deg)"],seealso:["atan","sin","cos"]}},function(e){e.exports={name:"tanh",category:"Trigonometry",syntax:["tanh(x)"],description:"Compute the hyperbolic tangent of x in radians.",examples:["tanh(0.5)","sinh(0.5) / cosh(0.5)"],seealso:["sinh","cosh"]}},function(e){e.exports={name:"to",category:"Units",syntax:["x to unit","to(x, unit)"],description:"Change the unit of a value.",examples:["5 inch to cm","3.2kg to g","16 bytes in bits"],seealso:[]}},function(e){e.exports={name:"clone",category:"Utils",syntax:["clone(x)"],description:"Clone a variable. Creates a copy of primitive variables,and a deep copy of matrices",examples:["clone(3.5)","clone(2 - 4i)","clone(45 deg)","clone([1, 2; 3, 4])",'clone("hello world")'],seealso:[]}},function(e){e.exports={name:"map",category:"Utils",syntax:["map(x, callback)"],description:"Create a new matrix or array with the results of the callback function executed on each entry of the matrix/array.",examples:["map([1, 2, 3], function(val) { return value * value })"],seealso:[]}},function(e){e.exports={name:"forEach",category:"Utils",syntax:["forEach(x, callback)"],description:"Iterates over all elements of a matrix/array, and executes the given callback function.",examples:["forEach([1, 2, 3], function(val) { console.log(val) })"],seealso:["unit"]}},function(e){e.exports={name:"format",category:"Utils",syntax:["format(value)","format(value, precision)"],description:"Format a value of any type as string.",examples:["format(2.3)","format(3 - 4i)","format([])","format(pi, 3)"],seealso:["print"]}},function(e){e.exports={name:"import",category:"Utils",syntax:["import(string)"],description:"Import functions from a file.",examples:['import("numbers")','import("./mylib.js")'],seealso:[]}},function(e){e.exports={name:"sort",category:"Utils",syntax:["sort(x)","sort(x, compare)"],description:'Sort the items in a matrix. Compare can be a string "asc" or "desc", or a custom sort function.',examples:["sort([5, 10, 1])",'sort(["C", "B", "A", "D"])'],seealso:[]}},function(e){e.exports={name:"typeof",category:"Utils",syntax:["typeof(x)"],description:"Get the type of a variable.",examples:["typeof(3.5)","typeof(2 - 4i)","typeof(45 deg)",'typeof("hello world")'],seealso:[]}},function(e){"use strict";e.exports={end:!0}},function(e,r,n){"use strict";function t(){for(var e,r=Array.prototype.slice.call(arguments),n=0,t=r.length;t>n;n++){e=r[n];for(var i in e)e.hasOwnProperty(i)&&(x[i]=e[i])}}function i(e,r){return"undefined"!=typeof e[r]}function o(e){return function(r){return i(e,r)}}function a(e){return function(n){if("boolean"==typeof e[n])n=e[n]===!0?"\\"+n:"\\mathrm{"+n+"}";else if("string"==typeof e[n])n=e[n];else if("string"==typeof n){var t=n.indexOf("_");-1!==t&&(n=r.toSymbol(n.substring(0,t))+"_{"+r.toSymbol(n.substring(t+1))+"}")}return n}}var s=n(144),u=n(153),f={Alpha:"A",alpha:!0,Beta:"B",beta:!0,Gamma:!0,gamma:!0,Delta:!0,delta:!0,Epsilon:"E",epsilon:!0,varepsilon:!0,Zeta:"Z",zeta:!0,Eta:"H",eta:!0,Theta:!0,theta:!0,vartheta:!0,Iota:"I",iota:!0,Kappa:"K",kappa:!0,varkappa:!0,Lambda:!0,lambda:!0,Mu:"M",mu:!0,Nu:"N",nu:!0,Xi:!0,xi:!0,Omicron:"O",omicron:!0,Pi:!0,pi:!0,varpi:!0,Rho:"P",rho:!0,varrho:!0,Sigma:!0,sigma:!0,varsigma:!0,Tau:"T",tau:!0,Upsilon:!0,upsilon:!0,Phi:!0,phi:!0,varphi:!0,Chi:"X",chi:!0,Psi:!0,psi:!0,Omega:!0,omega:!0},c={dots:!0,ldots:!0,cdots:!0,vdots:!0,ddots:!0,idots:!0},l={"true":"\\mathrm{True}","false":"\\mathrm{False}"},p={inf:"\\infty",Inf:"\\infty",infinity:"\\infty",Infinity:"\\infty",oo:"\\infty",lim:!0,undefined:"\\mathbf{?}"},m={acos:"\\cos^{-1}",arccos:"\\cos^{-1}",cos:!0,csc:!0,csch:!1,exp:!0,ker:!0,limsup:!0,min:!0,sinh:!0,asin:"\\sin^{-1}",arcsin:"\\sin^{-1}",cosh:!0,deg:!0,gcd:!0,lg:!0,ln:!0,Pr:!0,sup:!0,atan:"\\tan^{-1}",atan2:"\\tan2^{-1}",arctan:"\\tan^{-1}",cot:!0,det:!0,hom:!0,log:!0,log10:"\\log_{10}",sec:!0,sech:!1,tan:!0,arg:!0,coth:!0,dim:!0,inf:!0,max:!0,sin:!0,tanh:!0,fix:!1,lcm:!1,sign:!1,xgcd:!1,unaryMinus:!1,unaryPlus:!1,complex:!1,conj:!1,im:!1,re:!1,diag:!1,resize:!1,size:!1,squeeze:!1,subset:!1,index:!1,ones:!1,zeros:!1,range:!1,random:!1,mean:"\\mu",median:!1,prod:!1,std:"\\sigma","var":"\\sigma^2"},h={sqrt:!0,inv:!0,"int":"\\int",Int:"\\int",integrate:"\\int",eigenvalues:"\\lambda",liminf:!0,lim:!0,exp:"e^",sum:!0,eye:"\\mathbf{I}"},g={"<=":"\\leq",">=":"\\geq","!=":"\\neq","in":!0,"*":"\\cdot","/":"\\frac",mod:"\\bmod",to:"\\rightarrow"},d={deg:"^{\\circ}"},x={};t(m,h,f,c,l,p),r.isSymbol=o(x),r.toSymbol=a(x),r.isFunction=o(m),r.toFunction=a(m),r.isCurlyFunction=o(h),r.toCurlyFunction=a(h),r.isOperator=o(g),r.toOperator=a(g),r.isUnit=o(d),r.toUnit=function(){var e=a(d);return function(n,t){return r.isUnit(n)?e(n):(t?"":"\\,")+"\\mathrm{"+n+"}"}}(),r.addBraces=function(e,r,n){if(null===r)return e;var t=["",""];switch(n=n||"normal","undefined"==typeof r||r===!1?t=["{","}"]:r===!0?(t=["(",")"],n="lr"):t=Array.isArray(r)&&2===r.length?r:[r,r],n){case"normal":case!1:return t[0]+e+t[1];case"lr":return"\\left"+t[0]+"{"+e+"}\\right"+t[1];case"be":return"\\begin{"+t[0]+"}"+e+"\\end{"+t[1]+"}"}return t[0]+e+t[1]},r.toParams=function(e){var n=e.symbol,t=e.params,i=n.toTex(),o=null,a=null,f=!1,c=!1,l="",p="",m=null;switch(n.name){case"add":m="+";break;case"subtract":m="-";break;case"larger":m=">";break;case"largerEq":m=">=";break;case"smaller":m="<";break;case"smallerEq":m="<=";break;case"unequal":m="!=";break;case"equal":m="=";break;case"mod":m="mod";break;case"multiply":m="*";break;case"pow":m="^";break;case"concat":m="||";break;case"factorial":m="!";break;case"permutations":if(1!==t.length){var h=t[0].toTex(),g=t[1].toTex();return"\\frac{"+h+"!}{\\left("+h+" - "+g+"\\right)!}"}m="!";break;case"combinations":m="\\choose";break;case"abs":a="|",f="lr";break;case"norm":if(a="\\|",f="lr",2===t.length){var d=t[1].toTex();"\\text{inf}"===d?d="\\infty":"\\text{-inf}"===d?d="{- \\infty}":"\\text{fro}"===d&&(d="F"),p="_{"+d+"}",t=[t[0]]}break;case"ceil":a=["\\lceil","\\rceil"],f="lr";break;case"floor":a=["\\lfloor","\\rfloor"],f="lr";break;case"round":a=["\\lfloor","\\rceil"],f="lr",2===t.length&&(p="_"+r.addBraces(t[1].toTex()),t=[t[0]]);break;case"inv":p="^{-1}";break;case"transpose":p="^{T}",a=!1;break;case"log":var x="e";2===t.length&&(x=t[1].toTex(),i="\\log_{"+x+"}",t=[t[0]]),"e"===x&&(i="\\ln"),c=!0;break;case"square":p="^{2}";break;case"cube":p="^{3}";break;case"eye":c=!0,a=!1,i+="_";break;case"det":if(e.params[0]instanceof s)return e.params[0].toTex("vmatrix");a="vmatrix",f="be";break;default:c=!0}return null!==m?(a="+"===m||"-"===m,o=new u(m,n.name,t).toTex()):m=", ",null!==a||r.isCurlyFunction(n.name)||(a=!0),o=o||t.map(function(e){return"{"+e.toTex()+"}"}).join(m),l+(c?i:"")+r.addBraces(o,a,f)+p}}])});
//# sourceMappingURL=math.map;
// Copyright 2012-2016 Laserfiche. All rights reserved

﻿
var LF=LF||{};LF.f={_IsNumber:{f:function(value){return LF.formula.isNumber(value);},d:"",e:"",t:"H"},_IsBigNumber:function(value){if(Object.prototype.toString.call(value)==="[object Object]"){return Object.getPrototypeOf(value)===Object.getPrototypeOf(math.bignumber(1));}
return false;},_IsUndefined:function(value){return value===undefined;},_IsBoolean:function(value){return(value===true)||(value===false);},_IsArray:function(value){return Object.prototype.toString.call(value)==='[object Array]';},_IsSameSign:function(val1,val2){if(arguments.length===2){if(LF.f._IsBigNumber(val1)&&LF.f._IsBigNumber(val2)){return(val1.toNumber()>=0)===(val2.toNumber()>=0)&&(val1.toNumber()<=0)===(val2.toNumber()<=0);}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},_AreSameType:function(val1,val2){if(LF.f._IsBoolean(val1)&&LF.f._IsBoolean(val2)||LF.f._IsString(val1)&&LF.f._IsString(val2)||LF.f._IsArray(val1)&&LF.f._IsArray(val2)||LF.f._IsDate(val1)&&LF.f._IsDate(val2)||LF.f._IsBigNumber(val1)&&LF.f._IsBigNumber(val2)){return true;}
return false;},_TruncateNumber:function(value){if(arguments.length===1){if(LF.f._IsBigNumber(value)){return value.trunc();}
else if(LF.f._IsString(value)&&LF.formula.isNumberString(value)){var retVal=parseInt(value);if(retVal!==NaN){return LF.f._BN(retVal);}}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.badArgCount;},_FixItem:function(a,blankToZero,noTrim){if(a instanceof jQuery){a=a.val();if(a==''&&blankToZero){a=LF.f._BN(0);}}
if(typeof(a)==="number"){a=LF.f._BN(a);}
else if(!noTrim&&typeof(a)==="string"){a=a.trim();}
return a;},_FixArguments:function(args,blankToZero,noTrim){_.each(args,function(a,i){if(Array.isArray(a)){var ret=[];_.each(a,function(array){ret.push(LF.f._FixItem(array,blankToZero,noTrim));});args[i]=ret;}
else{args[i]=LF.f._FixItem(a,blankToZero,noTrim);}});},_IsInteger:function(value){if(LF.f._IsBigNumber(value)){return value.mod(1).eq(0);}
else{throw LF.formula.errorList.notNumber;}},_BN:function(value){return math.bignumber(math.bignumber(value).toPrecision(LF.number.defaultPrecision));},_NotNull:function(){var flatArgs=LF.formula.concatArgs(arguments);return _.every(flatArgs,function(element){return element!==null;});},ADD:function(val1,val2){LF.f._FixArguments(arguments,true);if(arguments.length===2){if(LF.f._IsBigNumber(val1)&&LF.f._IsBigNumber(val2)){return val1.plus(val2);}
else{throw LF.formula.errorList.badArgValue;}}
throw LF.formula.errorList.badArgCount;},MINUS:function(value){LF.f._FixArguments(arguments,true);if(arguments.length===1){if(LF.f._IsBigNumber(value)){return value.neg();}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},_PLUS:function(value){LF.f._FixArguments(arguments,true);if(arguments.length===1){if(LF.f._IsBigNumber(value)){return value;}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},SUB:function(val1,val2){LF.f._FixArguments(arguments,true);if(arguments.length===2){if(LF.f._IsBigNumber(val1)&&LF.f._IsBigNumber(val2)){return val1.minus(val2);}
else{throw LF.formula.errorList.badArgValue;}}
throw LF.formula.errorList.badArgCount;},MULT:function(val1,val2){LF.f._FixArguments(arguments,true);if(arguments.length===2){if(LF.f._IsBigNumber(val1)&&LF.f._IsBigNumber(val2)){return val1.times(val2);}
else{throw LF.formula.errorList.notNumber;}}
throw LF.formula.errorList.badArgCount;},DIV:function(val1,val2){LF.f._FixArguments(arguments,true);if(arguments.length===2){if(LF.f._IsBigNumber(val1)&&LF.f._IsBigNumber(val2)){if(val2.toNumber()===0){throw LF.formula.errorList.divByZero;}
return val1.div(val2);}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},IDIV:function(val1,val2){LF.f._FixArguments(arguments,true);if(arguments.length===2){var divVal=LF.f.DIV(val1,val2);return LF.f._IsSameSign(val1,val2)?divVal.floor():divVal.ceil();}
throw LF.formula.errorList.badArgCount;},MOD:function(val1,val2){LF.f._FixArguments(arguments,true);if(arguments.length===2){if(LF.f._IsBigNumber(val1)&&LF.f._IsBigNumber(val2)){if(val2.toNumber()===0){throw LF.formula.errorList.divByZero;}
return LF.f._IsSameSign(val1,val2)?val1.mod(val2):val1.mod(val2).neg();}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},POWER:function(base,exponent){LF.f._FixArguments(arguments,true);if(arguments.length!==2){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsBigNumber(base)||!LF.f._IsBigNumber(exponent)){throw LF.formula.errorList.notNumber;}
return base.pow(exponent);},EXP:function(exponent){LF.f._FixArguments(arguments,true);if(arguments.length!==1||exponent===undefined){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsBigNumber(exponent)){throw LF.formula.errorList.notNumber;}
return exponent.exp(exponent);},SQRT:function(val){LF.f._FixArguments(arguments,true);if(arguments.length!==1||val===undefined){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsBigNumber(val)){throw LF.formula.errorList.notNumber;}
if(val.lt(0)){throw LF.formula.errorList.badArgValue;}
return val.sqrt();},SUM:function(){LF.f._FixArguments(arguments);var inputs=LF.formula.concatArgs(arguments);if(_.filter(inputs,function(element){return element!==undefined;}).length===0){throw LF.formula.errorList.badArgCount;}
var filter=_.filter(inputs,function(element){return(LF.f._IsBigNumber(element));});if(!filter.length){return LF.f._BN(0);}
return _.reduce(filter,function(s,n){return s.plus(n);},LF.f._BN(0));},AVG:function(){LF.f._FixArguments(arguments);var inputs=LF.formula.concatArgs(arguments);if(_.filter(inputs,function(element){return element!==undefined;}).length===0){throw LF.formula.errorList.badArgCount;}
var filter=_.filter(inputs,function(element){return(LF.f._IsBigNumber(element));});if(filter.length){return _.reduce(filter,function(s,n){return LF.f._BN(s).plus(n);},0).div(filter.length);}
throw LF.formula.errorList.divByZero;},AVERAGE:function(){return LF.f.AVG.apply(this,arguments);},_ConvertStringsAndBools:function(array){if(arguments.length===1&&LF.f._IsArray(array)){array=_.map(array,function(element){if(LF.f._IsBigNumber(element)){return element;}
else if(element===true){return LF.f._BN(1);}
else{return LF.f._BN(0);}});return array;}
throw LF.formula.errorList.unexpectedError;},AVERAGEA:function(){LF.f._FixArguments(arguments);var inputs=LF.formula.concatArgs(arguments);inputs=_.filter(inputs,function(element){return(element!==null&&element!==undefined);});if(arguments.length){return LF.f.AVG.apply(this,LF.f._ConvertStringsAndBools(inputs));}
throw LF.formula.errorList.badArgCount;},MAX:function(){LF.f._FixArguments(arguments);var inputs=LF.formula.concatArgs(arguments);if(_.filter(inputs,function(element){return element!==undefined;}).length===0){throw LF.formula.errorList.badArgCount;}
var filter=_.filter(inputs,function(element){return LF.f._IsBigNumber(element);});if(!filter.length){return LF.f._BN(0);}
return _.max(filter,function(element){return element.toNumber();});},MAXA:function(){var hasVariable=_.find(arguments,function(ele){return ele instanceof jQuery;});LF.f._FixArguments(arguments);var inputs=_.filter(LF.formula.concatArgs(arguments),function(element){return(element!==undefined&&element!='');});if(hasVariable&&inputs.length==0){inputs.push(LF.f._BN(0));}
return LF.f.MAX.apply(this,LF.f._ConvertStringsAndBools(inputs));},MIN:function(){LF.f._FixArguments(arguments);var inputs=LF.formula.concatArgs(arguments);if(_.filter(inputs,function(element){return element!==undefined;}).length===0){throw LF.formula.errorList.badArgCount;}
var filter=_.filter(inputs,function(element){return LF.f._IsBigNumber(element);});if(!filter.length){return LF.f._BN(0);}
return _.min(filter,function(element){return element.toNumber();});},MINA:function(){var hasVariable=_.find(arguments,function(ele){return ele instanceof jQuery;});LF.f._FixArguments(arguments);var inputs=_.filter(LF.formula.concatArgs(arguments),function(element){return(element!==undefined&&element!='');});if(hasVariable&&inputs.length==0){inputs.push(LF.f._BN(0));}
return LF.f.MIN.apply(this,LF.f._ConvertStringsAndBools(inputs));},COUNT:function(){LF.f._FixArguments(arguments);var inputs=LF.formula.concatArgs(arguments);var numArgs=_.filter(inputs,function(arg){return LF.f._IsBigNumber(arg);});return LF.f._BN(numArgs.length);},ABS:function(value){LF.f._FixArguments(arguments,true);if(arguments.length!==1||value===undefined){throw LF.formula.errorList.badArgCount;}
else if(!LF.f._IsBigNumber(value)){throw LF.formula.errorList.notNumber;}
return value.abs();},CEILING:function(value,ceil)
{LF.f._FixArguments(arguments,true);if(arguments.length!==1&&arguments.length!==2||value===undefined){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsBigNumber(value)){throw LF.formula.errorList.notNumber;}
if(ceil===undefined){ceil=value.greaterThan(0)?LF.f._BN(1):LF.f._BN(-1);}
if(!LF.f._IsBigNumber(ceil)){throw LF.formula.errorList.notNumber;}
if(value.toNumber()===0||ceil.toNumber()===0){return LF.f._BN(0);}
return ceil.abs().times(value.div(ceil.abs()).ceil());},FLOOR:function(value,floor)
{LF.f._FixArguments(arguments,true);if(arguments.length!==1&&arguments.length!==2||value===undefined){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsBigNumber(value)){throw LF.formula.errorList.notNumber;}
if(floor===undefined){floor=value.greaterThan(0)?LF.f._BN(1):LF.f._BN(-1);}
if(!LF.f._IsBigNumber(floor)){throw LF.formula.errorList.notNumber;}
if(value.toNumber()===0||floor.toNumber()===0){return LF.f._BN(0);}
return floor.abs().times(value.div(floor.abs()).floor());},ISEVEN:function(value){LF.f._FixArguments(arguments,true);if(arguments.length!==1||value===undefined){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsBigNumber(value)){throw LF.formula.errorList.notNumber;}
if(value.toNumber()===Infinity||value.toNumber()===-Infinity){return false;}
return LF.f._TruncateNumber(value)%2===0;},ISODD:function(value){LF.f._FixArguments(arguments,true);if(arguments.length!==1||value===undefined){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsBigNumber(value)){throw LF.formula.errorList.notNumber;}
if(value.toNumber()===Infinity||value.toNumber()===-Infinity){return false;}
return LF.f._TruncateNumber(value)%2!==0;},EVEN:function(value){LF.f._FixArguments(arguments,true);if(arguments.length!==1||value===undefined){throw LF.formula.errorList.badArgCount;}
if(LF.f._IsBigNumber(value)){var ceil=value>0?LF.f._BN(2):LF.f._BN(-2);return ceil.times(value.div(ceil).ceil());}
throw LF.formula.errorList.notNumber;},ODD:function(value){LF.f._FixArguments(arguments,true);if(arguments.length!==1||value===undefined){throw LF.formula.errorList.badArgCount;}
if(LF.f._IsBigNumber(value)){var retVal;if(value.gt(0)){retVal=value.ceil();if(retVal.mod(2).eq(0)){retVal=retVal.plus(1);}}
else if(value.lt(0)){retVal=value.floor();if(retVal.mod(2).eq(0)){retVal=retVal.minus(1);}}
else{retVal=LF.f._BN(1);}
return retVal;}
throw LF.formula.errorList.notNumber;},LOG:function(value,base){LF.f._FixArguments(arguments,true);if(arguments.length===2||(arguments.length===1&&arguments[0]!==undefined)){if(arguments.length===1){base=LF.f._BN(10);}
if(LF.f._IsBigNumber(base)&&LF.f._IsBigNumber(value)){if(LF.f.SIGN(value).eq(1)&&LF.f.SIGN(base).eq(1)){return value.logarithm(base);}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},LOG10:function(value){LF.f._FixArguments(arguments,true);if(arguments.length===1){return LF.f.LOG(value);}
throw LF.formula.errorList.badArgCount;},LN:function(value){LF.f._FixArguments(arguments,true);if(arguments.length===1&&arguments[0]!==undefined){if(LF.f._IsBigNumber(value)){if(LF.f.SIGN(value).eq(1)){return value.ln()}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.notNumber}
throw LF.formula.errorList.badArgCount;},MEDIAN:function(){LF.f._FixArguments(arguments);if(arguments.length&&(arguments.length!==1||arguments[0]!==undefined)){var inputs=_.filter(LF.formula.concatArgs(arguments),function(element){return LF.f._IsBigNumber(element);}).sort(function(bigNum1,bigNum2){return bigNum1.minus(bigNum2);});var length=inputs.length;if(!length){throw LF.formula.errorList.badArgValue;}
if(LF.f.ISEVEN(LF.f._BN(length))){return LF.f.AVG(inputs[length/2-1],inputs[length/2]);}
else{return inputs[LF.f._TruncateNumber(LF.f._BN(length).div(2))];}}
throw LF.formula.errorList.badArgCount;},MODE:function(){LF.f._FixArguments(arguments);if(arguments.length&&(arguments.length!==1||arguments[0]!==undefined)){var inputs=_.filter(LF.formula.concatArgs(arguments),function(element){return LF.f._IsBigNumber(element);}).sort();var length=inputs.length;if(!length){throw LF.formula.errorList.badArgValue;}
else if(length!=arguments.length){throw LF.formula.errorList.badArgValue;}
var currentCount=0;var currentValue=inputs[0];var maxCount=0;var maxValue=inputs[0];for(var i=0;i<length;i++){if(inputs[i].eq(currentValue)){currentCount++;}
else{if(currentCount>maxCount){maxCount=currentCount;maxValue=currentValue;}
currentCount=1;currentValue=inputs[i];}}
return currentCount>maxCount?currentValue:maxValue;}
throw LF.formula.errorList.badArgCount;},MROUND:function(number,multiple){LF.f._FixArguments(arguments,true);if(arguments.length!==2){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsBigNumber(number)||!LF.f._IsBigNumber(multiple)){throw LF.formula.errorList.badArgValue;}
if(multiple.eq(0)){return LF.f._BN(0);}
return number.div(multiple).round().times(multiple);},PI:function(){LF.f._FixArguments(arguments);if((arguments.length===1&&arguments[0]===undefined)||!arguments.length){return LF.f._BN("3.141592653589793238462643383279502884197169399375105820974944592307816406286");}
throw LF.formula.errorList.badArgCount;},_Factorial:function(value){if(arguments.length===1){if(LF.f._IsBigNumber(value)){if(value.gte(0)){if(value.eq(0)){return BigNumber(1);}
return value.times(LF.f._Factorial(value.minus(1)));}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},PRODUCT:function(){LF.f._FixArguments(arguments);var inputs=LF.formula.concatArgs(arguments);if(_.filter(inputs,function(element){return element!==undefined;}).length===0){throw LF.formula.errorList.badArgCount;}
var filter=_.filter(inputs,function(element){return LF.f._IsBigNumber(element);});if(!filter.length){return LF.f._BN(0);}
return _.reduce(filter,function(s,n){return s.times(n);});},QUOTIENT:function(val1,val2){LF.f._FixArguments(arguments,true);return LF.f._TruncateNumber(LF.f.DIV.apply(this,arguments));},ROUND:function(value,numDigits){LF.f._FixArguments(arguments,true);if(arguments.length===2||(arguments.length===1&&value!==undefined)){if(numDigits===undefined){numDigits=LF.f._BN(0)}
var upper=LF.f.ROUNDUP(value,numDigits);var lower=LF.f.ROUNDDOWN(value,numDigits);return(LF.f.ABS(value.minus(lower)).lessThan(LF.f.ABS(upper.minus(value))))?lower:upper;}
throw LF.formula.errorList.badArgCount;},ROUNDDOWN:function(value,numDigits){LF.f._FixArguments(arguments,true);if(arguments.length===2||(arguments.length===1&&arguments[0]!==undefined)){if(arguments.length===1){numDigits=LF.f._BN(0);}
numDigits=LF.f._TruncateNumber(numDigits);return LF.f.TRUNC(value,numDigits);}
throw LF.formula.errorList.badArgCount;},ROUNDUP:function(value,numDigits){LF.f._FixArguments(arguments,true);if(arguments.length===2||(arguments.length===1&&arguments[0]!==undefined)){if(arguments.length===1){numDigits=LF.f._BN(0);}
if(LF.f._IsBigNumber(value)&&LF.f._IsBigNumber(numDigits)){numDigits=LF.f._TruncateNumber(numDigits);return value.greaterThan(0)?LF.f.CEILING(value,LF.f._BN(Math.pow(10,numDigits.times(-1)))):LF.f.FLOOR(value,LF.f._BN(-1*Math.pow(10,numDigits.times(-1))));}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.badArgCount;},SIGN:function(value){LF.f._FixArguments(arguments,true);if(arguments.length===1&&arguments[0]!==undefined){if(LF.f._IsBigNumber(value)){if(value.c.length===1&&value.c[0]===0){return LF.f._BN(0);}
return LF.f._BN(value.s);}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},TRUNC:function(number,numDigits){LF.f._FixArguments(arguments,true);if(arguments.length===2||(arguments.length===1&&arguments[0]!==undefined)){if(arguments.length===1){numDigits=LF.f._BN(0);}
if(LF.f._IsBigNumber(number)&&LF.f._IsBigNumber(numDigits)){numDigits=LF.f._TruncateNumber(numDigits);return number.greaterThan(0)?LF.f.FLOOR(number,LF.f._BN(Math.pow(10,numDigits.times(-1)))):LF.f.CEILING(number,LF.f._BN(-1*Math.pow(10,numDigits.times(-1))));}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.badArgCount;},LARGE:function(array,n){LF.f._FixArguments(arguments);if(arguments.length===2){if(!LF.f._IsArray(array)||(!LF.f._IsBigNumber(n)&&!LF.f._IsArray(n))){throw LF.formula.errorList.badArgValue;}
if(!_.some(array,function(element){return LF.f._IsBigNumber(element);})){throw LF.formula.errorList.badArgValue;}
array=_.map(_.omit(array,function(element){return!LF.f._IsBigNumber(element)}));array=array.sort(this._CompareBigNumbers);if(LF.f._IsBigNumber(n)){n=LF.f.CEILING(n);if(n.toNumber()>array.length||n.toNumber()<1){throw LF.formula.errorList.outOfRange;}
if(LF.f._IsBigNumber(array[array.length-n.toNumber()])){return array[array.length-n.toNumber()];}
throw LF.formula.errorList.notNumber;}
else{var retArray=[];_.map(n,function(element){if(LF.f._IsBigNumber(element)){element=LF.f.CEILING(element);if(element<=array.length&&element.toNumber()>=1){return element;}
throw LF.formula.errorList.outOfRange;}
throw LF.formula.errorList.notNumber;});n.forEach(function(element){retArray.push(array[array.length-element]);});}
return retArray;}
throw LF.formula.errorList.badArgCount;},_CompareBigNumbers:function(bigNumberOne,bigNumberTwo){if(bigNumberOne.lt(bigNumberTwo)){return-1;}
if(bigNumberOne.gt(bigNumberTwo)){return 1;}
return 0;},_FilterFloat:function(value){if(/^(\-|\+)?([0-9]+(\.[0-9]+)?|Infinity)$/.test(value)){return LF.f._BN(value);}
return NaN;},_COUNTIF:function(array,criterion){var op="";var critVal;var critIsNumber=true;var critIsBool=false;if(criterion===""){critVal=LF.f._BN(0);}
else if(typeof(criterion)=="boolean"){critVal=criterion;critIsBool=true;}
else if(LF.f._IsBigNumber(criterion)){critVal=criterion;}
else{var opRE=/^(>=|<=|<>|[=><])/g;var opMatchArray=criterion.match(opRE);if(opMatchArray==null){critVal=LF.f._parseValue(criterion);}
else if(opMatchArray.length==1){op=opMatchArray[0];critVal=LF.f._parseValue(criterion.replace(op,""));}
else{return null;}
if(critVal==null){critVal=criterion.replace(op,"");critIsNumber=false;}}
var retArray=critIsBool?LF.f._boolCompare(array,critVal):critIsNumber?LF.f._numCompare(array,op,critVal):LF.f._strCompare(array,op,critVal);return retArray;},_boolCompare:function(array,criterion){return _.filter(array,function(n){return typeof(n)=='string'?n.toLowerCase()==criterion.toString():typeof(n)=='boolean'?n==criterion:false})},_strCompare:function(array,op,criterion){var retArray=[];switch(op){case"":case"=":retArray=_.filter(array,function(n){return typeof(n)=='string'?n.toLowerCase()==criterion.toLowerCase():typeof(n)=='boolean'?n.toString()==criterion.toLowerCase():false});break;case">":retArray=_.filter(array,function(n){return typeof(n)=='string'?n.toLowerCase()>criterion.toLowerCase():false});break;case"<":retArray=_.filter(array,function(n){return typeof(n)=='string'?n.toLowerCase()<criterion.toLowerCase():false});break;case">=":retArray=_.filter(array,function(n){return typeof(n)=='string'?n.toLowerCase()>=criterion.toLowerCase():false});break;case"<=":retArray=_.filter(array,function(n){return typeof(n)=='string'?n.toLowerCase()<=criterion.toLowerCase():false});break;case"<>":retArray=_.filter(array,function(n){return typeof(n)=='string'?n.toLowerCase()!=criterion.toLowerCase():typeof(n)=='boolean'?n.toString()!=criterion.toLowerCase():false});break;default:break;}
return retArray;},_numCompare:function(array,op,criterion){var retArray=[];var temp;switch(op){case"":case"=":retArray=_.filter(array,function(n){return LF.f._IsBigNumber(n)?n.eq(criterion):(temp=LF.f._parseValue(n))==null?false:temp.eq(criterion)});break;case">":retArray=_.filter(array,function(n){return LF.f._IsBigNumber(n)?n.gt(criterion):(temp=LF.f._parseValue(n))==null?false:temp.gt(criterion)});break;case"<":retArray=_.filter(array,function(n){return LF.f._IsBigNumber(n)?n.lt(criterion):(temp=LF.f._parseValue(n))==null?false:temp.lt(criterion)});break;case">=":retArray=_.filter(array,function(n){return LF.f._IsBigNumber(n)?n.gte(criterion):(temp=LF.f._parseValue(n))==null?false:temp.gte(criterion)});break;case"<=":retArray=_.filter(array,function(n){return LF.f._IsBigNumber(n)?n.lte(criterion):(temp=LF.f._parseValue(n))==null?false:temp.lte(criterion)});break;case"<>":retArray=_.filter(array,function(n){return LF.f._IsBigNumber(n)?!n.eq(criterion):(temp=LF.f._parseValue(n))==null?false:!temp.eq(criterion)});break;default:break;}
return retArray;},_XCOUNTIF:function(array,criterion){var retArray=[];if(criterion==""){criterion=LF.f._BN(0);}
var numfilter=_.map(_.filter(array,function(element){return LF.f._IsBigNumber(LF.f._FilterFloat(element));}),function(n){return LF.f._FilterFloat(n)});var stringfilter=_.filter(array,function(element){return LF.f._IsString(element);});if(!LF.f._IsBigNumber(criterion)&&!LF.f._IsString(criterion)){return null;}
else if(LF.f._IsBigNumber(criterion)){retArray=_.filter(numfilter,function(element){return element.toNumber()===criterion.toNumber();});}
else{var changedString=criterion.replace("=","").replace(">","").replace("<","");var doubleCriteria=LF.f._FilterFloat(changedString);if(LF.f._IsBigNumber(doubleCriteria)&&criterion.length!==0){if((criterion[0]==='='&&criterion.replace("=","")===changedString)||criterion===changedString){retArray=_.filter(numfilter,function(element){return element.toNumber()===doubleCriteria.toNumber();});}
else if(criterion[0]==='<'){if(criterion.length>1&&criterion[1]==='>'&&criterion.replace("<>","")===changedString){retArray=_.filter(array,function(element){if(LF.f._IsBigNumber(element)){return element.toNumber()!=doubleCriteria.toNumber();}
return true;});}
else if(criterion.length>1&&criterion[1]==='='&&criterion.replace("<=","")===changedString){retArray=_.filter(numfilter,function(element){return element.toNumber()<=doubleCriteria.toNumber();});}
else if(criterion.replace("<","")===changedString){retArray=_.filter(numfilter,function(element){return element.toNumber()<doubleCriteria.toNumber();});}}
else if(criterion[0]==='>'){if(criterion.length>1&&criterion[1]==='='&&criterion.replace(">=","")===changedString){retArray=_.filter(numfilter,function(element){return element.toNumber()>=doubleCriteria.toNumber();});}
else if(criterion.replace(">","")===changedString){retArray=_.filter(numfilter,function(element){return element.toNumber()>doubleCriteria.toNumber();});}}}
else{var regularExpression=criterion.replace(/\?/g,".").replace(/~\./g,"\\?").replace(/\*/g,".*").replace(/~\.\*/g,"\\*").replace(/~\\\?/g,"~.").replace(/~\\\*/g,"~.*");regularExpression='^'+regularExpression+'$';regularExpression=new RegExp(regularExpression,"i");retArray=_.filter(array,function(element){if(LF.f._IsBigNumber(element)){return regularExpression.test(element.toNumber());}
else{return regularExpression.test(element);}});}}
return retArray;},COUNTIF:function(array,criterion){LF.f._FixArguments(arguments);if(arguments.length!==2){return LF.f._BN(0);}
if(!LF.f._IsArray(array)||(!LF.f._IsBigNumber(criterion)&&!LF.f._IsString(criterion))){return LF.f._BN(0);}
var retArray=LF.f._COUNTIF(array,criterion);if(retArray===null){return LF.f._BN(0);}
return LF.f._BN(retArray.length);},SUMIF:function(array,criterion,sum_range){LF.f._FixArguments(arguments);if(arguments.length!==2&&arguments.length!==3){return LF.f._BN(0);}
else if(arguments.length===2){sum_range=array;}
var retArray=LF.f._COUNTIF(array,criterion);if(retArray===null){return LF.f._BN(0);}
var index=[];for(var i=0;i<array.length;i++){if(retArray.indexOf(array[i])>-1||retArray.indexOf(LF.f._FilterFloat(array[i]))>-1){index.push(i);}}
var sumArray=[];for(var i=0;i<sum_range.length;i++){if(index.indexOf(i)>-1){sumArray.push(sum_range[i]);}}
var numArray=_.filter(sumArray,function(element){return LF.f._IsBigNumber(element);});if(numArray.length===0){return LF.f._BN(0);}
return LF.f.SUM(numArray);},SUMIFS:function(sum_range,array,criterion){LF.f._FixArguments(arguments);if(arguments.length%2==0){throw LF.formula.errorList.badArgCount;}
var length=sum_range.length;var criteria=[];var ranges=[];var retArr=[];var i=1;while(i<arguments.length-1){if(arguments[i].length==length){ranges.push(arguments[i]);i++;criteria.push(arguments[i]);i++;}
else{throw LF.formula.errorList.badArgValue;}}
for(i=0;i<ranges.length;++i){var arr=LF.f._COUNTIF(ranges[i],criteria[i]);if(arr===null||arr.length==0){return LF.f._BN(0);}
else{retArr.push(arr);}}
var indexArr=[];var j=0;for(i=0;i<ranges.length;++i){var indexSubArr=[];for(j=0;j<ranges[i].length;++j){if(retArr[i].indexOf(ranges[i][j])>-1){indexSubArr.push(j);}}
indexArr.push(indexSubArr);}
var sumRangeIndexArr=_.intersection.apply(this,indexArr);if(sumRangeIndexArr.length==0){return LF.f._BN(0);}
var sumRangeArr=_.map(sumRangeIndexArr,function(index){return sum_range[index]});var numArray=_.filter(sumRangeArr,function(element){return LF.f._IsBigNumber(element);});if(numArray.length===0){return LF.f._BN(0);}
return LF.f.SUM(numArray);},AVERAGEIF:function(array,criterion,sum_range){LF.f._FixArguments(arguments);if(sum_range===null||(arguments.length!=2&&arguments.length!=3)){return LF.f._BN(0);}
else if(arguments.length===2){sum_range=array;}
var sumResult=LF.f.SUMIF(array,criterion,sum_range);var countResult=LF.f.COUNTIF(array,criterion);var averageResult=LF.f._BN(0);if(countResult.toNumber()!==0){averageResult=sumResult.div(countResult);}
return averageResult;},CHOOSE:function(index){LF.f._FixArguments(arguments);var args=Array.prototype.slice.call(arguments,1);if(args.length&&index!==undefined){if(LF.f._IsBigNumber(index)){index=LF.f._TruncateNumber(index)}
else{throw LF.formula.errorList.notNumber;}
if(index.toNumber()<1||index.toNumber()>args.length){throw LF.formula.errorList.outOfRange;}
if(args[index.toNumber()-1]!==undefined){return args[index.toNumber()-1]}}
throw LF.formula.errorList.badArgCount;},CHOOSEA:function(){LF.f._FixArguments(arguments);args=LF.formula.concatArgs(arguments);return LF.f.CHOOSE.apply(this,args);},GT:function(val1,val2){LF.f._FixArguments(arguments,true);if(arguments.length===2){if(LF.f._IsBigNumber(val1)&&LF.f._IsBigNumber(val2)){return val1.gt(val2);}
if(LF.f._AreSameType(val1,val2)){return val1>val2;}
return false;}
throw LF.formula.errorList.badArgCount;},GTE:function(val1,val2){LF.f._FixArguments(arguments,true);if(arguments.length===2){return(LF.f.GT(val1,val2)||LF.f.EQ(val1,val2));}
throw LF.formula.errorList.badArgCount;},LT:function(val1,val2){LF.f._FixArguments(arguments,true);if(arguments.length===2){return!LF.f.GTE(val1,val2);}
throw LF.formula.errorList.badArgCount;},LTE:function(val1,val2){LF.f._FixArguments(arguments,true);if(arguments.length===2){return!LF.f.GT(val1,val2);}
throw LF.formula.errorList.badArgCount;},EQ:function(val1,val2){LF.f._FixArguments(arguments,true);if(arguments.length===2){if(LF.f._IsBigNumber(val1)&&LF.f._IsBigNumber(val2)){return val1.eq(val2);}
else if(LF.f._IsArray(val1)&&LF.f._IsArray(val2)){if(val1.length!==val2.length)
return false;for(var i=0;i<val1.length;i++){if(!LF.f.EQ(val1[i],val2[i])){return false;}}
return true;}
else{return val1===val2;}}
throw LF.formula.errorList.badArgCount;},NEQ:function(val1,val2){LF.f._FixArguments(arguments,true);if(arguments.length===2){return!LF.f.EQ(val1,val2);}
throw LF.formula.errorList.badArgCount;},NOT:function(value){LF.f._FixArguments(arguments);if(arguments.length===1&&value!==undefined){if(LF.f._IsBoolean(value)){return!value;}
else if(LF.f._IsBigNumber(value)){return!(value.toNumber());}
throw LF.formula.errorList.notLogical;}
throw LF.formula.errorList.badArgCount;},AND:function(val1,val2){LF.f._FixArguments(arguments);var args=_.filter(LF.formula.concatArgs(arguments),function(element){return element!==undefined;});if(args.length){var filter=_.filter(args,function(element){return(LF.f._IsBoolean(element)||LF.f._IsBigNumber(element));});if(filter.length===0){throw LF.formula.errorList.badArgValue;}
return _.every(filter,function(element){if(LF.f._IsBoolean(element)){return element;}
else{return!!(element.toNumber());}});}
throw LF.formula.errorList.badArgValue;},_ANDA:function(){LF.f._FixArguments(arguments);var args=_.filter(LF.formula.concatArgs(arguments),function(element){return element!==undefined;});if(args.length){return(_.every(LF.formula.concatArgs(arguments),function(element){return!!element;}));}
throw LF.formula.errorList.badArgCount;},OR:function(val1,val2){LF.f._FixArguments(arguments);var args=_.filter(LF.formula.concatArgs(arguments),function(element){return element!==undefined;});if(args.length){var filter=_.filter(args,function(element){return(LF.f._IsBoolean(element)||LF.f._IsBigNumber(element));});if(filter.length===0){throw LF.formula.errorList.badArgValue;}
return _.some(filter,function(element){if(LF.f._IsBigNumber(element)){return!!(element.toNumber());}
else{return element;}});}
throw LF.formula.errorList.badArgValue;},IF:function(expr,val1,val2){LF.f._FixArguments(arguments);if(arguments.length!==3){throw LF.formula.errorList.badArgCount;}
if(LF.f._IsBoolean(expr)){return(expr)?val1:val2;}
else if(LF.f._IsBigNumber(expr)){return(!!(expr.toNumber()))?val1:val2;}
throw LF.formula.errorList.notLogical;},_TFIELD:function(fieldId){return $("#Field"+fieldId);},_NFIELD:function(fieldId){var field=$("#Field"+fieldId);var numString=field.val().replace(new RegExp(LF.number.separatorChar,"g"),"");if(LF.formula.isNumberString(numString)){return LF.f._BN(numString);}
return field;},_MEMB:function(id){return undefined;},_CBMEM:function(id,choiceName){return undefined;},_CCBM:function(id,choiceName){return undefined;},_RFIELD:function(fieldId){for(var i=0;$("#Field"+fieldId+"-"+i).length;i++){if($("#Field"+fieldId+"-"+i).is(':checked')){var testVal=$("#Field"+fieldId+"-"+i).val();if(LF.formula.isNumberString(testVal)){return LF.f._BN(testVal);}
else{return testVal;}}}
if($("#Field"+fieldId+"_other").is(':checked')){var testVal=$("#Field"+fieldId+"_other_value").val();if(LF.formula.isNumberString(testVal)){return LF.f._BN(testVal);}
return testVal;}
return"";},_DROPDOWN:function(fieldId){var targetField=$("#Field"+fieldId);var fieldVal=targetField.val();if(LF.formula.isNumberString(fieldVal)){return LF.f._BN(fieldVal);}
return fieldVal;},_CBFIELD:function(fieldId,checkboxNum){if(checkboxNum===-1){if(!$("#Field"+fieldId+"_other").is(':checked')){return"";}
var testVal=$("#Field"+fieldId+"_other_value").val();if(LF.formula.isNumberString(testVal)){return LF.f._BN(testVal);}
else if(testVal===undefined||testVal.length===0){return"";}
else{return testVal;}}
else if(checkboxNum===-2){return $("#Field"+fieldId+"_other").is(':checked');}
return $("#Field"+fieldId+"-"+checkboxNum).is(':checked');},_DFIELD:function(fieldId){var field=$("[id='Field"+fieldId+"']");var momentFormat=field.attr('momentpattern');if(typeof momentFormat===typeof undefined||momentFormat===false){throw"date field error";}
var fieldVal=field.val();if(fieldVal===""){return"";}
var dateValue=moment(field.val(),momentFormat);if(!dateValue.isValid()){return"";}
return LF.f._DateToSerialNumber(dateValue);},_CDATE:function(fieldId){var fieldValues=new Array();$("[id^='Field"+fieldId+"(']").each(function(){fieldValues.push(LF.f._DFIELD($(this).attr('id').substring(5)));});return fieldValues;},_CTEXT:function(fieldId){var fieldValues=new Array();$("[id^='Field"+fieldId+"(']").each(function(){fieldValues.push($(this).val());});return fieldValues;},_CNUMBER:function(fieldId){var fieldValues=new Array();$("[id^='Field"+fieldId+"(']").each(function(){var numString=$(this).val().replace(LF.number.separatorChar,"");if(LF.formula.isNumberString(numString)){fieldValues.push(LF.f._BN(numString));}
else{fieldValues.push($(this).val());}});return fieldValues;},_CDROP:function(fieldId){var fieldValues=new Array();$("[id^='Field"+fieldId+"(']").each(function(){var fieldValue=$(this).val();if(LF.formula.isNumberString(fieldValue)){fieldValues.push(LF.f._BN(fieldValue));}
else{fieldValues.push(fieldValue);}});return fieldValues;},_CRADIO:function(value){var fieldValues=new Array();var i=1;var radioFields=$("[id^='Field"+value+"(1)-']");while(radioFields.size()!==0){var choiceDetected=false;radioFields.each(function(){if($(this).is(':checked')){var stringVal=$(this).val();if(LF.formula.isNumberString(stringVal)){fieldValues.push(LF.f._BN(stringVal));}
else{fieldValues.push(stringVal);}
choiceDetected=true;return false;}});if(!choiceDetected){if($("[id='Field"+value+"("+i+")_other']").is(':checked')){var stringVal=$("[id='Field"+value+"("+i+")_other_value']").val();if(LF.formula.isNumberString(stringVal)){fieldValues.push(LF.f._BN(stringVal));}
else{fieldValues.push('');}
choiceDetected=true;}
else{fieldValues.push(undefined);}}
i++;radioFields=$("[id^='Field"+value+"("+i+")-']");}
return fieldValues;},_CCB:function(fieldId,choiceIndex){var fieldValues=new Array();var i=1;if(choiceIndex===-1){var otherInput=$("[id='Field"+fieldId+"("+i+")_other']");while(otherInput.size()){if(otherInput.is(':checked')){fieldValues.push($("[id='Field"+fieldId+"("+i+")_other_value']").val());}
else{fieldValues.push('');}
i++;otherInput=$("[id='Field"+fieldId+"("+i+")_other']");};}
else{var item=choiceIndex===-2?'_other':('-'+choiceIndex);var choiceInput=$("[id='Field"+fieldId+"("+i+")"+item+"']");while(choiceInput.size()){fieldValues.push(choiceInput.is(':checked'));i++;choiceInput=$("[id='Field"+fieldId+"("+i+")"+item+"']");}}
return fieldValues;},_DCFIELD:function(value){return undefined;},_UNKNOWN:function(value){return undefined;},_ToString:function(value){var ret="";if(LF.f._IsString(value)){ret+=value;}
else if(LF.f._IsBigNumber(value)){if(math.bignumber(value.toPrecision(15)).eq(value)){ret=value.toString();}
else{ret=Number(value.toPrecision(15)).toString();}}
else if(value===true){ret="TRUE";}
else if(value===false){ret="FALSE";}
else if(LF.f._IsArray(value)){var retString="";_.forEach(value,function(singleVal){retString+=LF.f._ToString(singleVal)+',';})
ret=retString.substring(0,retString.length-1);}
else if(value===undefined){ret="";}
else{ret+=value;}
return ret.trim();},_TryGetFormattedDate:function(serialNumber,momentFormat){if(!LF.f._IsBigNumber(serialNumber)){if(LF.formula.isNumberString(serialNumber)){serialNumber=LF.f._BN(serialNumber);}
else{return LF.f._ToString(serialNumber);}}
var dateValue=LF.f._SerialNumberToDate(serialNumber);return dateValue.utcOffset(moment().utcOffset()).format(momentFormat);},_IsString:function(value){return LF.formula.isString(value);},_AMP:function(val1,val2){LF.f._FixArguments(arguments);if(arguments.length===2){return LF.f._ToString(val1)+LF.f._ToString(val2);}
throw LF.formula.errorList.badArgCount;},CHAR:function(code){LF.f._FixArguments(arguments);if(arguments.length===1&&code!==undefined){if(LF.f._IsBigNumber(code)){if(code.toNumber()>=1&&code.toNumber()<=255){return String.fromCharCode(code.toNumber());}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},CODE:function(char){LF.f._FixArguments(arguments);if(arguments.length===1&&char!==undefined){if(LF.f._IsString(char)&&char!==""){return new LF.f._BN(char.charCodeAt(0));}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.badArgCount;},EXACT:function(var1,var2){LF.f._FixArguments(arguments);if(arguments.length===2&&var1!==undefined&&var2!==undefined){if(LF.f._IsArray(var1)&&LF.f._IsArray(var2)){return LF.f._ToString(var1[0])===LF.f._ToString(var2[0]);}
return LF.f._ToString(var1)===LF.f._ToString(var2);}
throw LF.formula.errorList.badArgCount;},FIND:function(search,text,startIndex){LF.f._FixArguments(arguments);if(arguments.length!==2&&arguments.length!==3){throw LF.formula.errorList.badArgCount;}
if(startIndex===undefined){startIndex=LF.f._BN(1);}
if(!LF.f._IsBigNumber(startIndex)){throw LF.formula.errorList.notNumber;}
if(!LF.f._IsString(search)||!LF.f._IsString(text)||startIndex.lt(1)){throw LF.formula.errorList.badArgValue;}
var findIndex=text.indexOf(search,startIndex-1);if(findIndex===-1){throw LF.formula.errorList.badArgValue;}
return LF.f._BN(findIndex).plus(1);},CONCATENATE:function(){LF.f._FixArguments(arguments);var resultString="";_.forEach(arguments,function(arg){resultString+=LF.f._ToString(arg);});return resultString;},INDEX:function(ref,rows){var columns=null;LF.f._FixArguments(arguments);if(LF.f._IsBigNumber(rows)){rows=LF.f._TruncateNumber(rows)}
if(columns){if(LF.f._IsBigNumber(columns)){columns=LF.f._TruncateNumber(columns);}}
if(rows<1||(columns&&columns<1)){throw LF.formula.errorList.outOfRange;}
return columns?ref[rows-1][columns-1]:ref[rows-1];},ROW:function(){LF.f._FixArguments(arguments);var resultString=0;if(LF.formula.popfield){var field=LF.formula.popfield.attr("id");var f=field.indexOf("(");if(f!=-1){resultString=field.substring(f+1,field.indexOf(")"));}}
return LF.f._BN(resultString);},COLUMN:function(){LF.f._FixArguments(arguments);var resultString=0;if(LF.formula.popfield){var coltype=LF.formula.popfield.closest('.cf-collection,.cf-table');if(coltype.length){if(coltype.hasClass('cf-table')){var t=LF.formula.popfield.closest('[data-col]');resultString=t.parent().find('[data-col]').index(t)+1;}
else{resultString=LF.formula.popfield.closest('li').index()+1;}}}
return LF.f._BN(resultString);},LEN:function(text){LF.f._FixArguments(arguments);if(arguments.length===1&&text!==undefined){if(LF.f._IsBigNumber(text)||LF.f._IsString(text)){return new LF.f._BN((LF.f._ToString(text).length));}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.badArgCount;},FIXED:function(number,decimals,no_commas){LF.f._FixArguments(arguments,true);if(arguments.length<1||arguments.length>3||number===undefined){throw LF.formula.errorList.badArgCount;}
if(decimals===undefined){decimals=LF.f._BN(2);}
if(no_commas===undefined){no_commas=false;}
if(!LF.f._IsBigNumber(number)||!LF.f._IsBigNumber(decimals)){throw LF.formula.errorList.notNumber;}
if(!LF.f._IsBoolean(no_commas)){throw LF.formula.errorList.notLogical;}
if(decimals.gt(0)){number=number.toFixed(decimals);}
else{number=math.round(number.times(math.pow(10,decimals))).div(math.pow(10,decimals)).toFixed();}
var numberPieces=number.split(LF.number.decimalChar);if(!no_commas){numberPieces[0]=LF.number.addThousandsSeparators(numberPieces[0]);}
if(numberPieces.length>2){throw LF.formula.errorList.unexpectedError;}
number=numberPieces.length===2?numberPieces[0]+LF.number.decimalChar+numberPieces[1]:numberPieces[0];return number;},LEFT:function(text,length){LF.f._FixArguments(arguments,true);if((arguments.length===1||arguments.length===2)&&text!==undefined){if(LF.f._IsBigNumber(length)||length===undefined){if(length===undefined){length=LF.f._BN(1);}
length=LF.f._TruncateNumber(length);if(LF.f._IsString(text)&&(length>=0)){return text.substring(0,length);}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},RIGHT:function(text,length){LF.f._FixArguments(arguments,true);if((arguments.length===1||arguments.length===2)&&text!==undefined){if(LF.f._IsBigNumber(length)||length===undefined){if(length===undefined){length=1;}
if(LF.f._IsString(text)&&(length.gte(0))){return text.substring(text.length-Math.floor(length.toNumber()));}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},LOWER:function(text){LF.f._FixArguments(arguments);if(arguments.length===1&&text!==undefined){return LF.f._ToString(text).toLowerCase();}
throw LF.formula.errorList.badArgCount;},UPPER:function(text){LF.f._FixArguments(arguments);if(arguments.length===1&&text!==undefined){return LF.f._ToString(text).toUpperCase();}
throw LF.formula.errorList.badArgCount;},_IsAlpha:function(char){return(char.length===1&&(char).match(/^[a-zA-Z]/)!==null);},_ToUpper:function(char){if(LF.f._IsAlpha(char)){return char.toUpperCase();}
else{return LF.f._ToString(char);}},_ToLower:function(char){if(LF.f._IsAlpha(char)){return char.toLowerCase();}
else{return LF.f._ToString(char);}},PROPER:function(text){LF.f._FixArguments(arguments);if(arguments.length===1&&text!==undefined){text=LF.f._ToString(text);if(text.length){var k=0;text=LF.f.REPLACE(text,LF.f._BN(k).plus(1),LF.f._BN(1),LF.f.UPPER(text[k]));for(k=1;k<text.length;k++){if(text[k]==' '){text=text+text[k];}
else if(!LF.f._IsAlpha(text[k-1])){text=LF.f.REPLACE(text,LF.f._BN(k).plus(1),LF.f._BN(1),LF.f.UPPER(text[k]));}
else{text=LF.f.REPLACE(text,LF.f._BN(k).plus(1),LF.f._BN(1),LF.f.LOWER(text[k]));}}}
return text;}
throw LF.formula.errorList.badArgCount;},REPT:function(text,count){LF.f._FixArguments(arguments,true);if(arguments.length===2&&text!==undefined){if(LF.f._IsBigNumber(count)){if(count>=0){return new Array(Number(count|0)+1).join(LF.f._ToString(text));}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},SPLIT:function(text,splitString){LF.f._FixArguments(arguments);if(arguments.length!==2){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsString(text)||!LF.f._IsString(splitString)||splitString===""){throw LF.formula.errorList.badArgValue;}
return _.filter(text.split(splitString),function(ele){return ele!=="";});},JOIN:function(separator,array){LF.f._FixArguments(arguments);if(arguments.length!==2){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsArray(array)||!LF.f._IsString(separator)){throw LF.formula.errorList.badArgValue;}
_.forEach(array,function(value,index,inArray){inArray[index]=LF.f._ToString(value);});return array.join(separator);},MID:function(text,start,length){LF.f._FixArguments(arguments,true);if(arguments.length===3&&text!==undefined){if(LF.f._IsBigNumber(start)&&LF.f._IsBigNumber(length)){start=LF.f._TruncateNumber(start);length=LF.f._TruncateNumber(length);if(start>=1&&length>=0){return LF.f._ToString(text).substring(start-1,start-1+Number(length));}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},REPLACE:function(text,start,count,newText){LF.f._FixArguments(arguments,true);if(arguments.length===4&&text!==undefined&&newText!==undefined){if(LF.f._IsBigNumber(start)&&LF.f._IsBigNumber(count)){if(start>=1){return LF.f._ToString(text).substring(0,Number(start|0)-1)+LF.f._ToString(newText)+LF.f._ToString(text).substring(Number(start|0)-1+Number(count|0));}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},TEXT:function(text){LF.f._FixArguments(arguments);if(arguments.length===1&&text!==undefined){return(LF.f._ToString(text));}
throw LF.formula.errorList.badArgCount;},T:function(text){LF.f._FixArguments(arguments);if(arguments.length===1&&text!==undefined){if(LF.f._IsString(text)){return text;}
else{return"";}}
throw LF.formula.errorList.badArgCount;},SUBSTITUTE:function(text,oldText,newText,whichOccurrence){LF.f._FixArguments(arguments);if(arguments.length!==3&&arguments.length!==4){throw LF.formula.errorList.badArgCount;}
var textString=LF.f._ToString(text);var oldString=LF.f._ToString(oldText);var newString=LF.f._ToString(newText);if(!LF.f._IsBigNumber(whichOccurrence)&&typeof whichOccurrence!==typeof undefined){throw LF.formula.errorList.notNumber;}
if(oldString===""){return textString;}
if(typeof whichOccurrence===typeof undefined){return textString.replace(new RegExp(oldString,'g'),newString);}
if(whichOccurrence.lt(1)){throw LF.formula.errorList.badArgValue;}
var textPieces=textString.split(oldString);var tmpPieces=[];_.forEach(textPieces,function(piece,index,array){tmpPieces.push(piece);if(index<array.length-1){tmpPieces.push(oldString);}});whichOccurrence=whichOccurrence.times(2).minus(1);if(whichOccurrence.lt(tmpPieces.length)){tmpPieces[whichOccurrence]=newString;}
return tmpPieces.join('');},TRIM:function(text){LF.f._FixArguments(arguments);if(arguments.length===1&&text!==undefined){return LF.f._ToString(text).replace(/ {1,}/g," ").trim();}
throw LF.formula.errorList.badArgCount;},_parseValue:function(text){var result=LF.f._BN(0);if(typeof(text)!='string'||text==""){return null;}
var re1=/^[+-]?[ ]*[0-9]+(([eE][+-]?[0-9]+)|%)?$/;var re2=/^[+-]?\$?([0-9]+(,[0-9]{3})*)?(\.[0-9]+)?(([eE][+-]?[0-9]+)|%)?$/;var re3=/^[+-]?[ ]*[0-9]+[ ]+[0-9]+\/[1-9][0-9]?$/;var dateTimeRe=/^(?:(?:(?:0?[1-9]|1[0-2])[/-](?:[0-2]?[0-9]|3[0-1])[/-]|(?:[0-2]?[0-9]|3[0-1])[/-](?:0?[1-9]|1[0-2])[/-])(?:\d{4}|\d{2})|(?:\d{4}|\d{2})[/-](?:0?[1-9]|1[0-2])[/-](?:[0-2]?[0-9]|3[0-1])?)(?:\s(?:(?:[0-1]?[0-9]|2[0-3])(?::[0-5]?[0-9])?(?::[0-5]?[0-9](?:\.\d{1,3})?)?(?:\s(?:am|pm))?))?$/i;var ISOdateTimeRe=/^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;var alphabeticDateTimeRe=/^(?:[a-z]+\s(?:[0-2]?[0-9]|3[0-1]),|(?:[0-2]?[0-9]|3[0-1])\s[a-z]+,?)\s\d{4}(?:\s|\b)(?:(?:[0-1]?[0-9]|2[0-3])(?::[0-5]?[0-9])?(?::[0-5]?[0-9](?:\.\d*)?)?(?:\s(?:am|pm))?)?$/i;var timeRe=/^(?:[0-1]?[0-9]|2[0-3])(?::[0-5]?[0-9])?(?::[0-5]?[0-9](?:\.\d{1,3})?)?$|^(?:0?[0-9]|1[0-2])(?::[0-5]?[0-9])?(?::[0-5]?[0-9](?:\.\d{1,3})?)?(?:\s(?:AM|PM))?$/i;text=text.trim();if(re1.test(text)||re2.test(text)){if(text.indexOf("$")>-1){text=text.replace("$","");}
if(text.indexOf(",")>-1){text=text.replace(/,/g,"");}
if(text.charAt(text.length-1)=='%'){text=text.slice(0,-1);return LF.f._BN(text).div(100);}
else{return LF.f._BN(text);}}
else if(re3.test(text)){var stringList=text.split(' ');result=0;for(var s in stringList){if(stringList[s].indexOf('/')>-1){var fracArr=stringList[s].split('/');result+=parseFloat(fracArr[0])/parseFloat(fracArr[1]);}
else{result+=Math.abs(parseFloat(stringList[s]));}}
if(text.charAt(0)=='-'){result=-result;}
return LF.f._BN(result.toPrecision(15));}
else if(dateTimeRe.test(text)||ISOdateTimeRe.test(text)){var datetime=moment(text,LF.f._DateTimeFormat);if(!datetime.isValid()){return null;}
else{return LF.f._DateToSerialNumber(datetime);}}
else if(alphabeticDateTimeRe.test(text)){var datetime=moment(text,LF.f._AlphabeticDateTimeFormat,true);if(!datetime.isValid()){return null;}
else{return LF.f._DateToSerialNumber(datetime);}}
else if(timeRe.test(text)){if(/PM/i.test(text)){result=LF.f._BN(0.5);}
if(/PM|AM/i.test(text)){text=text.replace(/PM|AM/i,"").trim();if(LF.f._IsBigNumber(LF.f._FilterFloat(text))){return result.plus(LF.f._DurationToSerialNumber(moment.duration(LF.f._FilterFloat(text).toNumber()%12,"hours")));}
else{var duration=moment.duration(text);if(duration.hours>12){duration.hours=duration.hours-12}
return result.plus(LF.f._DurationToSerialNumber(duration).mod(LF.f._BN(0.5)));}}
else{return LF.f._DurationToSerialNumber(moment.duration(text));}}
else{return null;}},VALUE:function(text){LF.f._FixArguments(arguments,false,true);if(arguments.length===1&&text!==undefined){if(text===""){return LF.f._BN(0);}
var result=LF.f._parseValue(text);if(result==null){throw LF.formula.errorList.badArgValue;}
return result;}
throw LF.formula.errorList.badArgCount;},_DateTimeFormat:[moment.ISO_8601,"M/D/YYYY","M-D-YYYY","M/D/YYYY h:m:s A","M-D-YYYY h:m:s A","M/D/YYYY h:m A","M-D-YYYY h:m A","M/D/YYYY h A","M-D-YYYY h A","M/D/YYYY H:m:s","M-D-YYYY H:m:s","M/D/YYYY H:m","M-D-YYYY H:m","YYYY/M/D","YYYY-M-D","YYYY/M/D h:m:s A","YYYY-M-D h:m:s A","YYYY/M/D h:m A","YYYY-M-D h:m A","YYYY/M/D h A","YYYY-M-D h A","YYYY/M/D H:m:ss","YYYY-M-D H:m:s","YYYY/M/D H:m","YYYY-M-D H:m",],_AlphabeticDateTimeFormat:["MMM D, YYYY","D MMM YYYY","MMMM D, YYYY","D MMMM YYYY","D MMM, YYYY","D MMMM, YYYY","MMM D, YYYY H:m:s","D MMM YYYY H:m:s","MMMM D, YYYY H:m:s","D MMMM YYYY H:m:s","D MMM, YYYY H:m:s","D MMMM, YYYY H:m:s","MMM D, YYYY H:m","D MMM YYYY H:m","MMMM D, YYYY H:m","D MMMM YYYY H:m","D MMM, YYYY H:m","D MMMM, YYYY H:m","MMM D, YYYY h:m:s A","D MMM YYYY h:m:s A","MMMM D, YYYY h:m:s A","D MMMM YYYY h:m:s A","D MMM, YYYY h:m:s A","D MMMM, YYYY h:m:s A","MMM D, YYYY h:m A","D MMM YYYY h:m A","MMMM D, YYYY h:m A","D MMMM YYYY h:m A","D MMM, YYYY h:m A","D MMMM, YYYY h:m A","MMM D, YYYY h A","D MMM YYYY h A","MMMM D, YYYY h A","D MMMM YYYY h A","D MMM, YYYY h A","D MMMM, YYYY h A",],_IsDate:function(value){return moment.isMoment(value)&&value.isValid();},_IsDateWithinRange:function(year,month,day){if(arguments.length===3&&LF.f._IsBigNumber(year)&&LF.f._IsBigNumber(month)&&LF.f._IsBigNumber(day)){return(year.gte(LF.formula.minDate)&&year.lte(LF.formula.maxDate)&&month.gte(1)&&day.gte(1)&&LF.f._IsInteger(year)&&LF.f._IsInteger(month)&&LF.f._IsInteger(day));}
return null;},_IsLeapYear:function(dateObj){if(arguments.length!==1||arguments[0]===undefined){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsDate(dateObj)){dateObj=LF.f._DateToSerialNumber(LF.f._TryConvertToDate(dateObj));}
if(LF.f.YEAR(dateObj).lessThan(LF.formula.minDate)||LF.f.YEAR(dateObj).greaterThan(LF.formula.maxDate)){throw LF.formula.errorList.badArgValue;}
return moment([LF.f.YEAR(dateObj).toNumber()]).isLeapYear();},_TruncateDate:function(dateObj){if(!LF.f._IsDate(dateObj)){dateObj=LF.f._TryConvertToDate(dateObj);}
dateObj=LF.f._DateToSerialNumber(dateObj);return new moment([LF.f.YEAR(dateObj),LF.f.MONTH(dateObj).minus(1),LF.f.DAY(dateObj)]);},_IsLastDayOfFebruary:function(dateObj){if(!LF.f._IsDate(dateObj)){dateObj=LF.f._DateToSerialNumber(LF.f._TryConvertToDate(dateObj));}
return(LF.f.MONTH(dateObj).toNumber()===2&&((LF.f.DAY(dateObj).toNumber()===28&&LF.f._IsLeapYear(dateObj))||(LF.f.DAY(dateObj).toNumber()===29&&LF.f._IsLeapYear(dateObj))));},_DayCount:function(date1,date2,basis){if(arguments.length===3){date1=LF.f._TruncateDate(date1);date2=LF.f._TruncateDate(date2);if(date1===date2){return LF.f._BN(0);}
else if(date1>date2){var temp=date2;date2=date1;date1=temp;}
var days1=LF.f.DAY(LF.f._DateToSerialNumber(date1));var days2=LF.f.DAY(LF.f._DateToSerialNumber(date2));switch(basis.toNumber()){case 0:if(days1.toNumber()===31){days1=days1.minus(1);}
if(days1.toNumber()===30&&days2.toNumber()===31){days2=days2.minus(1);}
if(LF.f._IsLastDayOfFebruary(date1)&&LF.f._IsLastDayOfFebruary(date2)){days2=LF.f._BN(30);}
if(LF.f._IsLastDayOfFebruary(date1)){days1=LF.f._BN(30);}
return LF.f._BN(LF.f.YEAR(LF.f._DateToSerialNumber(date2))).times(360).plus(LF.f._BN(LF.f.MONTH(LF.f._DateToSerialNumber(date2))).times(30)).plus(LF.f._BN(days2)).minus(LF.f._BN(LF.f.YEAR(LF.f._DateToSerialNumber(date1))).times(360).plus(LF.f._BN(LF.f.MONTH(LF.f._DateToSerialNumber(date1))).times(30)).plus(LF.f._BN(days1)));case 1:case 2:case 3:return LF.f._BN(Math.round(LF.f.SUB(LF.f._DateToSerialNumber(date2),LF.f._DateToSerialNumber(date1))));case 4:return LF.f._BN(LF.f.DAYS360(LF.f._DateToSerialNumber(date1),LF.f._DateToSerialNumber(date2),LF.f._BN(1)));default:throw LF.formula.errorList.badArgValue;}}},_DoesContainFeb29:function(startDate,endDate){if(startDate>endDate){var temp=endDate;endDate=startDate;startDate=temp;}
var leapYear=LF.f.FLOOR(LF.f.YEAR(endDate),LF.f._BN(4));if(!LF.f._IsLeapYear(new Date(leapYear.toNumber(),0,1))){leapYear=leapYear.minus(4);}
return((LF.f.SUB(endDate,new Date(leapYear.toNumber(),1,29)).gte(0)&&((LF.f.SUB(new Date(leapYear,1,29),startDate)).gte(0))));},_AverageDaysPerYear:function(date1,date2){if(arguments.length===2){if(!LF.f._IsDate(date1)||!LF.f._IsDate(date2)){date1=LF.f._TryConvertToDate(date1);date2=LF.f._TryConvertToDate(date2);}
var excess=0;if(!(LF.f.YEAR(date2)-LF.f.YEAR(date1))){return LF.f._BN(365+moment([LF.f.YEAR(date1)]).isLeapYear());}
for(var k=LF.f.YEAR(date1);k<=LF.f.YEAR(date2);k++){excess+=moment([k]).isLeapYear();}
return LF.f._BN(365).times((LF.f.YEAR(date2).minus(LF.f.YEAR(date1)).plus(1))).plus(excess).div(((LF.f.YEAR(date2).minus(LF.f.YEAR(date1)).plus(1))));}
throw LF.formula.errorList.badArgCount;},_DaysInYear:function(date1,date2,basis){switch(basis.toNumber()){case 0:return LF.f._BN(360);case 1:var condition1=(LF.f.YEAR(date1)!==LF.f.YEAR(date2));var condition2=(LF.f.YEAR(date2)!==(LF.f.YEAR(date1)+1));var condition3=(LF.f.MONTH(date1)<LF.f.MONTH(date2));var condition4=(LF.f.MONTH(date1)===LF.f.MONTH(date2));var condition5=(LF.f.DAY(date1)<LF.f.DAY(date2));if((condition1&&condition2)||(condition1&&condition3)||(condition1&&condition4&&condition5)){return LF.f._AverageDaysPerYear(date1,date2);}
if((LF.f.YEAR(date1)!==LF.f.YEAR(date2)&&LF.f._IsLeapYear(date1))||LF.f._DoesContainFeb29(date1,date2)||(LF.f.MONTH(date2)===2&&LF.f.DAY(date2)===29)){return LF.f._BN(366);}
else{return LF.f._BN(365);}
case 2:return LF.f._BN(360);case 3:return LF.f._BN(365);case 4:return LF.f._BN(360);default:throw LF.formula.errorList.badArgValue;}},_CheckWorkDay:function(holidays,workdays){if(!LF.f._IsArray(holidays)||!LF.f._IsArray(workdays)){throw LF.formula.errorList.badArgValue;}
if(!_.every(holidays,function(holiday){return LF.f._IsBigNumber(holiday);})){throw LF.formula.errorList.notDate;}
if(workdays.length!==7){throw LF.formula.errorList.badArgValue;}
else if(!_.every(workdays,function(n){return LF.f._IsBigNumber(n);})){throw LF.formula.errorList.notNumber;}
else if(!_.every(workdays,function(n){return(n.eq(LF.f._BN(1))||n.eq(LF.f._BN(0)));})){throw LF.formula.errorList.badArgValue;}
else if(LF.f.SUM(workdays).toNumber()===7){throw LF.formula.errorList.badArgValue;}
return true;},_TryConvertToDate:function(value){if(LF.f._IsBigNumber(value)){var date=LF.f._SerialNumberToDate(value);if(date.isValid()){return date;}}
throw LF.formula.errorList.notDate;},_DateToSerialNumber:function(momentDate){return math.bignumber(momentDate.utcOffset()).times(60000).plus(momentDate.valueOf()).div(86400000).plus(25569);},_DurationToSerialNumber:function(momentDuration){return math.bignumber(momentDuration.asMilliseconds()).div(86400000);},_SerialNumberToDate:function(serialNumber){var unixTimeInMs=serialNumber.minus(25569).times(86400000).minus(math.bignumber(moment().utcOffset()).times(60000));return moment(unixTimeInMs.toNumber()).utcOffset(moment().utcOffset());},DATE:function(year,month,day){LF.f._FixArguments(arguments,true);if(arguments.length===3){if(LF.f._IsBigNumber(year)&&LF.f._IsBigNumber(month)&&LF.f._IsBigNumber(day)){year=LF.f._TruncateNumber(year);month=LF.f._TruncateNumber(month);day=LF.f._TruncateNumber(day);if(!LF.f._IsDateWithinRange(year,month,day)){throw LF.formula.errorList.badArgValue;}
if(year.lte(LF.formula.cutoffYear)){year=year.plus(1900);}
var retDate=moment([year]);retDate.add(month.minus(1).toNumber(),'months');retDate.add(day.minus(1).toNumber(),'days');if(retDate.get('year')>LF.formula.maxDate){throw LF.formula.errorList.badArgValue;}
return LF.f._DateToSerialNumber(retDate);}
throw LF.formula.errorList.notNumber;}
throw LF.formula.errorList.badArgCount;},YEAR:function(value){LF.f._FixArguments(arguments);if(arguments.length!==1||value===undefined){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsDate(value)){value=LF.f._TryConvertToDate(value);}
return LF.f._BN(value.get('year'));},MONTH:function(value){LF.f._FixArguments(arguments);if(arguments.length!==1||value===undefined){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsDate(value)){value=LF.f._TryConvertToDate(value);}
return LF.f._BN(value.get('month')+1);},DAY:function(value){LF.f._FixArguments(arguments);if(arguments.length!==1||value===undefined){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsDate(value)){value=LF.f._TryConvertToDate(value);}
return LF.f._BN(value.get('date'));},TODAY:function(){LF.f._FixArguments(arguments);if((arguments.length===1&&arguments[0]===undefined)||!arguments.length){var today=moment().utcOffset(processUtcOffset).startOf('day');return LF.f._DateToSerialNumber(today);}
throw LF.formula.errorList.badArgCount;},DAYS360:function(startDate,endDate,mode){LF.f._FixArguments(arguments);if((arguments.length===2||arguments.length===3)){if(!LF.f._IsDate(startDate)||!LF.f._IsDate(endDate)){startDate=LF.f._TryConvertToDate(startDate);endDate=LF.f._TryConvertToDate(endDate);}
var sign=LF.f._BN(1);if(arguments.length===2){mode=LF.f._BN(0);}
else if(!LF.f._IsBigNumber(mode)){throw LF.formula.errorList.badArgValue;}
else if(mode.toNumber()<0||mode.toNumber()>1){throw LF.formula.errorList.badArgValue;}
if(mode.toNumber()===1&&endDate<startDate){sign=LF.f._BN(-1);var temp=endDate;endDate=startDate;startDate=temp;}
var day1=LF.f.DAY(startDate);var day2=LF.f.DAY(endDate);if(day1.toNumber()===31){day1=day.minus(1);}
if(mode.toNumber()<1&&LF.f.MONTH(startDate).toNumber()===2&&((LF.f._IsLeapYear(startDate)&&day1.toNumber()===29)||(!LF.f._IsLeapYear(startDate)&&day1.toNumber()===28))){day1=LF.f._BN(30);}
if(mode.toNumber()<0&&day2.toNumber()===31&&day1.toNumber()===30){day2=day2.minus(1);}
if(mode.toNumber()===1&&day2.toNumber()===31){day2=LF.f._BN(30);}
return LF.f._BN(sign.times(((LF.f.YEAR(endDate).times(360).plus(LF.f.MONTH(endDate).times(30).plus(day2))).minus((LF.f.YEAR(startDate).times(360).plus(LF.f.MONTH(startDate).times(30).plus(day1)))))));}
throw LF.formula.errorList.badArgCount;},YEARFRAC:function(date1,date2,basis){LF.f._FixArguments(arguments);if(arguments.length===2){basis=LF.f._BN(0);}
if((arguments.length===2||arguments.length===3)){if(!LF.f._IsDate(date1)||!LF.f._IsDate(date2)){date1=LF.f._TryConvertToDate(date1);date2=LF.f._TryConvertToDate(date2);}
if(LF.f._IsBigNumber(basis)){basis=LF.f._TruncateNumber(basis);}
else{throw LF.formula.errorList.notNumber;}
return(LF.f._DayCount(date1,date2,basis)).div(LF.f._DaysInYear(date1,date2,basis));}
throw LF.formula.errorList.badArgCount;},EDATE:function(startDate,months){LF.f._FixArguments(arguments,true);if(arguments.length===2){if(!LF.f._IsDate(startDate)){startDate=LF.f._TryConvertToDate(startDate);}
if(LF.f._IsBigNumber(months)){months=LF.f._TruncateNumber(months);}
else{throw LF.formula.errorList.notNumber;}
startDate=LF.f._TruncateDate(startDate);return LF.f._DateToSerialNumber(moment(startDate).add(months.toNumber(),'months'));}
throw LF.formula.errorList.badArgCount;},EOMONTH:function(startDate,months){LF.f._FixArguments(arguments,true);if(arguments.length===2){if(!LF.f._IsDate(startDate)){startDate=LF.f._TryConvertToDate(startDate);}
if(LF.f._IsBigNumber(months)){months=LF.f._TruncateNumber(months);}
else{throw LF.formula.errorList.notNumber;}
startDate=LF.f._TruncateDate(startDate);startDate=moment(startDate).add(months.toNumber(),'months');return LF.f._DateToSerialNumber(moment([startDate.year(),startDate.month(),startDate.daysInMonth()]));}
throw LF.formula.errorList.badArgCount;},ADD_MONTHS:function(date,months){LF.f._FixArguments(arguments,true);if(arguments.length===2){if(!LF.f._IsDate(date)){date=LF.f._TryConvertToDate(date);}
if(!LF.f._IsBigNumber(months)){throw LF.formula.errorList.notNumber;}
var days=(months.mod(1).times(30));var hours=(days.mod(1).times(24));date=date.add(months.toNumber(),"months");date=date.add(days.toNumber(),"days");date=date.add(hours.toNumber(),"hours");return LF.f._DateToSerialNumber(date);}
throw LF.formula.errorList.badArgCount;},DATEVALUE:function(date){LF.f._FixArguments(arguments);if(arguments.length===1){if(LF.f._IsString(date)){var parsedDate=moment(date,"YYYY-MM-DD");if(parsedDate.isValid()&&parsedDate.get('year')<=LF.formula.maxParseDate&&parsedDate.get('year')>=LF.formula.minParseDate){if(date.trim().split('-')[0].length>4){throw LF.formula.errorList.badArgValue;}
return LF.f._DateToSerialNumber(parsedDate);}}
throw LF.formula.errorList.badArgValue;}
throw LF.formula.errorList.badArgCount;},WORKDAY:function(date,offset,holidays,workDays){LF.f._FixArguments(arguments,true);if(arguments.length>=2&&arguments.length<=4){if(holidays===undefined){holidays=[];}
if(workDays===undefined){workDays=[LF.f._BN(1),LF.f._BN(0),LF.f._BN(0),LF.f._BN(0),LF.f._BN(0),LF.f._BN(0),LF.f._BN(1)];}
if(LF.f._CheckWorkDay(holidays,workDays)){if(!LF.f._IsDate(date)){date=LF.f._TryConvertToDate(date);}
if(!LF.f._IsBigNumber(offset)){throw LF.formula.errorList.notNumber;}
if(!(offset.toNumber())){return LF.f._DateToSerialNumber(date);}
var sign=offset.greaterThan(0)?LF.f._BN(1):LF.f._BN(-1);holidays=_.uniq(holidays);var dayOfWeek=date;while(Math.abs(offset.toNumber())>0){dayOfWeek=dayOfWeek.add('days',sign.toNumber());if(workDays[dayOfWeek.day()].toNumber()===0){_.forEach(holidays,function(n){if(n.eq(LF.f._DateToSerialNumber(dayOfWeek))){offset=offset.plus(sign);}});offset=offset.minus(sign);}}
return LF.f._DateToSerialNumber(dayOfWeek);}
else{throw LF.formula.errorList.unexpectedError;}}
throw LF.formula.errorList.badArgCount;},NETWORKDAYS:function(date1,date2,holidays,workDays){LF.f._FixArguments(arguments);if(arguments.length>=2&&arguments.length<=4){if(workDays===undefined){workDays=[LF.f._BN(1),LF.f._BN(0),LF.f._BN(0),LF.f._BN(0),LF.f._BN(0),LF.f._BN(0),LF.f._BN(1)];}
if(holidays===undefined){holidays=[];}
if(!LF.f._IsDate(date1)||!LF.f._IsDate(date2)){date1=LF.f._TryConvertToDate(date1);date2=LF.f._TryConvertToDate(date2);}
var date1Later=date1>date2;if(date1Later){var temp=date1;date1=date2;date2=temp;}
if(LF.f._CheckWorkDay(holidays,workDays)){var offset=LF.f._BN(0);var dayOfWeek=date1;while(date2.valueOf()>=dayOfWeek.valueOf()){if(workDays[dayOfWeek.day()].toNumber()===0){_.forEach(holidays,function(n){if(n.eq(LF.f._DateToSerialNumber(dayOfWeek))){offset=offset.minus(1);}});offset=offset.plus(1);}
dayOfWeek=dayOfWeek.add('days',1);}
return date1Later?offset.neg():offset;}
else{throw LF.formula.errorList.unexpectedError;}}
throw LF.formula.errorList.badArgCount;},WEEKNUM:function(date,mode){LF.f._FixArguments(arguments);if(mode===undefined){mode=LF.f._BN(1);}
if(arguments.length!==2&&arguments.length!==1||date===undefined){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsDate(date)){date=LF.f._TryConvertToDate(date);}
if(!LF.f._IsBigNumber(mode)){throw LF.formula.errorList.notNumber;}
var previousDoW=moment().lang()._week.dow;switch(mode.toNumber()){case 1:case 17:moment().lang()._week.dow=0;break;case 2:case 11:moment().lang()._week.dow=1;break;case 12:moment().lang()._week.dow=2;break;case 13:moment().lang()._week.dow=3;break;case 14:moment().lang()._week.dow=4;break;case 15:moment().lang()._week.dow=5;break;case 16:moment().lang()._week.dow=6;break;case 21:case 150:return LF.f._BN(moment(date).isoWeek());default:throw LF.formula.errorList.badArgValue;}
var weekNum=LF.f._BN(moment(date).week());moment().lang()._week.dow=previousDoW;return weekNum;},WEEKDAY:function(date,type){LF.f._FixArguments(arguments);if(type===undefined||type==""){type=LF.f._BN(1);}
type=type.floor();if(arguments.length!==2&&arguments.length!==1||date===undefined){throw LF.formula.errorList.badArgCount;}
if(!LF.f._IsDate(date)){date=LF.f._TryConvertToDate(LF.f._IsBigNumber(date)?date:LF.f._parseValue(date));}
if(!LF.f._IsBigNumber(type)){throw LF.formula.errorList.notNumber;}
var weekDay=moment(date).day();switch(type.toNumber()){case 1:weekDay=weekDay+1;break;case 2:if(weekDay==0){weekDay=7;}
break;case 3:weekDay=(weekDay+6)%7;break;default:throw LF.formula.errorList.badArgValue;}
return LF.f._BN(weekDay);},DATEDIF:function(start_date,end_date,unit){LF.f._FixArguments(arguments);if(arguments.length===3){var startMoment=LF.f._TryConvertToDate(start_date);var endMoment=LF.f._TryConvertToDate(end_date);if(!LF.f._IsString(unit)){throw LF.formula.errorList.badArgValue;}
if(!startMoment.isValid()||!endMoment.isValid()){throw LF.formula.errorList.notDate;}
switch(unit.toUpperCase()){case"Y":return LF.f._BN(endMoment.diff(startMoment,'years'));break;case"M":return LF.f._BN(endMoment.diff(startMoment,'months'));break;case"D":return LF.f._BN(endMoment.diff(startMoment,'days'));break;case"MD":endMoment.month(startMoment.month());endMoment.year(startMoment.year());return LF.f._BN(endMoment.diff(startMoment,'days'));break;case"YM":endMoment.date(startMoment.date());endMoment.year(startMoment.year());return LF.f._BN(endMoment.diff(startMoment,'months'));break;case"YD":endMoment.year(startMoment.year());return LF.f._BN(endMoment.diff(startMoment,'days'));break;default:throw LF.formula.errorList.badArgValue;}}
throw LF.formula.errorList.badArgCount}}
var localize=localize||function(){return"";};LF.formula={jsonFormulas:'',errorList:{lessThanMin:{message:localize('ERR_VALUE_LESS_THAN_MIN')},greaterThanMax:{message:localize('ERR_VALUE_GREATER_THAN_MAX')},notNumber:{tag:"#!NUM"},notDate:{tag:"#!DATE"},badArgCount:{tag:"#ARGS"},divByZero:{tag:"#DIV/0"},unexpectedError:{tag:"#UNKNOWN"},badArgValue:{tag:"#VALUE"},outOfRange:{tag:"#INDEX"},notInteger:{tag:"#!INT"},notLogical:{tag:"#!LOGICAL"},},errorCount:0,warningList:{warningCalc:{message:localize('WRN_FORMULA_CALC_ERR')},formulaRefFields:{message:localize('WRN_FORMULA_REFERENCE_FIELDS')}},compareFormulas:function(a,b){if(a.order<b.order){return-1;}
else if(a.order>b.order){return 1;}
else{return 0;}},fixFloatError:function(value){return parseFloat((value).toPrecision(15));},isNumber:function(value){return typeof value==="number"&&!isNaN(value);},isNumberString:function(value){return!isNaN(parseFloat(value))&&isFinite(value)&&!Array.isArray(value);},isString:function(value){return typeof value==="string";},containsDate:function(value){var date=new Date(value);if(Object.prototype.toString.call(date)==='[object Date]'){return isNaN(date.getTime())?false:true;}
else{return false;}},getDateFormat:function(fieldId){if(!jsonForm||!jsonForm.fields){return null;}
var index=_.findIndex(jsonForm.fields,function(n){return(n.fieldId===fieldId);});if(index!==-1){return jsonForm.fields[index].format;}},insertValueInField:function(value,populatedField){var fieldValue="";var dateFormat=populatedField.attr('momentpattern');if(typeof dateFormat!==typeof undefined&&dateFormat!==false){fieldValue=LF.f._TryGetFormattedDate(value==''?0:value,dateFormat);}
else if(value==''&&populatedField.hasClass('number')){fieldValue="0";}
else{fieldValue=LF.f._ToString(value);}
var maxLength=populatedField.attr("maxlength");if(typeof maxLength!==typeof undefined&&maxLength!==false){fieldValue=fieldValue.substring(0,Number(maxLength));}
populatedField.val(fieldValue);},concatArgs:function(inputArguments){return _.flatten(inputArguments);},init:function(jsonForm){if(jsonForm&&jsonForm.formulas&&jsonForm.calculateFormulas){$("input[type='submit']").on('click',function(){LF.formula.displayLoadErrorMessages();});this.jsonFormulas=jsonForm.formulas.sort(this.compareFormulas);for(var i=0;i<this.jsonFormulas.length;i++){var formulaObject=this.jsonFormulas[i];var fieldId=formulaObject.populatedField;if(formulaObject.errorType==="none"){var popFields=LF.formula.getPopulatedFields(fieldId,false);if(formulaObject.triggerFields){for(var j=0;j<formulaObject.triggerFields.length;j++){LF.formula.setTriggerField(formulaObject.triggerFields[j],fieldId);}}
if(popFields.length===0){continue;}
_.each(popFields,function(pf){var popfield=LF.formula.popfield=$(pf);if(LF.formula.formulaTakesPrecedence(popfield)&&(!jsonForm.isDraft||((popfield.prop('backend-readonly')||popfield.prop('readonly'))&&!formulaObject.disableOnReadonly))){try{var fieldValue=eval(formulaObject.parsedExpression);if(fieldValue instanceof jQuery){fieldValue=fieldValue.val();}
LF.formula.insertValueInField(fieldValue,popfield);}
catch(error){popfield.val('');LF.formula.displayErrorMessage(popfield,error,formulaObject,formulaObject.triggerFields.length!=0);}
finally{popfield.trigger('change');}}});LF.formula.popfield=null;popFields.change(function(){LF.formula.removePopFieldError(this);});}}}},updateField:function(fieldId,isStartEvent,fieldObject,hideIfError){if(LF.formula.jsonFormulas){var formulaObject=_.find(LF.formula.jsonFormulas,function(formula){return formula.populatedField===parseInt(fieldId)})
var popFields=LF.formula.getPopulatedFields(fieldId,!formulaObject?false:formulaObject.disableOnReadonly,fieldObject);if(popFields.length===0){return;}
var isSEvent=isStartEvent||LF.lookup.startingCount!=0;_.each(popFields,function(pf){var popField=LF.formula.popfield=$(pf);var qf=$(popField).closest('li,td').data('qfield');if((isSEvent||(qf&&qf.isPreviousDataPreserved))&&popField.attr('vo')==='u'){return;}
if(typeof formulaObject===typeof undefined){if(popField.attr('id').indexOf('(')==-1){popField.trigger('updateFormula');}
return false;}
try{var fieldValue=eval(formulaObject.parsedExpression);if(fieldValue instanceof jQuery){fieldValue=fieldValue.val();}
var orgVal=popField.val();LF.formula.insertValueInField(fieldValue,popField);popField.trigger('change',[isStartEvent,null,null,orgVal]);if(popField.is('textarea')){popField.trigger('blur');}
LF.formula.removePopFieldError(popField);}
catch(error){if(!isSEvent){var hideError=hideIfError&&formulaObject.triggerFields.length!=0&&popField.attr('id').indexOf('(')!=-1;LF.formula.displayErrorMessage(popField,error,formulaObject,hideError);}}});LF.formula.propfield=null;}},formulaTakesPrecedence:function(populatedField){return populatedField.attr('vo')==='d'||populatedField.attr('vo')==='e';},setTriggerField:function(triggerFieldId,updateFieldId){var triggerFields=$("input[id='Field"+triggerFieldId+"'],textarea[id='Field"+triggerFieldId+"'],select[id='Field"+triggerFieldId+"'],[id^='Field"+triggerFieldId+"-']");if(triggerFields.length===0){triggerFields=$("[id^='Field"+triggerFieldId+"('][id*=')-']");}
if(triggerFields.length===0){triggerFields=$("[id^='Field"+triggerFieldId+"(']");}
var idAttr=triggerFields.attr('id');var isCheckboxOrRadio=false;if(typeof idAttr!==typeof undefined&&idAttr!==false){isCheckboxOrRadio=idAttr.indexOf('-')>-1;}
triggerFields.on('updateFormula',function(e,isStartEvent){LF.formula.updateField(updateFieldId,isStartEvent);});if(isCheckboxOrRadio){triggerFields.on('click',function(e,isStartEvent){LF.formula.updateField(updateFieldId,isStartEvent);});var otherCheck=$("[id='Field"+triggerFieldId+"_other']");var otherValue=$("[id='Field"+triggerFieldId+"_other_value']");if(otherCheck.length===0){otherCheck=$("[id^='Field"+triggerFieldId+"('][id$=')_other']");otherValue=$("[id^='Field"+triggerFieldId+"('][id$=')_other_value']");}
if(otherCheck.length!==0){otherCheck.on('click',function(e,isStartEvent){LF.formula.updateField(updateFieldId,isStartEvent);});otherValue.on('change',function(e,isStartEvent){LF.formula.updateField(updateFieldId,isStartEvent);});}}
else{triggerFields.on('change',function(e,isStartEvent){LF.formula.updateField(updateFieldId,isStartEvent);});}},setTriggerCollectionField:function(triggerFieldId){for(var i=0;i<LF.formula.jsonFormulas.length;i++){var currFormula=LF.formula.jsonFormulas[i];if(currFormula.errorType==="none"&&currFormula.triggerFields){var currTriggerFields=currFormula.triggerFields;for(var j=0;j<currTriggerFields.length;j++){if(currTriggerFields[j]==triggerFieldId.replace(/\([^)]*\).*/,"")){LF.formula.setTriggerField(triggerFieldId.replace('(','\\(').replace(')','\\)'),currFormula.populatedField);}}}}},updateCollectionFormulas:function(triggerFieldId,ignorePopulated){for(var i=0;i<LF.formula.jsonFormulas.length;i++){var currFormula=LF.formula.jsonFormulas[i];if(currFormula.populatedField==parseInt(triggerFieldId)&&!ignorePopulated){LF.formula.updateField(triggerFieldId,null,null,true);}
if(currFormula.triggerFields){var currTriggerFields=currFormula.triggerFields;for(var j=0;j<currTriggerFields.length;j++){if(currTriggerFields[j]==parseInt(triggerFieldId)){LF.formula.updateField(currFormula.populatedField,null,null,true);}}}}},addErrorMessage:function(populatedField,formulaObject,hide){if(populatedField.length===0){return;}
var popDiv=populatedField.parent('.cf-field');if(popDiv.length===0){return;}
var referenceFieldsString=this.getReferenceFieldsString(formulaObject);if(referenceFieldsString!==""){referenceFieldsString="<br />"+referenceFieldsString;}
var errmsg="<p class='ws-errormessage'>"+LF.formula.warningList.warningCalc.message+referenceFieldsString+"</p>";$("<div class='ws-errorbox' style='display: block;' id='formula-errorbox-"+populatedField.attr('id').substring(5)+"'>"+errmsg+"</div>").insertAfter(popDiv.children().last()).toggle(!hide);populatedField.attr("aria-describedby","formula-errorbox-"+populatedField.attr('id').substring(5));if(!hide){var popFieldError=$("[id='formula-errorbox-"+populatedField.attr('id').substring(5)+"']");popFieldError.animate({height:popFieldError.height('auto')});}
LF.formula.errorCount++;},getReferenceStringOfField:function(populatedFieldId){var formulaObject=_.find(this.jsonFormulas,function(formulaObj){return formulaObj.populatedField===populatedFieldId;});return this.getReferenceFieldsString(formulaObject);},getReferenceFieldsString:function(formulaObject){if(formulaObject.triggerFields.length===0){return"";}
var fieldLabelsString="";_.forEach(formulaObject.triggerFields,function(triggerFieldId){var triggerFieldObject=_.find(jsonForm.fields,function(field){return field.fieldId===triggerFieldId;});if(triggerFieldObject!==undefined){var memberPathPieces=triggerFieldObject.memberPath.split("_.");for(var i=0;i<memberPathPieces.length-1;i++){var parentFieldObject=_.find(jsonForm.fields,function(field){return field.memberId===parseInt(memberPathPieces[i]);});fieldLabelsString+=parentFieldObject.label+" ";}
fieldLabelsString+=triggerFieldObject.label+", ";}});if(fieldLabelsString.length!==0){fieldLabelsString=fieldLabelsString.substring(0,fieldLabelsString.length-2);}
LF.number.defineFormatFunction();return String.format(LF.formula.warningList.formulaRefFields.message,fieldLabelsString);},displayLoadErrorMessages:function(){var self=this;for(var i=0;i<this.jsonFormulas.length;i++){var formulaObject=this.jsonFormulas[i];var popFields=this.getPopulatedFields(formulaObject.populatedField,formulaObject.disableOnReadonly);_.each(popFields,function(pf){var popfield=$(pf);self.makeErrorVisible(popfield);});}},makeErrorVisible:function(popFields){var popFieldsErrors=$("[id='formula-errorbox-"+popFields.attr('id').substring(5)+"']");if(popFieldsErrors.length===0){return;}
var sectionBlock=popFieldsErrors.closest('div.cf-section-block');if(sectionBlock.length===0){return;}
sectionBlock.find('div.cf-section-header.collapsible.collapsed').trigger('click');},displayErrorMessage:function(populatedField,error,formulaObject,hideError){if(populatedField.hasClass("formula-error")){hideError=false;}
populatedField.addClass(hideError?"formula-error-hidden":"formula-error");var errEle=$("[id='formula-errorbox-"+populatedField.attr('id').substring(5)+"']").toggle(!hideError);if(errEle.length){return;}
populatedField.val("");populatedField.trigger('change');this.addErrorMessage(populatedField,formulaObject,hideError);},removeErrorMessageIfExists:function(formulaObject,populatedField){var popFieldError=$("[id='formula-errorbox-"+populatedField.attr('id').substring(5)+"']");if(popFieldError.length){populatedField.removeAttr("aria-describedby");popFieldError.remove();populatedField.removeClass("formula-error").removeClass("formula-error-hidden");LF.formula.errorCount--;}},removePopFieldError:function(populatedField){var popFieldId=parseInt($(populatedField).attr('id').substring(5));var formulaObject=_.find(LF.formula.jsonFormulas,function(formulaObj){return formulaObj.populatedField===popFieldId;})
LF.formula.removeErrorMessageIfExists(formulaObject,$(populatedField));},setErrorRemoval:function(fields){$(fields).each(function(){var currField=this;var fieldId=parseInt($(currField).attr('id').substring(5));var formulaObject=_.find(LF.formula.jsonFormulas,function(formulaObj){return formulaObj.populatedField===fieldId;});if(!formulaObject){return;}
$(currField).on('change',function(){LF.formula.removePopFieldError(currField);});});},getPopulatedFields:function(populatedFieldId,excludeReadonly,fieldObject){var populatedFields=fieldObject;if(!populatedFields){var populatedFields=$("[id='Field"+populatedFieldId+"']");if(populatedFields.length===0){populatedFields=$("[id^='Field"+populatedFieldId+"(']");}}
populatedFields=_.filter(populatedFields,function(popField){return($(popField).attr('lookupAlt')!=="true"||$(popField).attr('readonly')!=="readonly")&&(!excludeReadonly||!($(popField).prop('backend-readonly')||$(popField).prop('readonly')));});return $(populatedFields);},getTriggerFields:function(triggerFieldId){var triggerFields=$("select[id='Field"+triggerFieldId+"'],textarea[id='Field"+triggerFieldId+"'],input[id='Field"+triggerFieldId+"'],[id^='Field"+triggerFieldId+"-']");if(triggerFields.length===0){triggerFields=$("[id^='Field"+triggerFieldId+"('][id*=')-']");}
if(triggerFields.length===0){triggerFields=$("[id^='Field"+triggerFieldId+"(']");}
return $(triggerFields);},getTriggerToPopulatedMap:function(triggerFieldIdStrings){var populatedFieldIds={};_.forEach(triggerFieldIdStrings,function(triggerFieldId){if(populatedFieldIds[triggerFieldId]===undefined){populatedFieldIds[triggerFieldId]=[];}
populatedFieldIds[triggerFieldId]=populatedFieldIds[triggerFieldId].concat(LF.formula.getPopulatedIdsWithTriggerId(parseInt(triggerFieldId)));});return populatedFieldIds;},getPopulatedIdsWithTriggerId:function(triggerFieldId){var populatedFieldIds=[];_.forEach(this.jsonFormulas,function(formula){if(_.contains(formula.triggerFields,triggerFieldId)){populatedFieldIds.push(formula.populatedField);}});return populatedFieldIds;},maxDate:9999,minDate:0,cutoffYear:1899,minParseDate:100,maxParseDate:9999};
// Copyright 2012-2016 Laserfiche. All rights reserved

﻿
LF.number={formObject:null,decimalChar:'.',separatorChar:',',defaultPrecision:15,maxDecimalPlaces:30,defaultDecimalPlaces:0,init:function(formObject){if(!jsonForm.calculateFormulas){return;}
this.formObject=formObject;_.forEach(this.formObject.fields,function(fieldObject){if(fieldObject.type==="number"){if(fieldObject.maxDecimalPlaces===null){fieldObject.removeTrailingZeros=true;fieldObject.maxDecimalPlaces=LF.number.maxDecimalPlaces;}
var inputFields=LF.number.findAndSetNumberFieldTriggers(fieldObject);if(inputFields!==null&&LF.number.shouldHandleOnChange(fieldObject)){_.forEach(inputFields,function(inputField){LF.number.handleNumberChange($(inputField),fieldObject,null,true);});}}
else if(fieldObject.type==="currency"){fieldObject.maxDecimalPlaces=2;fieldObject.removeTrailingZeros=true;var inputFields=LF.number.findAndSetCurrencyFieldTriggers(fieldObject);_.forEach(inputFields,function(inputField){LF.number.handleNumberChange($(inputField),fieldObject,null,true);});}});},shouldRemoveTrailingZeros:function(fieldObject){return!!fieldObject.removeTrailingZeros;},hasDecimalPlaces:function(fieldObject){return true;},shouldHandleOnChange:function(fieldObject){return fieldObject.isSeparatorEnabled||this.hasDecimalPlaces(fieldObject);},shouldHandleOnKeypress:function(fieldObject){return this.hasDecimalPlaces(fieldObject);},findAndSetNumberFieldTriggers:function(fieldObject){var field=$("[id^='Field"+fieldObject.fieldId+"(']");if(field.length===0){field=$("[id='Field"+fieldObject.fieldId+"']");}
if(field.length===0){return null;}
if(this.shouldHandleOnKeypress(fieldObject)){_.forEach(field,function(fieldInput){$(fieldInput).keypress(function(e){LF.number.handleNumberKeypress($(fieldInput),fieldObject,e)});});}
if(this.shouldHandleOnChange(fieldObject)){_.forEach(field,function(fieldInput){$(fieldInput).change(function(e,isStartEvent,originRule,alreadyHandled,originalValue){if(!alreadyHandled){LF.number.handleNumberChange($(fieldInput),fieldObject,e,isStartEvent,originRule,null,originalValue);}});$(fieldInput).on('updateNumberFormat',function(e,originalValue){LF.number.handleNumberChange($(fieldInput),fieldObject,null,null,null,null,originalValue);});});}
return field;},findAndSetCurrencyFieldTriggers:function(fieldObject){var field=$("[id='Field"+fieldObject.fieldId+"'],[id^='Field"+fieldObject.fieldId+"(']");if(field.length===0){return null;}
_.forEach(field,function(fieldInput){$(fieldInput).change(function(e,isStartEvent,originRule,alreadyHandled){if(!alreadyHandled){LF.number.handleNumberChange($(fieldInput),fieldObject)}});field.on('updateNumberFormat',function(e,originalValue){LF.number.handleNumberChange(field,fieldObject,null,null,null,null,originalValue);});});return field;},setNumberFieldTriggers:function(field){var fieldId=parseInt(field.attr('id').substring(5));var fieldObject=_.find(this.formObject.fields,function(fieldObj){return fieldObj.fieldId===fieldId;});if(this.shouldHandleOnKeypress(fieldObject)){field.keypress(function(e){LF.number.handleNumberKeypress(field,fieldObject,e)});}
if(this.shouldHandleOnChange(fieldObject)){field.change(function(e,isStartEvent,originRule,alreadyHandled,originalValue){if(!alreadyHandled){LF.number.handleNumberChange(field,fieldObject,e,isStartEvent,originRule,null,originalValue);}});field.on('updateNumberFormat',function(e,originalValue){LF.number.handleNumberChange(field,fieldObject,null,null,null,null,originalValue);});}},setCurrencyFieldTriggers:function(field){var fieldId=parseInt(field.attr('id').substring(5));var fieldObject=_.find(this.formObject.fields,function(fieldObj){return fieldObj.fieldId===fieldId;});if(this.shouldHandleOnChange(fieldObject)){field.change(function(e,isStartEvent,originRule,alreadyHandled){if(!alreadyHandled){LF.number.handleNumberChange(field,fieldObject,e,isStartEvent,originRule);}});field.on('updateNumberFormat',function(addRepeatElement){LF.number.handleNumberChange(field,fieldObject,null,null,null,addRepeatElement)});}},handleNumberKeypress:function(field,fieldObject,e){if(this.shouldHandleOnKeypress(fieldObject)&&e.which!==0){var separatorRegExp=new RegExp(this.separatorChar,'g');var fieldValue=field.val().replace(separatorRegExp,'');if(e.which===46){var numberPieces=fieldValue.split('.');if(fieldObject.maxDecimalPlaces===0||numberPieces.length>=2){e.preventDefault();}}
else if(e.which>=48&&e.which<=57){var valueAfterKeypress=field.val().substring(0,field[0].selectionStart)+String.fromCharCode(e.which)+field.val().substring(field[0].selectionEnd);valueAfterKeypress=valueAfterKeypress.replace(separatorRegExp,'');var newNumberPieces=valueAfterKeypress.split('.');if(newNumberPieces.length===2&&newNumberPieces[1].length>fieldObject.maxDecimalPlaces&&field[0].selectionStart>newNumberPieces[0].length){e.preventDefault();}}
else if(e.which===45){if(typeof field[0].selectionStart===typeof undefined){return;}
var valueStartPosition=this.countLeadingWhitespace(field.val());if((!(field[0].selectionStart<=valueStartPosition)||!(field[0].selectionEnd>=valueStartPosition))||(field.val().charAt(valueStartPosition)==='-'&&!(field[0].selectionEnd>valueStartPosition))){e.preventDefault();}}
else if(e.which!==8&&(e.which!==44||!fieldObject.isSeparatorEnabled)){e.preventDefault();}}},countLeadingWhitespace:function(fieldValueString){for(var i=0;i<fieldValueString.length;i++){if(fieldValueString.charAt(i)!==' '&&fieldValueString.charAt(i)!=='\t'){return i;}}
return fieldValueString.length;},removeThousandsSeparator:function(numberString){var separatorRegExp=new RegExp(LF.number.separatorChar,'g');return numberString.replace(separatorRegExp,'');},removeLeadingZeros:function(numberString){var leadingZerosRegExp=new RegExp("^[0]+",'g');numberString=numberString.replace(leadingZerosRegExp,'');if(numberString.length===0||numberString[0]===LF.number.decimalChar){numberString='0'+numberString;}
return numberString;},removeTrailingZeros:function(numberString){if(numberString.trim().length===0){return numberString;}
if(!this.isNumeric(numberString)){return numberString;}
return math.bignumber(numberString).toFixed();},removeDecimal:function(numberString){if(numberString.toLowerCase().indexOf("e")!=-1){numberString=Number(numberString).toString();if(numberString.toLowerCase().indexOf("e")!=-1){numberString=LF.number.roundNumber(numberString,0);}}
var decimalPos=numberString.indexOf(LF.number.decimalChar);return decimalPos==-1?numberString:numberString.substring(0,decimalPos);},handleNumberChange:function(field,fieldObject,e,isStartEvent,originRule,addRepeatElement,originalValue){var fieldValue=field.val().trim();if(fieldValue.length===0){return;}
fieldValue=this.removeThousandsSeparator(fieldValue);if(!LF.number.isNumeric(fieldValue)||(!this.hasDecimalPlaces(fieldObject)&&fieldValue.charAt(fieldValue.length-1)===LF.number.decimalChar)){return;}
if(!fieldObject.maxDecimalPlaces||fieldObject.maxDecimalPlaces==0){fieldValue=LF.number.removeDecimal(fieldValue);}
else{fieldValue=LF.number.roundNumber(fieldValue,fieldObject.maxDecimalPlaces);}
var newVal=this.removeLeadingZeros(fieldValue);if(this.shouldRemoveTrailingZeros(fieldObject)){fieldValue=this.removeTrailingZeros(fieldValue);}
var numberPieces=fieldValue.split(LF.number.decimalChar);var integerPortion=numberPieces[0];var decimalPortion=numberPieces.length===2?numberPieces[1]:"";if(fieldObject.isSeparatorEnabled){integerPortion=LF.number.addThousandsSeparators(integerPortion);}
var correctedValue=decimalPortion===""?integerPortion:integerPortion+LF.number.decimalChar+decimalPortion;field.val(correctedValue);if(e){e.stopImmediatePropagation();}
if(parseFloat(fieldValue)!==parseFloat(newVal)||(parseFloat(originalValue)!==parseFloat(correctedValue))){field.trigger('change',[isStartEvent,originRule,true,true]);field.trigger('updatevalidation');}},addThousandsSeparators:function(numberString){return numberString.replace(/\B(?=(\d{3})+(?!\d))/g,LF.number.separatorChar);},roundNumber:function(numberString,maxDecimalPlaces){var num=math.bignumber(numberString);return math.bignumber(num.toPrecision(this.defaultPrecision)).toFixed(maxDecimalPlaces);},isNumeric:function(inputValue){return!isNaN(inputValue);},defineEscapeFunction:function(){if(!RegExp.escape){RegExp.escape=function(s){return s.replace(/[-\/\\^$*+?.()|[\]{}]/g,'\\$&');};}},isFormattedNumber:function(inputValue,isSeparatorEnabled){if(!isSeparatorEnabled){return this.isNumeric(inputValue);}
this.defineEscapeFunction();var numberFormat=new RegExp("^-?\\d{1,3}("+RegExp.escape(this.separatorChar)+"\\d{3})*("+RegExp.escape(this.decimalChar)+"\\d+)?$");return isSeparatorEnabled&&numberFormat.test(inputValue);},removeNumberFormatting:function(inputValue){if(this.isNumeric(inputValue)){return inputValue};var separatorRegExp=new RegExp(this.separatorChar,'g');return inputValue.replace(separatorRegExp,'');},defineFormatFunction:function(){if(!String.format){String.format=function(format){var args=Array.prototype.slice.call(arguments,1);return format.replace(/{(\d+)}/g,function(match,number){return typeof args[number]!='undefined'?args[number]:match;});};}},getMinValueErrorString:function(minValue){this.defineFormatFunction();return String.format(LF.formula.errorList.lessThanMin.message,minValue);},getMaxValueErrorString:function(maxValue){this.defineFormatFunction();return String.format(LF.formula.errorList.greaterThanMax.message,maxValue);},};
