{"version":3,"file":"misc.js.map","sources":["Scripts/xml2json.js","Scripts/loader-url.js","Scripts/ui-bootstrap-tpls-0.11.2.js","Scripts/angular-confirm.js","Scripts/ui-grid.js","Scripts/autofill-event.js","Scripts/underscore.js","Scripts/lodash.js","Scripts/moment-with-locales.js","Scripts/moment-timezone-with-data-2010-2020.js","Content/Theme/global/plugins/bootstrap-daterangepicker/daterangepicker.js","Scripts/jquery.signalR-2.1.2.js","Scripts/angular-moment.js","Scripts/spin.js","Scripts/sortable.js","Scripts/toastr.js","Scripts/accounting.js","Scripts/stacktrace.js","Scripts/FileSaver.js","Scripts/jquery.payment.js","Scripts/restangular.js","Content/Theme/global/plugins/angular-minicolors/angular-minicolors.js","Content/Theme/global/plugins/angular-bootstrap-datetimepicker/js/datetimepicker.js","Content/Theme/global/plugins/ngAutocomplete/ngAutocomplete.js","Content/Theme/global/plugins/ng-bs-daterangepicker/ng-bs-daterangepicker.js","Content/Theme/global/plugins/nya-bootstrap-select/nya-bootstrap-select.js","Content/Theme/global/plugins/angular-checklist-model/angular-checklist-model.js","Content/Theme/global/plugins/angular-smooth-scroll/angular-smooth-scroll.js","Content/Theme/global/plugins/angular-file-upload/angular-file-upload.js","Content/Theme/global/plugins/angular-multi-select/isteven-multi-select.js","Content/Theme/global/plugins/angular-loading-bar-master/loading-bar.min.js","Content/Theme/global/plugins/angular-ui-select/select.min.js","Content/Theme/global/plugins/angular-image-cropper/angular-image-cropper.js"],"sourcesContent":["/*\n Copyright 2011-2013 Abdulla Abdurakhmanov\n Original sources are available at https://code.google.com/p/x2js/\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n */\n\nfunction X2JS(config) {\n\t'use strict';\n\t\t\n\tvar VERSION = \"1.1.5\";\n\t\n\tconfig = config || {};\n\tinitConfigDefaults();\n\tinitRequiredPolyfills();\n\t\n\tfunction initConfigDefaults() {\n\t\tif(config.escapeMode === undefined) {\n\t\t\tconfig.escapeMode = true;\n\t\t}\n\t\tconfig.attributePrefix = config.attributePrefix || \"_\";\n\t\tconfig.arrayAccessForm = config.arrayAccessForm || \"none\";\n\t\tconfig.emptyNodeForm = config.emptyNodeForm || \"text\";\n\t\tif(config.enableToStringFunc === undefined) {\n\t\t\tconfig.enableToStringFunc = true; \n\t\t}\n\t\tconfig.arrayAccessFormPaths = config.arrayAccessFormPaths || []; \n\t\tif(config.skipEmptyTextNodesForObj === undefined) {\n\t\t\tconfig.skipEmptyTextNodesForObj = true;\n\t\t}\n\t\tif(config.stripWhitespaces === undefined) {\n\t\t\tconfig.stripWhitespaces = true;\n\t\t}\n\t\tconfig.datetimeAccessFormPaths = config.datetimeAccessFormPaths || [];\n\t}\n\n\tvar DOMNodeTypes = {\n\t\tELEMENT_NODE \t : 1,\n\t\tTEXT_NODE \t : 3,\n\t\tCDATA_SECTION_NODE : 4,\n\t\tCOMMENT_NODE\t : 8,\n\t\tDOCUMENT_NODE \t : 9\n\t};\n\t\n\tfunction initRequiredPolyfills() {\n\t\tfunction pad(number) {\n\t var r = String(number);\n\t if ( r.length === 1 ) {\n\t r = '0' + r;\n\t }\n\t return r;\n\t }\n\t\t// Hello IE8-\n\t\tif(typeof String.prototype.trim !== 'function') {\t\t\t\n\t\t\tString.prototype.trim = function() {\n\t\t\t\treturn this.replace(/^\\s+|^\\n+|(\\s|\\n)+$/g, '');\n\t\t\t}\n\t\t}\n\t\tif(typeof Date.prototype.toISOString !== 'function') {\n\t\t\t// Implementation from http://stackoverflow.com/questions/2573521/how-do-i-output-an-iso-8601-formatted-string-in-javascript\n\t\t\tDate.prototype.toISOString = function() {\n\t\t return this.getUTCFullYear()\n\t\t + '-' + pad( this.getUTCMonth() + 1 )\n\t\t + '-' + pad( this.getUTCDate() )\n\t\t + 'T' + pad( this.getUTCHours() )\n\t\t + ':' + pad( this.getUTCMinutes() )\n\t\t + ':' + pad( this.getUTCSeconds() )\n\t\t + '.' + String( (this.getUTCMilliseconds()/1000).toFixed(3) ).slice( 2, 5 )\n\t\t + 'Z';\n\t\t };\n\t\t}\n\t}\n\t\n\tfunction getNodeLocalName( node ) {\n\t\tvar nodeLocalName = node.localName;\t\t\t\n\t\tif(nodeLocalName == null) // Yeah, this is IE!! \n\t\t\tnodeLocalName = node.baseName;\n\t\tif(nodeLocalName == null || nodeLocalName==\"\") // ==\"\" is IE too\n\t\t\tnodeLocalName = node.nodeName;\n\t\treturn nodeLocalName;\n\t}\n\t\n\tfunction getNodePrefix(node) {\n\t\treturn node.prefix;\n\t}\n\t\t\n\tfunction escapeXmlChars(str) {\n\t\tif(typeof(str) == \"string\")\n\t\t\treturn str.replace(/&/g, '&').replace(//g, '>').replace(/\"/g, '"').replace(/'/g, ''').replace(/\\//g, '/');\n\t\telse\n\t\t\treturn str;\n\t}\n\n\tfunction unescapeXmlChars(str) {\n\t\treturn str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '\"').replace(/'/g, \"'\").replace(///g, '\\/');\n\t}\n\t\n\tfunction toArrayAccessForm(obj, childName, path) {\n\t\tswitch(config.arrayAccessForm) {\n\t\tcase \"property\":\n\t\t\tif(!(obj[childName] instanceof Array))\n\t\t\t\tobj[childName+\"_asArray\"] = [obj[childName]];\n\t\t\telse\n\t\t\t\tobj[childName+\"_asArray\"] = obj[childName];\n\t\t\tbreak;\t\t\n\t\t/*case \"none\":\n\t\t\tbreak;*/\n\t\t}\n\t\t\n\t\tif(!(obj[childName] instanceof Array) && config.arrayAccessFormPaths.length > 0) {\n\t\t\tvar idx = 0;\n\t\t\tfor(; idx < config.arrayAccessFormPaths.length; idx++) {\n\t\t\t\tvar arrayPath = config.arrayAccessFormPaths[idx];\n\t\t\t\tif( typeof arrayPath === \"string\" ) {\n\t\t\t\t\tif(arrayPath == path)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\tif( arrayPath instanceof RegExp) {\n\t\t\t\t\tif(arrayPath.test(path))\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\t\t\t\t\n\t\t\t\telse\n\t\t\t\tif( typeof arrayPath === \"function\") {\n\t\t\t\t\tif(arrayPath(obj, childName, path))\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(idx!=config.arrayAccessFormPaths.length) {\n\t\t\t\tobj[childName] = [obj[childName]];\n\t\t\t}\n\t\t}\n\t}\n\t\n\tfunction fromXmlDateTime(prop) {\n\t\t// Implementation based up on http://stackoverflow.com/questions/8178598/xml-datetime-to-javascript-date-object\n\t\t// Improved to support full spec and optional parts\n\t\tvar bits = prop.split(/[-T:+Z]/g);\n\t\t\n\t\tvar d = new Date(bits[0], bits[1]-1, bits[2]);\t\t\t\n\t\tvar secondBits = bits[5].split(\"\\.\");\n\t\td.setHours(bits[3], bits[4], secondBits[0]);\n\t\tif(secondBits.length>1)\n\t\t\td.setMilliseconds(secondBits[1]);\n\n\t\t// Get supplied time zone offset in minutes\n\t\tif(bits[6] && bits[7]) {\n\t\t\tvar offsetMinutes = bits[6] * 60 + Number(bits[7]);\n\t\t\tvar sign = /\\d\\d-\\d\\d:\\d\\d$/.test(prop)? '-' : '+';\n\n\t\t\t// Apply the sign\n\t\t\toffsetMinutes = 0 + (sign == '-'? -1 * offsetMinutes : offsetMinutes);\n\n\t\t\t// Apply offset and local timezone\n\t\t\td.setMinutes(d.getMinutes() - offsetMinutes - d.getTimezoneOffset())\n\t\t}\n\t\telse\n\t\t\tif(prop.indexOf(\"Z\", prop.length - 1) !== -1) {\n\t\t\t\td = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds(), d.getMilliseconds()));\t\t\t\t\t\n\t\t\t}\n\n\t\t// d is now a local time equivalent to the supplied time\n\t\treturn d;\n\t}\n\t\n\tfunction checkFromXmlDateTimePaths(value, childName, fullPath) {\n\t\tif(config.datetimeAccessFormPaths.length > 0) {\n\t\t\tvar path = fullPath.split(\"\\.#\")[0];\n\t\t\tvar idx = 0;\n\t\t\tfor(; idx < config.datetimeAccessFormPaths.length; idx++) {\n\t\t\t\tvar dtPath = config.datetimeAccessFormPaths[idx];\n\t\t\t\tif( typeof dtPath === \"string\" ) {\n\t\t\t\t\tif(dtPath == path)\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\tif( dtPath instanceof RegExp) {\n\t\t\t\t\tif(dtPath.test(path))\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\t\t\t\t\n\t\t\t\telse\n\t\t\t\tif( typeof dtPath === \"function\") {\n\t\t\t\t\tif(dtPath(obj, childName, path))\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif(idx!=config.datetimeAccessFormPaths.length) {\n\t\t\t\treturn fromXmlDateTime(value);\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn value;\n\t\t}\n\t\telse\n\t\t\treturn value;\n\t}\n\n\tfunction parseDOMChildren( node, path ) {\n\t\tif(node.nodeType == DOMNodeTypes.DOCUMENT_NODE) {\n\t\t\tvar result = new Object;\n\t\t\tvar nodeChildren = node.childNodes;\n\t\t\t// Alternative for firstElementChild which is not supported in some environments\n\t\t\tfor(var cidx=0; cidx 1 && result.__text!=null && config.skipEmptyTextNodesForObj) {\n\t\t\t\tif( (config.stripWhitespaces && result.__text==\"\") || (result.__text.trim()==\"\")) {\n\t\t\t\t\tdelete result.__text;\n\t\t\t\t}\n\t\t\t}\n\t\t\tdelete result.__cnt;\t\t\t\n\t\t\t\n\t\t\tif( config.enableToStringFunc && (result.__text!=null || result.__cdata!=null )) {\n\t\t\t\tresult.toString = function() {\n\t\t\t\t\treturn (this.__text!=null? this.__text:'')+( this.__cdata!=null ? this.__cdata:'');\n\t\t\t\t};\n\t\t\t}\n\t\t\t\n\t\t\treturn result;\n\t\t}\n\t\telse\n\t\tif(node.nodeType == DOMNodeTypes.TEXT_NODE || node.nodeType == DOMNodeTypes.CDATA_SECTION_NODE) {\n\t\t\treturn node.nodeValue;\n\t\t}\t\n\t}\n\t\n\tfunction startTag(jsonObj, element, attrList, closed) {\n\t\tvar resultStr = \"<\"+ ( (jsonObj!=null && jsonObj.__prefix!=null)? (jsonObj.__prefix+\":\"):\"\") + element;\n\t\tif(attrList!=null) {\n\t\t\tfor(var aidx = 0; aidx < attrList.length; aidx++) {\n\t\t\t\tvar attrName = attrList[aidx];\n\t\t\t\tvar attrVal = jsonObj[attrName];\n\t\t\t\tif(config.escapeMode)\n\t\t\t\t\tattrVal=escapeXmlChars(attrVal);\n\t\t\t\tresultStr+=\" \"+attrName.substr(config.attributePrefix.length)+\"='\"+attrVal+\"'\";\n\t\t\t}\n\t\t}\n\t\tif(!closed)\n\t\t\tresultStr+=\">\";\n\t\telse\n\t\t\tresultStr+=\"/>\";\n\t\treturn resultStr;\n\t}\n\t\n\tfunction endTag(jsonObj,elementName) {\n\t\treturn \"\";\n\t}\n\t\n\tfunction endsWith(str, suffix) {\n\t return str.indexOf(suffix, str.length - suffix.length) !== -1;\n\t}\n\t\n\tfunction jsonXmlSpecialElem ( jsonObj, jsonObjField ) {\n\t\tif((config.arrayAccessForm==\"property\" && endsWith(jsonObjField.toString(),(\"_asArray\"))) \n\t\t\t\t|| jsonObjField.toString().indexOf(config.attributePrefix)==0 \n\t\t\t\t|| jsonObjField.toString().indexOf(\"__\")==0\n\t\t\t\t|| (jsonObj[jsonObjField] instanceof Function) )\n\t\t\treturn true;\n\t\telse\n\t\t\treturn false;\n\t}\n\t\n\tfunction jsonXmlElemCount ( jsonObj ) {\n\t\tvar elementsCnt = 0;\n\t\tif(jsonObj instanceof Object ) {\n\t\t\tfor( var it in jsonObj ) {\n\t\t\t\tif(jsonXmlSpecialElem ( jsonObj, it) )\n\t\t\t\t\tcontinue;\t\t\t\n\t\t\t\telementsCnt++;\n\t\t\t}\n\t\t}\n\t\treturn elementsCnt;\n\t}\n\t\n\tfunction parseJSONAttributes ( jsonObj ) {\n\t\tvar attrList = [];\n\t\tif(jsonObj instanceof Object ) {\n\t\t\tfor( var ait in jsonObj ) {\n\t\t\t\tif(ait.toString().indexOf(\"__\")== -1 && ait.toString().indexOf(config.attributePrefix)==0) {\n\t\t\t\t\tattrList.push(ait);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\treturn attrList;\n\t}\n\t\n\tfunction parseJSONTextAttrs ( jsonTxtObj ) {\n\t\tvar result =\"\";\n\t\t\n\t\tif(jsonTxtObj.__cdata!=null) {\t\t\t\t\t\t\t\t\t\t\n\t\t\tresult+=\"\";\t\t\t\t\t\n\t\t}\n\t\t\n\t\tif(jsonTxtObj.__text!=null) {\t\t\t\n\t\t\tif(config.escapeMode)\n\t\t\t\tresult+=escapeXmlChars(jsonTxtObj.__text);\n\t\t\telse\n\t\t\t\tresult+=jsonTxtObj.__text;\n\t\t}\n\t\treturn result;\n\t}\n\t\n\tfunction parseJSONTextObject ( jsonTxtObj ) {\n\t\tvar result =\"\";\n\n\t\tif( jsonTxtObj instanceof Object ) {\n\t\t\tresult+=parseJSONTextAttrs ( jsonTxtObj );\n\t\t}\n\t\telse\n\t\t\tif(jsonTxtObj!=null) {\n\t\t\t\tif(config.escapeMode)\n\t\t\t\t\tresult+=escapeXmlChars(jsonTxtObj);\n\t\t\t\telse\n\t\t\t\t\tresult+=jsonTxtObj;\n\t\t\t}\n\t\t\n\t\treturn result;\n\t}\n\t\n\tfunction parseJSONArray ( jsonArrRoot, jsonArrObj, attrList ) {\n\t\tvar result = \"\"; \n\t\tif(jsonArrRoot.length == 0) {\n\t\t\tresult+=startTag(jsonArrRoot, jsonArrObj, attrList, true);\n\t\t}\n\t\telse {\n\t\t\tfor(var arIdx = 0; arIdx < jsonArrRoot.length; arIdx++) {\n\t\t\t\tresult+=startTag(jsonArrRoot[arIdx], jsonArrObj, parseJSONAttributes(jsonArrRoot[arIdx]), false);\n\t\t\t\tresult+=parseJSONObject(jsonArrRoot[arIdx]);\n\t\t\t\tresult+=endTag(jsonArrRoot[arIdx],jsonArrObj);\t\t\t\t\t\t\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\t\n\tfunction parseJSONObject ( jsonObj ) {\n\t\tvar result = \"\";\t\n\n\t\tvar elementsCnt = jsonXmlElemCount ( jsonObj );\n\t\t\n\t\tif(elementsCnt > 0) {\n\t\t\tfor( var it in jsonObj ) {\n\t\t\t\t\n\t\t\t\tif(jsonXmlSpecialElem ( jsonObj, it) )\n\t\t\t\t\tcontinue;\t\t\t\n\t\t\t\t\n\t\t\t\tvar subObj = jsonObj[it];\t\t\t\t\t\t\n\t\t\t\t\n\t\t\t\tvar attrList = parseJSONAttributes( subObj )\n\t\t\t\t\n\t\t\t\tif(subObj == null || subObj == undefined) {\n\t\t\t\t\tresult+=startTag(subObj, it, attrList, true);\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\tif(subObj instanceof Object) {\n\t\t\t\t\t\n\t\t\t\t\tif(subObj instanceof Array) {\t\t\t\t\t\n\t\t\t\t\t\tresult+=parseJSONArray( subObj, it, attrList );\t\t\t\t\t\n\t\t\t\t\t}\n\t\t\t\t\telse if(subObj instanceof Date) {\n\t\t\t\t\t\tresult+=startTag(subObj, it, attrList, false);\n\t\t\t\t\t\tresult+=subObj.toISOString();\n\t\t\t\t\t\tresult+=endTag(subObj,it);\n\t\t\t\t\t}\n\t\t\t\t\telse {\n\t\t\t\t\t\tvar subObjElementsCnt = jsonXmlElemCount ( subObj );\n\t\t\t\t\t\tif(subObjElementsCnt > 0 || subObj.__text!=null || subObj.__cdata!=null) {\n\t\t\t\t\t\t\tresult+=startTag(subObj, it, attrList, false);\n\t\t\t\t\t\t\tresult+=parseJSONObject(subObj);\n\t\t\t\t\t\t\tresult+=endTag(subObj,it);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tresult+=startTag(subObj, it, attrList, true);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\telse {\n\t\t\t\t\tresult+=startTag(subObj, it, attrList, false);\n\t\t\t\t\tresult+=parseJSONTextObject(subObj);\n\t\t\t\t\tresult+=endTag(subObj,it);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tresult+=parseJSONTextObject(jsonObj);\n\t\t\n\t\treturn result;\n\t}\n\t\n\tthis.parseXmlString = function(xmlDocStr) {\n\t\tvar isIEParser = window.ActiveXObject || \"ActiveXObject\" in window;\n\t\tif (xmlDocStr === undefined) {\n\t\t\treturn null;\n\t\t}\n\t\tvar xmlDoc;\n\t\tif (window.DOMParser) {\n\t\t\tvar parser=new window.DOMParser();\t\t\t\n\t\t\tvar parsererrorNS = null;\n\t\t\t// IE9+ now is here\n\t\t\tif(!isIEParser) {\n\t\t\t\ttry {\n\t\t\t\t\tparsererrorNS = parser.parseFromString(\"INVALID\", \"text/xml\").childNodes[0].namespaceURI;\n\t\t\t\t}\n\t\t\t\tcatch(err) {\t\t\t\t\t\n\t\t\t\t\tparsererrorNS = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\ttry {\n\t\t\t\txmlDoc = parser.parseFromString( xmlDocStr, \"text/xml\" );\n\t\t\t\tif( parsererrorNS!= null && xmlDoc.getElementsByTagNameNS(parsererrorNS, \"parsererror\").length > 0) {\n\t\t\t\t\t//throw new Error('Error parsing XML: '+xmlDocStr);\n\t\t\t\t\txmlDoc = null;\n\t\t\t\t}\n\t\t\t}\n\t\t\tcatch(err) {\n\t\t\t\txmlDoc = null;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\t// IE :(\n\t\t\tif(xmlDocStr.indexOf(\"\") + 2 );\n\t\t\t}\n\t\t\txmlDoc=new ActiveXObject(\"Microsoft.XMLDOM\");\n\t\t\txmlDoc.async=\"false\";\n\t\t\txmlDoc.loadXML(xmlDocStr);\n\t\t}\n\t\treturn xmlDoc;\n\t};\n\t\n\tthis.asArray = function(prop) {\n\t\tif(prop instanceof Array)\n\t\t\treturn prop;\n\t\telse\n\t\t\treturn [prop];\n\t};\n\t\n\tthis.toXmlDateTime = function(dt) {\n\t\tif(dt instanceof Date)\n\t\t\treturn dt.toISOString();\n\t\telse\n\t\tif(typeof(dt) === 'number' )\n\t\t\treturn new Date(dt).toISOString();\n\t\telse\t\n\t\t\treturn null;\n\t};\n\t\n\tthis.asDateTime = function(prop) {\n\t\tif(typeof(prop) == \"string\") {\n\t\t\treturn fromXmlDateTime(prop);\n\t\t}\n\t\telse\n\t\t\treturn prop;\n\t};\n\n\tthis.xml2json = function (xmlDoc) {\n\t\treturn parseDOMChildren ( xmlDoc );\n\t};\n\t\n\tthis.xml_str2json = function (xmlDocStr) {\n\t\tvar xmlDoc = this.parseXmlString(xmlDocStr);\n\t\tif(xmlDoc!=null)\n\t\t\treturn this.xml2json(xmlDoc);\n\t\telse\n\t\t\treturn null;\n\t};\n\n\tthis.json2xml_str = function (jsonObj) {\n\t\treturn parseJSONObject ( jsonObj );\n\t};\n\n\tthis.json2xml = function (jsonObj) {\n\t\tvar xmlDocStr = this.json2xml_str (jsonObj);\n\t\treturn this.parseXmlString(xmlDocStr);\n\t};\n\t\n\tthis.getVersion = function () {\n\t\treturn VERSION;\n\t};\n\t\n}\n","angular.module('pascalprecht.translate')\n/**\n * @ngdoc object\n * @name pascalprecht.translate.$translateUrlLoader\n * @requires $q\n * @requires $http\n *\n * @description\n * Creates a loading function for a typical dynamic url pattern:\n * \"locale.php?lang=en_US\", \"locale.php?lang=de_DE\", etc. Prefixing the specified\n * url, the current requested, language id will be applied with \"?lang={key}\".\n * Using this service, the response of these urls must be an object of\n * key-value pairs.\n *\n * @param {object} options Options object, which gets the url and key.\n */\n.factory('$translateUrlLoader', ['$q', '$http', function ($q, $http) {\n\n return function (options) {\n\n if (!options || !options.url) {\n throw new Error('Couldn\\'t use urlLoader since no url is given!');\n }\n\n var deferred = $q.defer();\n\n $http({\n url: options.url,\n params: { lang: options.key },\n method: 'GET'\n }).success(function (data) {\n deferred.resolve(data);\n }).error(function (data) {\n deferred.reject(options.key);\n });\n\n return deferred.promise;\n };\n}]);\n","/*\n * angular-ui-bootstrap\n * http://angular-ui.github.io/bootstrap/\n\n * Version: 0.11.2 - 2014-09-26\n * License: MIT\n */\nangular.module(\"ui.bootstrap\", [\"ui.bootstrap.tpls\", \"ui.bootstrap.transition\",\"ui.bootstrap.collapse\",\"ui.bootstrap.accordion\",\"ui.bootstrap.alert\",\"ui.bootstrap.bindHtml\",\"ui.bootstrap.buttons\",\"ui.bootstrap.carousel\",\"ui.bootstrap.dateparser\",\"ui.bootstrap.position\",\"ui.bootstrap.datepicker\",\"ui.bootstrap.dropdown\",\"ui.bootstrap.modal\",\"ui.bootstrap.pagination\",\"ui.bootstrap.tooltip\",\"ui.bootstrap.popover\",\"ui.bootstrap.progressbar\",\"ui.bootstrap.rating\",\"ui.bootstrap.tabs\",\"ui.bootstrap.timepicker\",\"ui.bootstrap.typeahead\"]);\nangular.module(\"ui.bootstrap.tpls\", [\"template/accordion/accordion-group.html\",\"template/accordion/accordion.html\",\"template/alert/alert.html\",\"template/carousel/carousel.html\",\"template/carousel/slide.html\",\"template/datepicker/datepicker.html\",\"template/datepicker/day.html\",\"template/datepicker/month.html\",\"template/datepicker/popup.html\",\"template/datepicker/year.html\",\"template/modal/backdrop.html\",\"template/modal/window.html\",\"template/pagination/pager.html\",\"template/pagination/pagination.html\",\"template/tooltip/tooltip-html-unsafe-popup.html\",\"template/tooltip/tooltip-popup.html\",\"template/popover/popover.html\",\"template/progressbar/bar.html\",\"template/progressbar/progress.html\",\"template/progressbar/progressbar.html\",\"template/rating/rating.html\",\"template/tabs/tab.html\",\"template/tabs/tabset.html\",\"template/timepicker/timepicker.html\",\"template/typeahead/typeahead-match.html\",\"template/typeahead/typeahead-popup.html\"]);\nangular.module('ui.bootstrap.transition', [])\n\n/**\n * $transition service provides a consistent interface to trigger CSS 3 transitions and to be informed when they complete.\n * @param {DOMElement} element The DOMElement that will be animated.\n * @param {string|object|function} trigger The thing that will cause the transition to start:\n * - As a string, it represents the css class to be added to the element.\n * - As an object, it represents a hash of style attributes to be applied to the element.\n * - As a function, it represents a function to be called that will cause the transition to occur.\n * @return {Promise} A promise that is resolved when the transition finishes.\n */\n.factory('$transition', ['$q', '$timeout', '$rootScope', function($q, $timeout, $rootScope) {\n\n var $transition = function(element, trigger, options) {\n options = options || {};\n var deferred = $q.defer();\n var endEventName = $transition[options.animation ? 'animationEndEventName' : 'transitionEndEventName'];\n\n var transitionEndHandler = function(event) {\n $rootScope.$apply(function() {\n element.unbind(endEventName, transitionEndHandler);\n deferred.resolve(element);\n });\n };\n\n if (endEventName) {\n element.bind(endEventName, transitionEndHandler);\n }\n\n // Wrap in a timeout to allow the browser time to update the DOM before the transition is to occur\n $timeout(function() {\n if ( angular.isString(trigger) ) {\n element.addClass(trigger);\n } else if ( angular.isFunction(trigger) ) {\n trigger(element);\n } else if ( angular.isObject(trigger) ) {\n element.css(trigger);\n }\n //If browser does not support transitions, instantly resolve\n if ( !endEventName ) {\n deferred.resolve(element);\n }\n });\n\n // Add our custom cancel function to the promise that is returned\n // We can call this if we are about to run a new transition, which we know will prevent this transition from ending,\n // i.e. it will therefore never raise a transitionEnd event for that transition\n deferred.promise.cancel = function() {\n if ( endEventName ) {\n element.unbind(endEventName, transitionEndHandler);\n }\n deferred.reject('Transition cancelled');\n };\n\n return deferred.promise;\n };\n\n // Work out the name of the transitionEnd event\n var transElement = document.createElement('trans');\n var transitionEndEventNames = {\n 'WebkitTransition': 'webkitTransitionEnd',\n 'MozTransition': 'transitionend',\n 'OTransition': 'oTransitionEnd',\n 'transition': 'transitionend'\n };\n var animationEndEventNames = {\n 'WebkitTransition': 'webkitAnimationEnd',\n 'MozTransition': 'animationend',\n 'OTransition': 'oAnimationEnd',\n 'transition': 'animationend'\n };\n function findEndEventName(endEventNames) {\n for (var name in endEventNames){\n if (transElement.style[name] !== undefined) {\n return endEventNames[name];\n }\n }\n }\n $transition.transitionEndEventName = findEndEventName(transitionEndEventNames);\n $transition.animationEndEventName = findEndEventName(animationEndEventNames);\n return $transition;\n}]);\n\nangular.module('ui.bootstrap.collapse', ['ui.bootstrap.transition'])\n\n .directive('collapse', ['$transition', function ($transition) {\n\n return {\n link: function (scope, element, attrs) {\n\n var initialAnimSkip = true;\n var currentTransition;\n\n function doTransition(change) {\n var newTransition = $transition(element, change);\n if (currentTransition) {\n currentTransition.cancel();\n }\n currentTransition = newTransition;\n newTransition.then(newTransitionDone, newTransitionDone);\n return newTransition;\n\n function newTransitionDone() {\n // Make sure it's this transition, otherwise, leave it alone.\n if (currentTransition === newTransition) {\n currentTransition = undefined;\n }\n }\n }\n\n function expand() {\n if (initialAnimSkip) {\n initialAnimSkip = false;\n expandDone();\n } else {\n element.removeClass('collapse').addClass('collapsing');\n doTransition({ height: element[0].scrollHeight + 'px' }).then(expandDone);\n }\n }\n\n function expandDone() {\n element.removeClass('collapsing');\n element.addClass('collapse in');\n element.css({height: 'auto'});\n }\n\n function collapse() {\n if (initialAnimSkip) {\n initialAnimSkip = false;\n collapseDone();\n element.css({height: 0});\n } else {\n // CSS transitions don't work with height: auto, so we have to manually change the height to a specific value\n element.css({ height: element[0].scrollHeight + 'px' });\n //trigger reflow so a browser realizes that height was updated from auto to a specific value\n var x = element[0].offsetWidth;\n\n element.removeClass('collapse in').addClass('collapsing');\n\n doTransition({ height: 0 }).then(collapseDone);\n }\n }\n\n function collapseDone() {\n element.removeClass('collapsing');\n element.addClass('collapse');\n }\n\n scope.$watch(attrs.collapse, function (shouldCollapse) {\n if (shouldCollapse) {\n collapse();\n } else {\n expand();\n }\n });\n }\n };\n }]);\n\nangular.module('ui.bootstrap.accordion', ['ui.bootstrap.collapse'])\n\n.constant('accordionConfig', {\n closeOthers: true\n})\n\n.controller('AccordionController', ['$scope', '$attrs', 'accordionConfig', function ($scope, $attrs, accordionConfig) {\n\n // This array keeps track of the accordion groups\n this.groups = [];\n\n // Ensure that all the groups in this accordion are closed, unless close-others explicitly says not to\n this.closeOthers = function(openGroup) {\n var closeOthers = angular.isDefined($attrs.closeOthers) ? $scope.$eval($attrs.closeOthers) : accordionConfig.closeOthers;\n if ( closeOthers ) {\n angular.forEach(this.groups, function (group) {\n if ( group !== openGroup ) {\n group.isOpen = false;\n }\n });\n }\n };\n\n // This is called from the accordion-group directive to add itself to the accordion\n this.addGroup = function(groupScope) {\n var that = this;\n this.groups.push(groupScope);\n\n groupScope.$on('$destroy', function (event) {\n that.removeGroup(groupScope);\n });\n };\n\n // This is called from the accordion-group directive when to remove itself\n this.removeGroup = function(group) {\n var index = this.groups.indexOf(group);\n if ( index !== -1 ) {\n this.groups.splice(index, 1);\n }\n };\n\n}])\n\n// The accordion directive simply sets up the directive controller\n// and adds an accordion CSS class to itself element.\n.directive('accordion', function () {\n return {\n restrict:'EA',\n controller:'AccordionController',\n transclude: true,\n replace: false,\n templateUrl: 'template/accordion/accordion.html'\n };\n})\n\n// The accordion-group directive indicates a block of html that will expand and collapse in an accordion\n.directive('accordionGroup', function() {\n return {\n require:'^accordion', // We need this directive to be inside an accordion\n restrict:'EA',\n transclude:true, // It transcludes the contents of the directive into the template\n replace: true, // The element containing the directive will be replaced with the template\n templateUrl:'template/accordion/accordion-group.html',\n scope: {\n heading: '@', // Interpolate the heading attribute onto this scope\n isOpen: '=?',\n isDisabled: '=?'\n },\n controller: function() {\n this.setHeading = function(element) {\n this.heading = element;\n };\n },\n link: function(scope, element, attrs, accordionCtrl) {\n accordionCtrl.addGroup(scope);\n\n scope.$watch('isOpen', function(value) {\n if ( value ) {\n accordionCtrl.closeOthers(scope);\n }\n });\n\n scope.toggleOpen = function() {\n if ( !scope.isDisabled ) {\n scope.isOpen = !scope.isOpen;\n }\n };\n }\n };\n})\n\n// Use accordion-heading below an accordion-group to provide a heading containing HTML\n// \n// Heading containing HTML - \n// \n.directive('accordionHeading', function() {\n return {\n restrict: 'EA',\n transclude: true, // Grab the contents to be used as the heading\n template: '', // In effect remove this element!\n replace: true,\n require: '^accordionGroup',\n link: function(scope, element, attr, accordionGroupCtrl, transclude) {\n // Pass the heading to the accordion-group controller\n // so that it can be transcluded into the right place in the template\n // [The second parameter to transclude causes the elements to be cloned so that they work in ng-repeat]\n accordionGroupCtrl.setHeading(transclude(scope, function() {}));\n }\n };\n})\n\n// Use in the accordion-group template to indicate where you want the heading to be transcluded\n// You must provide the property on the accordion-group controller that will hold the transcluded element\n//
\n// \n// ...\n//
\n.directive('accordionTransclude', function() {\n return {\n require: '^accordionGroup',\n link: function(scope, element, attr, controller) {\n scope.$watch(function() { return controller[attr.accordionTransclude]; }, function(heading) {\n if ( heading ) {\n element.html('');\n element.append(heading);\n }\n });\n }\n };\n});\n\nangular.module('ui.bootstrap.alert', [])\n\n.controller('AlertController', ['$scope', '$attrs', function ($scope, $attrs) {\n $scope.closeable = 'close' in $attrs;\n}])\n\n.directive('alert', function () {\n return {\n restrict:'EA',\n controller:'AlertController',\n templateUrl:'template/alert/alert.html',\n transclude:true,\n replace:true,\n scope: {\n type: '@',\n close: '&'\n }\n };\n});\n\nangular.module('ui.bootstrap.bindHtml', [])\n\n .directive('bindHtmlUnsafe', function () {\n return function (scope, element, attr) {\n element.addClass('ng-binding').data('$binding', attr.bindHtmlUnsafe);\n scope.$watch(attr.bindHtmlUnsafe, function bindHtmlUnsafeWatchAction(value) {\n element.html(value || '');\n });\n };\n });\nangular.module('ui.bootstrap.buttons', [])\n\n.constant('buttonConfig', {\n activeClass: 'active',\n toggleEvent: 'click'\n})\n\n.controller('ButtonsController', ['buttonConfig', function(buttonConfig) {\n this.activeClass = buttonConfig.activeClass || 'active';\n this.toggleEvent = buttonConfig.toggleEvent || 'click';\n}])\n\n.directive('btnRadio', function () {\n return {\n require: ['btnRadio', 'ngModel'],\n controller: 'ButtonsController',\n link: function (scope, element, attrs, ctrls) {\n var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];\n\n //model -> UI\n ngModelCtrl.$render = function () {\n element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, scope.$eval(attrs.btnRadio)));\n };\n\n //ui->model\n element.bind(buttonsCtrl.toggleEvent, function () {\n var isActive = element.hasClass(buttonsCtrl.activeClass);\n\n if (!isActive || angular.isDefined(attrs.uncheckable)) {\n scope.$apply(function () {\n ngModelCtrl.$setViewValue(isActive ? null : scope.$eval(attrs.btnRadio));\n ngModelCtrl.$render();\n });\n }\n });\n }\n };\n})\n\n.directive('btnCheckbox', function () {\n return {\n require: ['btnCheckbox', 'ngModel'],\n controller: 'ButtonsController',\n link: function (scope, element, attrs, ctrls) {\n var buttonsCtrl = ctrls[0], ngModelCtrl = ctrls[1];\n\n function getTrueValue() {\n return getCheckboxValue(attrs.btnCheckboxTrue, true);\n }\n\n function getFalseValue() {\n return getCheckboxValue(attrs.btnCheckboxFalse, false);\n }\n\n function getCheckboxValue(attributeValue, defaultValue) {\n var val = scope.$eval(attributeValue);\n return angular.isDefined(val) ? val : defaultValue;\n }\n\n //model -> UI\n ngModelCtrl.$render = function () {\n element.toggleClass(buttonsCtrl.activeClass, angular.equals(ngModelCtrl.$modelValue, getTrueValue()));\n };\n\n //ui->model\n element.bind(buttonsCtrl.toggleEvent, function () {\n scope.$apply(function () {\n ngModelCtrl.$setViewValue(element.hasClass(buttonsCtrl.activeClass) ? getFalseValue() : getTrueValue());\n ngModelCtrl.$render();\n });\n });\n }\n };\n});\n\n/**\n* @ngdoc overview\n* @name ui.bootstrap.carousel\n*\n* @description\n* AngularJS version of an image carousel.\n*\n*/\nangular.module('ui.bootstrap.carousel', ['ui.bootstrap.transition'])\n.controller('CarouselController', ['$scope', '$timeout', '$transition', function ($scope, $timeout, $transition) {\n var self = this,\n slides = self.slides = $scope.slides = [],\n currentIndex = -1,\n currentTimeout, isPlaying;\n self.currentSlide = null;\n\n var destroyed = false;\n /* direction: \"prev\" or \"next\" */\n self.select = $scope.select = function(nextSlide, direction) {\n var nextIndex = slides.indexOf(nextSlide);\n //Decide direction if it's not given\n if (direction === undefined) {\n direction = nextIndex > currentIndex ? 'next' : 'prev';\n }\n if (nextSlide && nextSlide !== self.currentSlide) {\n if ($scope.$currentTransition) {\n $scope.$currentTransition.cancel();\n //Timeout so ng-class in template has time to fix classes for finished slide\n $timeout(goNext);\n } else {\n goNext();\n }\n }\n function goNext() {\n // Scope has been destroyed, stop here.\n if (destroyed) { return; }\n //If we have a slide to transition from and we have a transition type and we're allowed, go\n if (self.currentSlide && angular.isString(direction) && !$scope.noTransition && nextSlide.$element) {\n //We shouldn't do class manip in here, but it's the same weird thing bootstrap does. need to fix sometime\n nextSlide.$element.addClass(direction);\n var reflow = nextSlide.$element[0].offsetWidth; //force reflow\n\n //Set all other slides to stop doing their stuff for the new transition\n angular.forEach(slides, function(slide) {\n angular.extend(slide, {direction: '', entering: false, leaving: false, active: false});\n });\n angular.extend(nextSlide, {direction: direction, active: true, entering: true});\n angular.extend(self.currentSlide||{}, {direction: direction, leaving: true});\n\n $scope.$currentTransition = $transition(nextSlide.$element, {});\n //We have to create new pointers inside a closure since next & current will change\n (function(next,current) {\n $scope.$currentTransition.then(\n function(){ transitionDone(next, current); },\n function(){ transitionDone(next, current); }\n );\n }(nextSlide, self.currentSlide));\n } else {\n transitionDone(nextSlide, self.currentSlide);\n }\n self.currentSlide = nextSlide;\n currentIndex = nextIndex;\n //every time you change slides, reset the timer\n restartTimer();\n }\n function transitionDone(next, current) {\n angular.extend(next, {direction: '', active: true, leaving: false, entering: false});\n angular.extend(current||{}, {direction: '', active: false, leaving: false, entering: false});\n $scope.$currentTransition = null;\n }\n };\n $scope.$on('$destroy', function () {\n destroyed = true;\n });\n\n /* Allow outside people to call indexOf on slides array */\n self.indexOfSlide = function(slide) {\n return slides.indexOf(slide);\n };\n\n $scope.next = function() {\n var newIndex = (currentIndex + 1) % slides.length;\n\n //Prevent this user-triggered transition from occurring if there is already one in progress\n if (!$scope.$currentTransition) {\n return self.select(slides[newIndex], 'next');\n }\n };\n\n $scope.prev = function() {\n var newIndex = currentIndex - 1 < 0 ? slides.length - 1 : currentIndex - 1;\n\n //Prevent this user-triggered transition from occurring if there is already one in progress\n if (!$scope.$currentTransition) {\n return self.select(slides[newIndex], 'prev');\n }\n };\n\n $scope.isActive = function(slide) {\n return self.currentSlide === slide;\n };\n\n $scope.$watch('interval', restartTimer);\n $scope.$on('$destroy', resetTimer);\n\n function restartTimer() {\n resetTimer();\n var interval = +$scope.interval;\n if (!isNaN(interval) && interval>=0) {\n currentTimeout = $timeout(timerFn, interval);\n }\n }\n\n function resetTimer() {\n if (currentTimeout) {\n $timeout.cancel(currentTimeout);\n currentTimeout = null;\n }\n }\n\n function timerFn() {\n if (isPlaying) {\n $scope.next();\n restartTimer();\n } else {\n $scope.pause();\n }\n }\n\n $scope.play = function() {\n if (!isPlaying) {\n isPlaying = true;\n restartTimer();\n }\n };\n $scope.pause = function() {\n if (!$scope.noPause) {\n isPlaying = false;\n resetTimer();\n }\n };\n\n self.addSlide = function(slide, element) {\n slide.$element = element;\n slides.push(slide);\n //if this is the first slide or the slide is set to active, select it\n if(slides.length === 1 || slide.active) {\n self.select(slides[slides.length-1]);\n if (slides.length == 1) {\n $scope.play();\n }\n } else {\n slide.active = false;\n }\n };\n\n self.removeSlide = function(slide) {\n //get the index of the slide inside the carousel\n var index = slides.indexOf(slide);\n slides.splice(index, 1);\n if (slides.length > 0 && slide.active) {\n if (index >= slides.length) {\n self.select(slides[index-1]);\n } else {\n self.select(slides[index]);\n }\n } else if (currentIndex > index) {\n currentIndex--;\n }\n };\n\n}])\n\n/**\n * @ngdoc directive\n * @name ui.bootstrap.carousel.directive:carousel\n * @restrict EA\n *\n * @description\n * Carousel is the outer container for a set of image 'slides' to showcase.\n *\n * @param {number=} interval The time, in milliseconds, that it will take the carousel to go to the next slide.\n * @param {boolean=} noTransition Whether to disable transitions on the carousel.\n * @param {boolean=} noPause Whether to disable pausing on the carousel (by default, the carousel interval pauses on hover).\n *\n * @example\n\n \n \n \n \n
\n

Beautiful!

\n
\n
\n \n \n
\n

D'aww!

\n
\n
\n
\n
\n \n .carousel-indicators {\n top: auto;\n bottom: 15px;\n }\n \n
\n */\n.directive('carousel', [function() {\n return {\n restrict: 'EA',\n transclude: true,\n replace: true,\n controller: 'CarouselController',\n require: 'carousel',\n templateUrl: 'template/carousel/carousel.html',\n scope: {\n interval: '=',\n noTransition: '=',\n noPause: '='\n }\n };\n}])\n\n/**\n * @ngdoc directive\n * @name ui.bootstrap.carousel.directive:slide\n * @restrict EA\n *\n * @description\n * Creates a slide inside a {@link ui.bootstrap.carousel.directive:carousel carousel}. Must be placed as a child of a carousel element.\n *\n * @param {boolean=} active Model binding, whether or not this slide is currently active.\n *\n * @example\n\n \n
\n \n \n \n
\n

Slide {{$index}}

\n

{{slide.text}}

\n
\n
\n
\n Interval, in milliseconds: \n
Enter a negative number to stop the interval.\n
\n
\n \nfunction CarouselDemoCtrl($scope) {\n $scope.myInterval = 5000;\n}\n \n \n .carousel-indicators {\n top: auto;\n bottom: 15px;\n }\n \n
\n*/\n\n.directive('slide', function() {\n return {\n require: '^carousel',\n restrict: 'EA',\n transclude: true,\n replace: true,\n templateUrl: 'template/carousel/slide.html',\n scope: {\n active: '=?'\n },\n link: function (scope, element, attrs, carouselCtrl) {\n carouselCtrl.addSlide(scope, element);\n //when the scope is destroyed then remove the slide from the current slides array\n scope.$on('$destroy', function() {\n carouselCtrl.removeSlide(scope);\n });\n\n scope.$watch('active', function(active) {\n if (active) {\n carouselCtrl.select(scope);\n }\n });\n }\n };\n});\n\nangular.module('ui.bootstrap.dateparser', [])\n\n.service('dateParser', ['$locale', 'orderByFilter', function($locale, orderByFilter) {\n\n this.parsers = {};\n\n var formatCodeToRegex = {\n 'yyyy': {\n regex: '\\\\d{4}',\n apply: function(value) { this.year = +value; }\n },\n 'yy': {\n regex: '\\\\d{2}',\n apply: function(value) { this.year = +value + 2000; }\n },\n 'y': {\n regex: '\\\\d{1,4}',\n apply: function(value) { this.year = +value; }\n },\n 'MMMM': {\n regex: $locale.DATETIME_FORMATS.MONTH.join('|'),\n apply: function(value) { this.month = $locale.DATETIME_FORMATS.MONTH.indexOf(value); }\n },\n 'MMM': {\n regex: $locale.DATETIME_FORMATS.SHORTMONTH.join('|'),\n apply: function(value) { this.month = $locale.DATETIME_FORMATS.SHORTMONTH.indexOf(value); }\n },\n 'MM': {\n regex: '0[1-9]|1[0-2]',\n apply: function(value) { this.month = value - 1; }\n },\n 'M': {\n regex: '[1-9]|1[0-2]',\n apply: function(value) { this.month = value - 1; }\n },\n 'dd': {\n regex: '[0-2][0-9]{1}|3[0-1]{1}',\n apply: function(value) { this.date = +value; }\n },\n 'd': {\n regex: '[1-2]?[0-9]{1}|3[0-1]{1}',\n apply: function(value) { this.date = +value; }\n },\n 'EEEE': {\n regex: $locale.DATETIME_FORMATS.DAY.join('|')\n },\n 'EEE': {\n regex: $locale.DATETIME_FORMATS.SHORTDAY.join('|')\n }\n };\n\n function createParser(format) {\n var map = [], regex = format.split('');\n\n angular.forEach(formatCodeToRegex, function(data, code) {\n var index = format.indexOf(code);\n\n if (index > -1) {\n format = format.split('');\n\n regex[index] = '(' + data.regex + ')';\n format[index] = '$'; // Custom symbol to define consumed part of format\n for (var i = index + 1, n = index + code.length; i < n; i++) {\n regex[i] = '';\n format[i] = '$';\n }\n format = format.join('');\n\n map.push({ index: index, apply: data.apply });\n }\n });\n\n return {\n regex: new RegExp('^' + regex.join('') + '$'),\n map: orderByFilter(map, 'index')\n };\n }\n\n this.parse = function(input, format) {\n if ( !angular.isString(input) || !format ) {\n return input;\n }\n\n format = $locale.DATETIME_FORMATS[format] || format;\n\n if ( !this.parsers[format] ) {\n this.parsers[format] = createParser(format);\n }\n\n var parser = this.parsers[format],\n regex = parser.regex,\n map = parser.map,\n results = input.match(regex);\n\n if ( results && results.length ) {\n var fields = { year: 1900, month: 0, date: 1, hours: 0 }, dt;\n\n for( var i = 1, n = results.length; i < n; i++ ) {\n var mapper = map[i-1];\n if ( mapper.apply ) {\n mapper.apply.call(fields, results[i]);\n }\n }\n\n if ( isValid(fields.year, fields.month, fields.date) ) {\n dt = new Date( fields.year, fields.month, fields.date, fields.hours);\n }\n\n return dt;\n }\n };\n\n // Check if date is valid for specific month (and year for February).\n // Month: 0 = Jan, 1 = Feb, etc\n function isValid(year, month, date) {\n if ( month === 1 && date > 28) {\n return date === 29 && ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0);\n }\n\n if ( month === 3 || month === 5 || month === 8 || month === 10) {\n return date < 31;\n }\n\n return true;\n }\n}]);\n\nangular.module('ui.bootstrap.position', [])\n\n/**\n * A set of utility methods that can be use to retrieve position of DOM elements.\n * It is meant to be used where we need to absolute-position DOM elements in\n * relation to other, existing elements (this is the case for tooltips, popovers,\n * typeahead suggestions etc.).\n */\n .factory('$position', ['$document', '$window', function ($document, $window) {\n\n function getStyle(el, cssprop) {\n if (el.currentStyle) { //IE\n return el.currentStyle[cssprop];\n } else if ($window.getComputedStyle) {\n return $window.getComputedStyle(el)[cssprop];\n }\n // finally try and get inline style\n return el.style[cssprop];\n }\n\n /**\n * Checks if a given element is statically positioned\n * @param element - raw DOM element\n */\n function isStaticPositioned(element) {\n return (getStyle(element, 'position') || 'static' ) === 'static';\n }\n\n /**\n * returns the closest, non-statically positioned parentOffset of a given element\n * @param element\n */\n var parentOffsetEl = function (element) {\n var docDomEl = $document[0];\n var offsetParent = element.offsetParent || docDomEl;\n while (offsetParent && offsetParent !== docDomEl && isStaticPositioned(offsetParent) ) {\n offsetParent = offsetParent.offsetParent;\n }\n return offsetParent || docDomEl;\n };\n\n return {\n /**\n * Provides read-only equivalent of jQuery's position function:\n * http://api.jquery.com/position/\n */\n position: function (element) {\n var elBCR = this.offset(element);\n var offsetParentBCR = { top: 0, left: 0 };\n var offsetParentEl = parentOffsetEl(element[0]);\n if (offsetParentEl != $document[0]) {\n offsetParentBCR = this.offset(angular.element(offsetParentEl));\n offsetParentBCR.top += offsetParentEl.clientTop - offsetParentEl.scrollTop;\n offsetParentBCR.left += offsetParentEl.clientLeft - offsetParentEl.scrollLeft;\n }\n\n var boundingClientRect = element[0].getBoundingClientRect();\n return {\n width: boundingClientRect.width || element.prop('offsetWidth'),\n height: boundingClientRect.height || element.prop('offsetHeight'),\n top: elBCR.top - offsetParentBCR.top,\n left: elBCR.left - offsetParentBCR.left\n };\n },\n\n /**\n * Provides read-only equivalent of jQuery's offset function:\n * http://api.jquery.com/offset/\n */\n offset: function (element) {\n var boundingClientRect = element[0].getBoundingClientRect();\n return {\n width: boundingClientRect.width || element.prop('offsetWidth'),\n height: boundingClientRect.height || element.prop('offsetHeight'),\n top: boundingClientRect.top + ($window.pageYOffset || $document[0].documentElement.scrollTop),\n left: boundingClientRect.left + ($window.pageXOffset || $document[0].documentElement.scrollLeft)\n };\n },\n\n /**\n * Provides coordinates for the targetEl in relation to hostEl\n */\n positionElements: function (hostEl, targetEl, positionStr, appendToBody) {\n\n var positionStrParts = positionStr.split('-');\n var pos0 = positionStrParts[0], pos1 = positionStrParts[1] || 'center';\n\n var hostElPos,\n targetElWidth,\n targetElHeight,\n targetElPos;\n\n hostElPos = appendToBody ? this.offset(hostEl) : this.position(hostEl);\n\n targetElWidth = targetEl.prop('offsetWidth');\n targetElHeight = targetEl.prop('offsetHeight');\n\n var shiftWidth = {\n center: function () {\n return hostElPos.left + hostElPos.width / 2 - targetElWidth / 2;\n },\n left: function () {\n return hostElPos.left;\n },\n right: function () {\n return hostElPos.left + hostElPos.width;\n }\n };\n\n var shiftHeight = {\n center: function () {\n return hostElPos.top + hostElPos.height / 2 - targetElHeight / 2;\n },\n top: function () {\n return hostElPos.top;\n },\n bottom: function () {\n return hostElPos.top + hostElPos.height;\n }\n };\n\n switch (pos0) {\n case 'right':\n targetElPos = {\n top: shiftHeight[pos1](),\n left: shiftWidth[pos0]()\n };\n break;\n case 'left':\n targetElPos = {\n top: shiftHeight[pos1](),\n left: hostElPos.left - targetElWidth\n };\n break;\n case 'bottom':\n targetElPos = {\n top: shiftHeight[pos0](),\n left: shiftWidth[pos1]()\n };\n break;\n default:\n targetElPos = {\n top: hostElPos.top - targetElHeight,\n left: shiftWidth[pos1]()\n };\n break;\n }\n\n return targetElPos;\n }\n };\n }]);\n\nangular.module('ui.bootstrap.datepicker', ['ui.bootstrap.dateparser', 'ui.bootstrap.position'])\n\n.constant('datepickerConfig', {\n formatDay: 'dd',\n formatMonth: 'MMMM',\n formatYear: 'yyyy',\n formatDayHeader: 'EEE',\n formatDayTitle: 'MMMM yyyy',\n formatMonthTitle: 'yyyy',\n datepickerMode: 'day',\n minMode: 'day',\n maxMode: 'year',\n showWeeks: true,\n startingDay: 0,\n yearRange: 20,\n minDate: null,\n maxDate: null\n})\n\n.controller('DatepickerController', ['$scope', '$attrs', '$parse', '$interpolate', '$timeout', '$log', 'dateFilter', 'datepickerConfig', function($scope, $attrs, $parse, $interpolate, $timeout, $log, dateFilter, datepickerConfig) {\n var self = this,\n ngModelCtrl = { $setViewValue: angular.noop }; // nullModelCtrl;\n\n // Modes chain\n this.modes = ['day', 'month', 'year'];\n\n // Configuration attributes\n angular.forEach(['formatDay', 'formatMonth', 'formatYear', 'formatDayHeader', 'formatDayTitle', 'formatMonthTitle',\n 'minMode', 'maxMode', 'showWeeks', 'startingDay', 'yearRange'], function( key, index ) {\n self[key] = angular.isDefined($attrs[key]) ? (index < 8 ? $interpolate($attrs[key])($scope.$parent) : $scope.$parent.$eval($attrs[key])) : datepickerConfig[key];\n });\n\n // Watchable date attributes\n angular.forEach(['minDate', 'maxDate'], function( key ) {\n if ( $attrs[key] ) {\n $scope.$parent.$watch($parse($attrs[key]), function(value) {\n self[key] = value ? new Date(value) : null;\n self.refreshView();\n });\n } else {\n self[key] = datepickerConfig[key] ? new Date(datepickerConfig[key]) : null;\n }\n });\n\n $scope.datepickerMode = $scope.datepickerMode || datepickerConfig.datepickerMode;\n $scope.uniqueId = 'datepicker-' + $scope.$id + '-' + Math.floor(Math.random() * 10000);\n this.activeDate = angular.isDefined($attrs.initDate) ? $scope.$parent.$eval($attrs.initDate) : new Date();\n\n $scope.isActive = function(dateObject) {\n if (self.compare(dateObject.date, self.activeDate) === 0) {\n $scope.activeDateId = dateObject.uid;\n return true;\n }\n return false;\n };\n\n this.init = function( ngModelCtrl_ ) {\n ngModelCtrl = ngModelCtrl_;\n\n ngModelCtrl.$render = function() {\n self.render();\n };\n };\n\n this.render = function() {\n if ( ngModelCtrl.$modelValue ) {\n var date = new Date( ngModelCtrl.$modelValue ),\n isValid = !isNaN(date);\n\n if ( isValid ) {\n this.activeDate = date;\n } else {\n $log.error('Datepicker directive: \"ng-model\" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');\n }\n ngModelCtrl.$setValidity('date', isValid);\n }\n this.refreshView();\n };\n\n this.refreshView = function() {\n if ( this.element ) {\n this._refreshView();\n\n var date = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : null;\n ngModelCtrl.$setValidity('date-disabled', !date || (this.element && !this.isDisabled(date)));\n }\n };\n\n this.createDateObject = function(date, format) {\n var model = ngModelCtrl.$modelValue ? new Date(ngModelCtrl.$modelValue) : null;\n return {\n date: date,\n label: dateFilter(date, format),\n selected: model && this.compare(date, model) === 0,\n disabled: this.isDisabled(date),\n current: this.compare(date, new Date()) === 0\n };\n };\n\n this.isDisabled = function( date ) {\n return ((this.minDate && this.compare(date, this.minDate) < 0) || (this.maxDate && this.compare(date, this.maxDate) > 0) || ($attrs.dateDisabled && $scope.dateDisabled({date: date, mode: $scope.datepickerMode})));\n };\n\n // Split array into smaller arrays\n this.split = function(arr, size) {\n var arrays = [];\n while (arr.length > 0) {\n arrays.push(arr.splice(0, size));\n }\n return arrays;\n };\n\n $scope.select = function( date ) {\n if ( $scope.datepickerMode === self.minMode ) {\n var dt = ngModelCtrl.$modelValue ? new Date( ngModelCtrl.$modelValue ) : new Date(0, 0, 0, 0, 0, 0, 0);\n dt.setFullYear( date.getFullYear(), date.getMonth(), date.getDate() );\n ngModelCtrl.$setViewValue( dt );\n ngModelCtrl.$render();\n } else {\n self.activeDate = date;\n $scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) - 1 ];\n }\n };\n\n $scope.move = function( direction ) {\n var year = self.activeDate.getFullYear() + direction * (self.step.years || 0),\n month = self.activeDate.getMonth() + direction * (self.step.months || 0);\n self.activeDate.setFullYear(year, month, 1);\n self.refreshView();\n };\n\n $scope.toggleMode = function( direction ) {\n direction = direction || 1;\n\n if (($scope.datepickerMode === self.maxMode && direction === 1) || ($scope.datepickerMode === self.minMode && direction === -1)) {\n return;\n }\n\n $scope.datepickerMode = self.modes[ self.modes.indexOf( $scope.datepickerMode ) + direction ];\n };\n\n // Key event mapper\n $scope.keys = { 13:'enter', 32:'space', 33:'pageup', 34:'pagedown', 35:'end', 36:'home', 37:'left', 38:'up', 39:'right', 40:'down' };\n\n var focusElement = function() {\n $timeout(function() {\n self.element[0].focus();\n }, 0 , false);\n };\n\n // Listen for focus requests from popup directive\n $scope.$on('datepicker.focus', focusElement);\n\n $scope.keydown = function( evt ) {\n var key = $scope.keys[evt.which];\n\n if ( !key || evt.shiftKey || evt.altKey ) {\n return;\n }\n\n evt.preventDefault();\n evt.stopPropagation();\n\n if (key === 'enter' || key === 'space') {\n if ( self.isDisabled(self.activeDate)) {\n return; // do nothing\n }\n $scope.select(self.activeDate);\n focusElement();\n } else if (evt.ctrlKey && (key === 'up' || key === 'down')) {\n $scope.toggleMode(key === 'up' ? 1 : -1);\n focusElement();\n } else {\n self.handleKeyDown(key, evt);\n self.refreshView();\n }\n };\n}])\n\n.directive( 'datepicker', function () {\n return {\n restrict: 'EA',\n replace: true,\n templateUrl: 'template/datepicker/datepicker.html',\n scope: {\n datepickerMode: '=?',\n dateDisabled: '&'\n },\n require: ['datepicker', '?^ngModel'],\n controller: 'DatepickerController',\n link: function(scope, element, attrs, ctrls) {\n var datepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];\n\n if ( ngModelCtrl ) {\n datepickerCtrl.init( ngModelCtrl );\n }\n }\n };\n})\n\n.directive('daypicker', ['dateFilter', function (dateFilter) {\n return {\n restrict: 'EA',\n replace: true,\n templateUrl: 'template/datepicker/day.html',\n require: '^datepicker',\n link: function(scope, element, attrs, ctrl) {\n scope.showWeeks = ctrl.showWeeks;\n\n ctrl.step = { months: 1 };\n ctrl.element = element;\n\n var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\n function getDaysInMonth( year, month ) {\n return ((month === 1) && (year % 4 === 0) && ((year % 100 !== 0) || (year % 400 === 0))) ? 29 : DAYS_IN_MONTH[month];\n }\n\n function getDates(startDate, n) {\n var dates = new Array(n), current = new Date(startDate), i = 0;\n current.setHours(12); // Prevent repeated dates because of timezone bug\n while ( i < n ) {\n dates[i++] = new Date(current);\n current.setDate( current.getDate() + 1 );\n }\n return dates;\n }\n\n ctrl._refreshView = function() {\n var year = ctrl.activeDate.getFullYear(),\n month = ctrl.activeDate.getMonth(),\n firstDayOfMonth = new Date(year, month, 1),\n difference = ctrl.startingDay - firstDayOfMonth.getDay(),\n numDisplayedFromPreviousMonth = (difference > 0) ? 7 - difference : - difference,\n firstDate = new Date(firstDayOfMonth);\n\n if ( numDisplayedFromPreviousMonth > 0 ) {\n firstDate.setDate( - numDisplayedFromPreviousMonth + 1 );\n }\n\n // 42 is the number of days on a six-month calendar\n var days = getDates(firstDate, 42);\n for (var i = 0; i < 42; i ++) {\n days[i] = angular.extend(ctrl.createDateObject(days[i], ctrl.formatDay), {\n secondary: days[i].getMonth() !== month,\n uid: scope.uniqueId + '-' + i\n });\n }\n\n scope.labels = new Array(7);\n for (var j = 0; j < 7; j++) {\n scope.labels[j] = {\n abbr: dateFilter(days[j].date, ctrl.formatDayHeader),\n full: dateFilter(days[j].date, 'EEEE')\n };\n }\n\n scope.title = dateFilter(ctrl.activeDate, ctrl.formatDayTitle);\n scope.rows = ctrl.split(days, 7);\n\n if ( scope.showWeeks ) {\n scope.weekNumbers = [];\n var weekNumber = getISO8601WeekNumber( scope.rows[0][0].date ),\n numWeeks = scope.rows.length;\n while( scope.weekNumbers.push(weekNumber++) < numWeeks ) {}\n }\n };\n\n ctrl.compare = function(date1, date2) {\n return (new Date( date1.getFullYear(), date1.getMonth(), date1.getDate() ) - new Date( date2.getFullYear(), date2.getMonth(), date2.getDate() ) );\n };\n\n function getISO8601WeekNumber(date) {\n var checkDate = new Date(date);\n checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); // Thursday\n var time = checkDate.getTime();\n checkDate.setMonth(0); // Compare with Jan 1\n checkDate.setDate(1);\n return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;\n }\n\n ctrl.handleKeyDown = function( key, evt ) {\n var date = ctrl.activeDate.getDate();\n\n if (key === 'left') {\n date = date - 1; // up\n } else if (key === 'up') {\n date = date - 7; // down\n } else if (key === 'right') {\n date = date + 1; // down\n } else if (key === 'down') {\n date = date + 7;\n } else if (key === 'pageup' || key === 'pagedown') {\n var month = ctrl.activeDate.getMonth() + (key === 'pageup' ? - 1 : 1);\n ctrl.activeDate.setMonth(month, 1);\n date = Math.min(getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth()), date);\n } else if (key === 'home') {\n date = 1;\n } else if (key === 'end') {\n date = getDaysInMonth(ctrl.activeDate.getFullYear(), ctrl.activeDate.getMonth());\n }\n ctrl.activeDate.setDate(date);\n };\n\n ctrl.refreshView();\n }\n };\n}])\n\n.directive('monthpicker', ['dateFilter', function (dateFilter) {\n return {\n restrict: 'EA',\n replace: true,\n templateUrl: 'template/datepicker/month.html',\n require: '^datepicker',\n link: function(scope, element, attrs, ctrl) {\n ctrl.step = { years: 1 };\n ctrl.element = element;\n\n ctrl._refreshView = function() {\n var months = new Array(12),\n year = ctrl.activeDate.getFullYear();\n\n for ( var i = 0; i < 12; i++ ) {\n months[i] = angular.extend(ctrl.createDateObject(new Date(year, i, 1), ctrl.formatMonth), {\n uid: scope.uniqueId + '-' + i\n });\n }\n\n scope.title = dateFilter(ctrl.activeDate, ctrl.formatMonthTitle);\n scope.rows = ctrl.split(months, 3);\n };\n\n ctrl.compare = function(date1, date2) {\n return new Date( date1.getFullYear(), date1.getMonth() ) - new Date( date2.getFullYear(), date2.getMonth() );\n };\n\n ctrl.handleKeyDown = function( key, evt ) {\n var date = ctrl.activeDate.getMonth();\n\n if (key === 'left') {\n date = date - 1; // up\n } else if (key === 'up') {\n date = date - 3; // down\n } else if (key === 'right') {\n date = date + 1; // down\n } else if (key === 'down') {\n date = date + 3;\n } else if (key === 'pageup' || key === 'pagedown') {\n var year = ctrl.activeDate.getFullYear() + (key === 'pageup' ? - 1 : 1);\n ctrl.activeDate.setFullYear(year);\n } else if (key === 'home') {\n date = 0;\n } else if (key === 'end') {\n date = 11;\n }\n ctrl.activeDate.setMonth(date);\n };\n\n ctrl.refreshView();\n }\n };\n}])\n\n.directive('yearpicker', ['dateFilter', function (dateFilter) {\n return {\n restrict: 'EA',\n replace: true,\n templateUrl: 'template/datepicker/year.html',\n require: '^datepicker',\n link: function(scope, element, attrs, ctrl) {\n var range = ctrl.yearRange;\n\n ctrl.step = { years: range };\n ctrl.element = element;\n\n function getStartingYear( year ) {\n return parseInt((year - 1) / range, 10) * range + 1;\n }\n\n ctrl._refreshView = function() {\n var years = new Array(range);\n\n for ( var i = 0, start = getStartingYear(ctrl.activeDate.getFullYear()); i < range; i++ ) {\n years[i] = angular.extend(ctrl.createDateObject(new Date(start + i, 0, 1), ctrl.formatYear), {\n uid: scope.uniqueId + '-' + i\n });\n }\n\n scope.title = [years[0].label, years[range - 1].label].join(' - ');\n scope.rows = ctrl.split(years, 5);\n };\n\n ctrl.compare = function(date1, date2) {\n return date1.getFullYear() - date2.getFullYear();\n };\n\n ctrl.handleKeyDown = function( key, evt ) {\n var date = ctrl.activeDate.getFullYear();\n\n if (key === 'left') {\n date = date - 1; // up\n } else if (key === 'up') {\n date = date - 5; // down\n } else if (key === 'right') {\n date = date + 1; // down\n } else if (key === 'down') {\n date = date + 5;\n } else if (key === 'pageup' || key === 'pagedown') {\n date += (key === 'pageup' ? - 1 : 1) * ctrl.step.years;\n } else if (key === 'home') {\n date = getStartingYear( ctrl.activeDate.getFullYear() );\n } else if (key === 'end') {\n date = getStartingYear( ctrl.activeDate.getFullYear() ) + range - 1;\n }\n ctrl.activeDate.setFullYear(date);\n };\n\n ctrl.refreshView();\n }\n };\n}])\n\n.constant('datepickerPopupConfig', {\n datepickerPopup: 'yyyy-MM-dd',\n currentText: 'Today',\n clearText: 'Clear',\n closeText: 'Done',\n closeOnDateSelection: true,\n appendToBody: false,\n showButtonBar: true\n})\n\n.directive('datepickerPopup', ['$compile', '$parse', '$document', '$position', 'dateFilter', 'dateParser', 'datepickerPopupConfig',\nfunction ($compile, $parse, $document, $position, dateFilter, dateParser, datepickerPopupConfig) {\n return {\n restrict: 'EA',\n require: 'ngModel',\n scope: {\n isOpen: '=?',\n currentText: '@',\n clearText: '@',\n closeText: '@',\n dateDisabled: '&'\n },\n link: function(scope, element, attrs, ngModel) {\n var dateFormat,\n closeOnDateSelection = angular.isDefined(attrs.closeOnDateSelection) ? scope.$parent.$eval(attrs.closeOnDateSelection) : datepickerPopupConfig.closeOnDateSelection,\n appendToBody = angular.isDefined(attrs.datepickerAppendToBody) ? scope.$parent.$eval(attrs.datepickerAppendToBody) : datepickerPopupConfig.appendToBody;\n\n scope.showButtonBar = angular.isDefined(attrs.showButtonBar) ? scope.$parent.$eval(attrs.showButtonBar) : datepickerPopupConfig.showButtonBar;\n\n scope.getText = function( key ) {\n return scope[key + 'Text'] || datepickerPopupConfig[key + 'Text'];\n };\n\n attrs.$observe('datepickerPopup', function(value) {\n dateFormat = value || datepickerPopupConfig.datepickerPopup;\n ngModel.$render();\n });\n\n // popup element used to display calendar\n var popupEl = angular.element('
');\n popupEl.attr({\n 'ng-model': 'date',\n 'ng-change': 'dateSelection()'\n });\n\n function cameltoDash( string ){\n return string.replace(/([A-Z])/g, function($1) { return '-' + $1.toLowerCase(); });\n }\n\n // datepicker element\n var datepickerEl = angular.element(popupEl.children()[0]);\n if ( attrs.datepickerOptions ) {\n angular.forEach(scope.$parent.$eval(attrs.datepickerOptions), function( value, option ) {\n datepickerEl.attr( cameltoDash(option), value );\n });\n }\n\n scope.watchData = {};\n angular.forEach(['minDate', 'maxDate', 'datepickerMode'], function( key ) {\n if ( attrs[key] ) {\n var getAttribute = $parse(attrs[key]);\n scope.$parent.$watch(getAttribute, function(value){\n scope.watchData[key] = value;\n });\n datepickerEl.attr(cameltoDash(key), 'watchData.' + key);\n\n // Propagate changes from datepicker to outside\n if ( key === 'datepickerMode' ) {\n var setAttribute = getAttribute.assign;\n scope.$watch('watchData.' + key, function(value, oldvalue) {\n if ( value !== oldvalue ) {\n setAttribute(scope.$parent, value);\n }\n });\n }\n }\n });\n if (attrs.dateDisabled) {\n datepickerEl.attr('date-disabled', 'dateDisabled({ date: date, mode: mode })');\n }\n\n function parseDate(viewValue) {\n if (!viewValue) {\n ngModel.$setValidity('date', true);\n return null;\n } else if (angular.isDate(viewValue) && !isNaN(viewValue)) {\n ngModel.$setValidity('date', true);\n return viewValue;\n } else if (angular.isString(viewValue)) {\n var date = dateParser.parse(viewValue, dateFormat) || new Date(viewValue);\n if (isNaN(date)) {\n ngModel.$setValidity('date', false);\n return undefined;\n } else {\n ngModel.$setValidity('date', true);\n return date;\n }\n } else {\n ngModel.$setValidity('date', false);\n return undefined;\n }\n }\n ngModel.$parsers.unshift(parseDate);\n\n // Inner change\n scope.dateSelection = function(dt) {\n if (angular.isDefined(dt)) {\n scope.date = dt;\n }\n ngModel.$setViewValue(scope.date);\n ngModel.$render();\n\n if ( closeOnDateSelection ) {\n scope.isOpen = false;\n element[0].focus();\n }\n };\n\n element.bind('input change keyup', function() {\n scope.$apply(function() {\n scope.date = ngModel.$modelValue;\n });\n });\n\n // Outter change\n ngModel.$render = function() {\n var date = ngModel.$viewValue ? dateFilter(ngModel.$viewValue, dateFormat) : '';\n element.val(date);\n scope.date = parseDate( ngModel.$modelValue );\n };\n\n var documentClickBind = function(event) {\n if (scope.isOpen && event.target !== element[0]) {\n scope.$apply(function() {\n scope.isOpen = false;\n });\n }\n };\n\n var keydown = function(evt, noApply) {\n scope.keydown(evt);\n };\n element.bind('keydown', keydown);\n\n scope.keydown = function(evt) {\n if (evt.which === 27) {\n evt.preventDefault();\n evt.stopPropagation();\n scope.close();\n } else if (evt.which === 40 && !scope.isOpen) {\n scope.isOpen = true;\n }\n };\n\n scope.$watch('isOpen', function(value) {\n if (value) {\n scope.$broadcast('datepicker.focus');\n scope.position = appendToBody ? $position.offset(element) : $position.position(element);\n scope.position.top = scope.position.top + element.prop('offsetHeight');\n\n $document.bind('click', documentClickBind);\n } else {\n $document.unbind('click', documentClickBind);\n }\n });\n\n scope.select = function( date ) {\n if (date === 'today') {\n var today = new Date();\n if (angular.isDate(ngModel.$modelValue)) {\n date = new Date(ngModel.$modelValue);\n date.setFullYear(today.getFullYear(), today.getMonth(), today.getDate());\n } else {\n date = new Date(today.setHours(0, 0, 0, 0));\n }\n }\n scope.dateSelection( date );\n };\n\n scope.close = function() {\n scope.isOpen = false;\n element[0].focus();\n };\n\n var $popup = $compile(popupEl)(scope);\n // Prevent jQuery cache memory leak (template is now redundant after linking)\n popupEl.remove();\n\n if ( appendToBody ) {\n $document.find('body').append($popup);\n } else {\n element.after($popup);\n }\n\n scope.$on('$destroy', function() {\n $popup.remove();\n element.unbind('keydown', keydown);\n $document.unbind('click', documentClickBind);\n });\n }\n };\n}])\n\n.directive('datepickerPopupWrap', function() {\n return {\n restrict:'EA',\n replace: true,\n transclude: true,\n templateUrl: 'template/datepicker/popup.html',\n link:function (scope, element, attrs) {\n element.bind('click', function(event) {\n event.preventDefault();\n event.stopPropagation();\n });\n }\n };\n});\n\nangular.module('ui.bootstrap.dropdown', [])\n\n.constant('dropdownConfig', {\n openClass: 'open'\n})\n\n.service('dropdownService', ['$document', function($document) {\n var openScope = null;\n\n this.open = function( dropdownScope ) {\n if ( !openScope ) {\n $document.bind('click', closeDropdown);\n $document.bind('keydown', escapeKeyBind);\n }\n\n if ( openScope && openScope !== dropdownScope ) {\n openScope.isOpen = false;\n }\n\n openScope = dropdownScope;\n };\n\n this.close = function( dropdownScope ) {\n if ( openScope === dropdownScope ) {\n openScope = null;\n $document.unbind('click', closeDropdown);\n $document.unbind('keydown', escapeKeyBind);\n }\n };\n\n var closeDropdown = function( evt ) {\n var toggleElement = openScope.getToggleElement();\n if ( evt && toggleElement && toggleElement[0].contains(evt.target) ) {\n return;\n }\n\n openScope.$apply(function() {\n openScope.isOpen = false;\n });\n };\n\n var escapeKeyBind = function( evt ) {\n if ( evt.which === 27 ) {\n openScope.focusToggleElement();\n closeDropdown();\n }\n };\n}])\n\n.controller('DropdownController', ['$scope', '$attrs', '$parse', 'dropdownConfig', 'dropdownService', '$animate', function($scope, $attrs, $parse, dropdownConfig, dropdownService, $animate) {\n var self = this,\n scope = $scope.$new(), // create a child scope so we are not polluting original one\n openClass = dropdownConfig.openClass,\n getIsOpen,\n setIsOpen = angular.noop,\n toggleInvoker = $attrs.onToggle ? $parse($attrs.onToggle) : angular.noop;\n\n this.init = function( element ) {\n self.$element = element;\n\n if ( $attrs.isOpen ) {\n getIsOpen = $parse($attrs.isOpen);\n setIsOpen = getIsOpen.assign;\n\n $scope.$watch(getIsOpen, function(value) {\n scope.isOpen = !!value;\n });\n }\n };\n\n this.toggle = function( open ) {\n return scope.isOpen = arguments.length ? !!open : !scope.isOpen;\n };\n\n // Allow other directives to watch status\n this.isOpen = function() {\n return scope.isOpen;\n };\n\n scope.getToggleElement = function() {\n return self.toggleElement;\n };\n\n scope.focusToggleElement = function() {\n if ( self.toggleElement ) {\n self.toggleElement[0].focus();\n }\n };\n\n scope.$watch('isOpen', function( isOpen, wasOpen ) {\n $animate[isOpen ? 'addClass' : 'removeClass'](self.$element, openClass);\n\n if ( isOpen ) {\n scope.focusToggleElement();\n dropdownService.open( scope );\n } else {\n dropdownService.close( scope );\n }\n\n setIsOpen($scope, isOpen);\n if (angular.isDefined(isOpen) && isOpen !== wasOpen) {\n toggleInvoker($scope, { open: !!isOpen });\n }\n });\n\n $scope.$on('$locationChangeSuccess', function() {\n scope.isOpen = false;\n });\n\n $scope.$on('$destroy', function() {\n scope.$destroy();\n });\n}])\n\n.directive('dropdown', function() {\n return {\n restrict: 'CA',\n controller: 'DropdownController',\n link: function(scope, element, attrs, dropdownCtrl) {\n dropdownCtrl.init( element );\n }\n };\n})\n\n.directive('dropdownToggle', function() {\n return {\n restrict: 'CA',\n require: '?^dropdown',\n link: function(scope, element, attrs, dropdownCtrl) {\n if ( !dropdownCtrl ) {\n return;\n }\n\n dropdownCtrl.toggleElement = element;\n\n var toggleDropdown = function(event) {\n event.preventDefault();\n\n if ( !element.hasClass('disabled') && !attrs.disabled ) {\n scope.$apply(function() {\n dropdownCtrl.toggle();\n });\n }\n };\n\n element.bind('click', toggleDropdown);\n\n // WAI-ARIA\n element.attr({ 'aria-haspopup': true, 'aria-expanded': false });\n scope.$watch(dropdownCtrl.isOpen, function( isOpen ) {\n element.attr('aria-expanded', !!isOpen);\n });\n\n scope.$on('$destroy', function() {\n element.unbind('click', toggleDropdown);\n });\n }\n };\n});\n\nangular.module('ui.bootstrap.modal', ['ui.bootstrap.transition'])\n\n/**\n * A helper, internal data structure that acts as a map but also allows getting / removing\n * elements in the LIFO order\n */\n .factory('$$stackedMap', function () {\n return {\n createNew: function () {\n var stack = [];\n\n return {\n add: function (key, value) {\n stack.push({\n key: key,\n value: value\n });\n },\n get: function (key) {\n for (var i = 0; i < stack.length; i++) {\n if (key == stack[i].key) {\n return stack[i];\n }\n }\n },\n keys: function() {\n var keys = [];\n for (var i = 0; i < stack.length; i++) {\n keys.push(stack[i].key);\n }\n return keys;\n },\n top: function () {\n return stack[stack.length - 1];\n },\n remove: function (key) {\n var idx = -1;\n for (var i = 0; i < stack.length; i++) {\n if (key == stack[i].key) {\n idx = i;\n break;\n }\n }\n return stack.splice(idx, 1)[0];\n },\n removeTop: function () {\n return stack.splice(stack.length - 1, 1)[0];\n },\n length: function () {\n return stack.length;\n }\n };\n }\n };\n })\n\n/**\n * A helper directive for the $modal service. It creates a backdrop element.\n */\n .directive('modalBackdrop', ['$timeout', function ($timeout) {\n return {\n restrict: 'EA',\n replace: true,\n templateUrl: 'template/modal/backdrop.html',\n link: function (scope, element, attrs) {\n scope.backdropClass = attrs.backdropClass || '';\n\n scope.animate = false;\n\n //trigger CSS transitions\n $timeout(function () {\n scope.animate = true;\n });\n }\n };\n }])\n\n .directive('modalWindow', ['$modalStack', '$timeout', function ($modalStack, $timeout) {\n return {\n restrict: 'EA',\n scope: {\n index: '@',\n animate: '='\n },\n replace: true,\n transclude: true,\n templateUrl: function(tElement, tAttrs) {\n return tAttrs.templateUrl || 'template/modal/window.html';\n },\n link: function (scope, element, attrs) {\n element.addClass(attrs.windowClass || '');\n scope.size = attrs.size;\n\n $timeout(function () {\n // trigger CSS transitions\n scope.animate = true;\n\n /**\n * Auto-focusing of a freshly-opened modal element causes any child elements\n * with the autofocus attribute to loose focus. This is an issue on touch\n * based devices which will show and then hide the onscreen keyboard.\n * Attempts to refocus the autofocus element via JavaScript will not reopen\n * the onscreen keyboard. Fixed by updated the focusing logic to only autofocus\n * the modal element if the modal does not contain an autofocus element.\n */\n if (!element[0].querySelectorAll('[autofocus]').length) {\n element[0].focus();\n }\n });\n\n scope.close = function (evt) {\n var modal = $modalStack.getTop();\n if (modal && modal.value.backdrop && modal.value.backdrop != 'static' && (evt.target === evt.currentTarget)) {\n evt.preventDefault();\n evt.stopPropagation();\n $modalStack.dismiss(modal.key, 'backdrop click');\n }\n };\n }\n };\n }])\n\n .directive('modalTransclude', function () {\n return {\n link: function($scope, $element, $attrs, controller, $transclude) {\n $transclude($scope.$parent, function(clone) {\n $element.empty();\n $element.append(clone);\n });\n }\n };\n })\n\n .factory('$modalStack', ['$transition', '$timeout', '$document', '$compile', '$rootScope', '$$stackedMap',\n function ($transition, $timeout, $document, $compile, $rootScope, $$stackedMap) {\n\n var OPENED_MODAL_CLASS = 'modal-open';\n\n var backdropDomEl, backdropScope;\n var openedWindows = $$stackedMap.createNew();\n var $modalStack = {};\n\n function backdropIndex() {\n var topBackdropIndex = -1;\n var opened = openedWindows.keys();\n for (var i = 0; i < opened.length; i++) {\n if (openedWindows.get(opened[i]).value.backdrop) {\n topBackdropIndex = i;\n }\n }\n return topBackdropIndex;\n }\n\n $rootScope.$watch(backdropIndex, function(newBackdropIndex){\n if (backdropScope) {\n backdropScope.index = newBackdropIndex;\n }\n });\n\n function removeModalWindow(modalInstance) {\n\n var body = $document.find('body').eq(0);\n var modalWindow = openedWindows.get(modalInstance).value;\n\n //clean up the stack\n openedWindows.remove(modalInstance);\n\n //remove window DOM element\n removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, 300, function() {\n modalWindow.modalScope.$destroy();\n body.toggleClass(OPENED_MODAL_CLASS, openedWindows.length() > 0);\n checkRemoveBackdrop();\n });\n }\n\n function checkRemoveBackdrop() {\n //remove backdrop if no longer needed\n if (backdropDomEl && backdropIndex() == -1) {\n var backdropScopeRef = backdropScope;\n removeAfterAnimate(backdropDomEl, backdropScope, 150, function () {\n backdropScopeRef.$destroy();\n backdropScopeRef = null;\n });\n backdropDomEl = undefined;\n backdropScope = undefined;\n }\n }\n\n function removeAfterAnimate(domEl, scope, emulateTime, done) {\n // Closing animation\n scope.animate = false;\n\n var transitionEndEventName = $transition.transitionEndEventName;\n if (transitionEndEventName) {\n // transition out\n var timeout = $timeout(afterAnimating, emulateTime);\n\n domEl.bind(transitionEndEventName, function () {\n $timeout.cancel(timeout);\n afterAnimating();\n scope.$apply();\n });\n } else {\n // Ensure this call is async\n $timeout(afterAnimating);\n }\n\n function afterAnimating() {\n if (afterAnimating.done) {\n return;\n }\n afterAnimating.done = true;\n\n domEl.remove();\n if (done) {\n done();\n }\n }\n }\n\n $document.bind('keydown', function (evt) {\n var modal;\n\n if (evt.which === 27) {\n modal = openedWindows.top();\n if (modal && modal.value.keyboard) {\n evt.preventDefault();\n $rootScope.$apply(function () {\n $modalStack.dismiss(modal.key, 'escape key press');\n });\n }\n }\n });\n\n $modalStack.open = function (modalInstance, modal) {\n\n openedWindows.add(modalInstance, {\n deferred: modal.deferred,\n modalScope: modal.scope,\n backdrop: modal.backdrop,\n keyboard: modal.keyboard\n });\n\n var body = $document.find('body').eq(0),\n currBackdropIndex = backdropIndex();\n\n if (currBackdropIndex >= 0 && !backdropDomEl) {\n backdropScope = $rootScope.$new(true);\n backdropScope.index = currBackdropIndex;\n var angularBackgroundDomEl = angular.element('
');\n angularBackgroundDomEl.attr('backdrop-class', modal.backdropClass);\n backdropDomEl = $compile(angularBackgroundDomEl)(backdropScope);\n body.append(backdropDomEl);\n }\n\n var angularDomEl = angular.element('
');\n angularDomEl.attr({\n 'template-url': modal.windowTemplateUrl,\n 'window-class': modal.windowClass,\n 'size': modal.size,\n 'index': openedWindows.length() - 1,\n 'animate': 'animate'\n }).html(modal.content);\n\n var modalDomEl = $compile(angularDomEl)(modal.scope);\n openedWindows.top().value.modalDomEl = modalDomEl;\n body.append(modalDomEl);\n body.addClass(OPENED_MODAL_CLASS);\n };\n\n $modalStack.close = function (modalInstance, result) {\n var modalWindow = openedWindows.get(modalInstance);\n if (modalWindow) {\n modalWindow.value.deferred.resolve(result);\n removeModalWindow(modalInstance);\n }\n };\n\n $modalStack.dismiss = function (modalInstance, reason) {\n var modalWindow = openedWindows.get(modalInstance);\n if (modalWindow) {\n modalWindow.value.deferred.reject(reason);\n removeModalWindow(modalInstance);\n }\n };\n\n $modalStack.dismissAll = function (reason) {\n var topModal = this.getTop();\n while (topModal) {\n this.dismiss(topModal.key, reason);\n topModal = this.getTop();\n }\n };\n\n $modalStack.getTop = function () {\n return openedWindows.top();\n };\n\n return $modalStack;\n }])\n\n .provider('$modal', function () {\n\n var $modalProvider = {\n options: {\n backdrop: true, //can be also false or 'static'\n keyboard: true\n },\n $get: ['$injector', '$rootScope', '$q', '$http', '$templateCache', '$controller', '$modalStack',\n function ($injector, $rootScope, $q, $http, $templateCache, $controller, $modalStack) {\n\n var $modal = {};\n\n function getTemplatePromise(options) {\n return options.template ? $q.when(options.template) :\n $http.get(angular.isFunction(options.templateUrl) ? (options.templateUrl)() : options.templateUrl,\n {cache: $templateCache}).then(function (result) {\n return result.data;\n });\n }\n\n function getResolvePromises(resolves) {\n var promisesArr = [];\n angular.forEach(resolves, function (value) {\n if (angular.isFunction(value) || angular.isArray(value)) {\n promisesArr.push($q.when($injector.invoke(value)));\n }\n });\n return promisesArr;\n }\n\n $modal.open = function (modalOptions) {\n\n var modalResultDeferred = $q.defer();\n var modalOpenedDeferred = $q.defer();\n\n //prepare an instance of a modal to be injected into controllers and returned to a caller\n var modalInstance = {\n result: modalResultDeferred.promise,\n opened: modalOpenedDeferred.promise,\n close: function (result) {\n $modalStack.close(modalInstance, result);\n },\n dismiss: function (reason) {\n $modalStack.dismiss(modalInstance, reason);\n }\n };\n\n //merge and clean up options\n modalOptions = angular.extend({}, $modalProvider.options, modalOptions);\n modalOptions.resolve = modalOptions.resolve || {};\n\n //verify options\n if (!modalOptions.template && !modalOptions.templateUrl) {\n throw new Error('One of template or templateUrl options is required.');\n }\n\n var templateAndResolvePromise =\n $q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));\n\n\n templateAndResolvePromise.then(function resolveSuccess(tplAndVars) {\n\n var modalScope = (modalOptions.scope || $rootScope).$new();\n modalScope.$close = modalInstance.close;\n modalScope.$dismiss = modalInstance.dismiss;\n\n var ctrlInstance, ctrlLocals = {};\n var resolveIter = 1;\n\n //controllers\n if (modalOptions.controller) {\n ctrlLocals.$scope = modalScope;\n ctrlLocals.$modalInstance = modalInstance;\n angular.forEach(modalOptions.resolve, function (value, key) {\n ctrlLocals[key] = tplAndVars[resolveIter++];\n });\n\n ctrlInstance = $controller(modalOptions.controller, ctrlLocals);\n if (modalOptions.controllerAs) {\n modalScope[modalOptions.controllerAs] = ctrlInstance;\n }\n }\n\n $modalStack.open(modalInstance, {\n scope: modalScope,\n deferred: modalResultDeferred,\n content: tplAndVars[0],\n backdrop: modalOptions.backdrop,\n keyboard: modalOptions.keyboard,\n backdropClass: modalOptions.backdropClass,\n windowClass: modalOptions.windowClass,\n windowTemplateUrl: modalOptions.windowTemplateUrl,\n size: modalOptions.size\n });\n\n }, function resolveError(reason) {\n modalResultDeferred.reject(reason);\n });\n\n templateAndResolvePromise.then(function () {\n modalOpenedDeferred.resolve(true);\n }, function () {\n modalOpenedDeferred.reject(false);\n });\n\n return modalInstance;\n };\n\n return $modal;\n }]\n };\n\n return $modalProvider;\n });\n\nangular.module('ui.bootstrap.pagination', [])\n\n.controller('PaginationController', ['$scope', '$attrs', '$parse', function ($scope, $attrs, $parse) {\n var self = this,\n ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl\n setNumPages = $attrs.numPages ? $parse($attrs.numPages).assign : angular.noop;\n\n this.init = function(ngModelCtrl_, config) {\n ngModelCtrl = ngModelCtrl_;\n this.config = config;\n\n ngModelCtrl.$render = function() {\n self.render();\n };\n\n if ($attrs.itemsPerPage) {\n $scope.$parent.$watch($parse($attrs.itemsPerPage), function(value) {\n self.itemsPerPage = parseInt(value, 10);\n $scope.totalPages = self.calculateTotalPages();\n });\n } else {\n this.itemsPerPage = config.itemsPerPage;\n }\n };\n\n this.calculateTotalPages = function() {\n var totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil($scope.totalItems / this.itemsPerPage);\n return Math.max(totalPages || 0, 1);\n };\n\n this.render = function() {\n $scope.page = parseInt(ngModelCtrl.$viewValue, 10) || 1;\n };\n\n $scope.selectPage = function(page) {\n if ( $scope.page !== page && page > 0 && page <= $scope.totalPages) {\n ngModelCtrl.$setViewValue(page);\n ngModelCtrl.$render();\n }\n };\n\n $scope.getText = function( key ) {\n return $scope[key + 'Text'] || self.config[key + 'Text'];\n };\n $scope.noPrevious = function() {\n return $scope.page === 1;\n };\n $scope.noNext = function() {\n return $scope.page === $scope.totalPages;\n };\n\n $scope.$watch('totalItems', function() {\n $scope.totalPages = self.calculateTotalPages();\n });\n\n $scope.$watch('totalPages', function(value) {\n setNumPages($scope.$parent, value); // Readonly variable\n\n if ( $scope.page > value ) {\n $scope.selectPage(value);\n } else {\n ngModelCtrl.$render();\n }\n });\n}])\n\n.constant('paginationConfig', {\n itemsPerPage: 10,\n boundaryLinks: false,\n directionLinks: true,\n firstText: 'First',\n previousText: 'Previous',\n nextText: 'Next',\n lastText: 'Last',\n rotate: true\n})\n\n.directive('pagination', ['$parse', 'paginationConfig', function($parse, paginationConfig) {\n return {\n restrict: 'EA',\n scope: {\n totalItems: '=',\n firstText: '@',\n previousText: '@',\n nextText: '@',\n lastText: '@'\n },\n require: ['pagination', '?ngModel'],\n controller: 'PaginationController',\n templateUrl: 'template/pagination/pagination.html',\n replace: true,\n link: function(scope, element, attrs, ctrls) {\n var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];\n\n if (!ngModelCtrl) {\n return; // do nothing if no ng-model\n }\n\n // Setup configuration parameters\n var maxSize = angular.isDefined(attrs.maxSize) ? scope.$parent.$eval(attrs.maxSize) : paginationConfig.maxSize,\n rotate = angular.isDefined(attrs.rotate) ? scope.$parent.$eval(attrs.rotate) : paginationConfig.rotate;\n scope.boundaryLinks = angular.isDefined(attrs.boundaryLinks) ? scope.$parent.$eval(attrs.boundaryLinks) : paginationConfig.boundaryLinks;\n scope.directionLinks = angular.isDefined(attrs.directionLinks) ? scope.$parent.$eval(attrs.directionLinks) : paginationConfig.directionLinks;\n\n paginationCtrl.init(ngModelCtrl, paginationConfig);\n\n if (attrs.maxSize) {\n scope.$parent.$watch($parse(attrs.maxSize), function(value) {\n maxSize = parseInt(value, 10);\n paginationCtrl.render();\n });\n }\n\n // Create page object used in template\n function makePage(number, text, isActive) {\n return {\n number: number,\n text: text,\n active: isActive\n };\n }\n\n function getPages(currentPage, totalPages) {\n var pages = [];\n\n // Default page limits\n var startPage = 1, endPage = totalPages;\n var isMaxSized = ( angular.isDefined(maxSize) && maxSize < totalPages );\n\n // recompute if maxSize\n if ( isMaxSized ) {\n if ( rotate ) {\n // Current page is displayed in the middle of the visible ones\n startPage = Math.max(currentPage - Math.floor(maxSize/2), 1);\n endPage = startPage + maxSize - 1;\n\n // Adjust if limit is exceeded\n if (endPage > totalPages) {\n endPage = totalPages;\n startPage = endPage - maxSize + 1;\n }\n } else {\n // Visible pages are paginated with maxSize\n startPage = ((Math.ceil(currentPage / maxSize) - 1) * maxSize) + 1;\n\n // Adjust last page if limit is exceeded\n endPage = Math.min(startPage + maxSize - 1, totalPages);\n }\n }\n\n // Add page number links\n for (var number = startPage; number <= endPage; number++) {\n var page = makePage(number, number, number === currentPage);\n pages.push(page);\n }\n\n // Add links to move between page sets\n if ( isMaxSized && ! rotate ) {\n if ( startPage > 1 ) {\n var previousPageSet = makePage(startPage - 1, '...', false);\n pages.unshift(previousPageSet);\n }\n\n if ( endPage < totalPages ) {\n var nextPageSet = makePage(endPage + 1, '...', false);\n pages.push(nextPageSet);\n }\n }\n\n return pages;\n }\n\n var originalRender = paginationCtrl.render;\n paginationCtrl.render = function() {\n originalRender();\n if (scope.page > 0 && scope.page <= scope.totalPages) {\n scope.pages = getPages(scope.page, scope.totalPages);\n }\n };\n }\n };\n}])\n\n.constant('pagerConfig', {\n itemsPerPage: 10,\n previousText: '« Previous',\n nextText: 'Next »',\n align: true\n})\n\n.directive('pager', ['pagerConfig', function(pagerConfig) {\n return {\n restrict: 'EA',\n scope: {\n totalItems: '=',\n previousText: '@',\n nextText: '@'\n },\n require: ['pager', '?ngModel'],\n controller: 'PaginationController',\n templateUrl: 'template/pagination/pager.html',\n replace: true,\n link: function(scope, element, attrs, ctrls) {\n var paginationCtrl = ctrls[0], ngModelCtrl = ctrls[1];\n\n if (!ngModelCtrl) {\n return; // do nothing if no ng-model\n }\n\n scope.align = angular.isDefined(attrs.align) ? scope.$parent.$eval(attrs.align) : pagerConfig.align;\n paginationCtrl.init(ngModelCtrl, pagerConfig);\n }\n };\n}]);\n\n/**\n * The following features are still outstanding: animation as a\n * function, placement as a function, inside, support for more triggers than\n * just mouse enter/leave, html tooltips, and selector delegation.\n */\nangular.module( 'ui.bootstrap.tooltip', [ 'ui.bootstrap.position', 'ui.bootstrap.bindHtml' ] )\n\n/**\n * The $tooltip service creates tooltip- and popover-like directives as well as\n * houses global options for them.\n */\n.provider( '$tooltip', function () {\n // The default options tooltip and popover.\n var defaultOptions = {\n placement: 'top',\n animation: true,\n popupDelay: 0\n };\n\n // Default hide triggers for each show trigger\n var triggerMap = {\n 'mouseenter': 'mouseleave',\n 'click': 'click',\n 'focus': 'blur'\n };\n\n // The options specified to the provider globally.\n var globalOptions = {};\n\n /**\n * `options({})` allows global configuration of all tooltips in the\n * application.\n *\n * var app = angular.module( 'App', ['ui.bootstrap.tooltip'], function( $tooltipProvider ) {\n * // place tooltips left instead of top by default\n * $tooltipProvider.options( { placement: 'left' } );\n * });\n */\n\tthis.options = function( value ) {\n\t\tangular.extend( globalOptions, value );\n\t};\n\n /**\n * This allows you to extend the set of trigger mappings available. E.g.:\n *\n * $tooltipProvider.setTriggers( 'openTrigger': 'closeTrigger' );\n */\n this.setTriggers = function setTriggers ( triggers ) {\n angular.extend( triggerMap, triggers );\n };\n\n /**\n * This is a helper function for translating camel-case to snake-case.\n */\n function snake_case(name){\n var regexp = /[A-Z]/g;\n var separator = '-';\n return name.replace(regexp, function(letter, pos) {\n return (pos ? separator : '') + letter.toLowerCase();\n });\n }\n\n /**\n * Returns the actual instance of the $tooltip service.\n * TODO support multiple triggers\n */\n this.$get = [ '$window', '$compile', '$timeout', '$parse', '$document', '$position', '$interpolate', function ( $window, $compile, $timeout, $parse, $document, $position, $interpolate ) {\n return function $tooltip ( type, prefix, defaultTriggerShow ) {\n var options = angular.extend( {}, defaultOptions, globalOptions );\n\n /**\n * Returns an object of show and hide triggers.\n *\n * If a trigger is supplied,\n * it is used to show the tooltip; otherwise, it will use the `trigger`\n * option passed to the `$tooltipProvider.options` method; else it will\n * default to the trigger supplied to this directive factory.\n *\n * The hide trigger is based on the show trigger. If the `trigger` option\n * was passed to the `$tooltipProvider.options` method, it will use the\n * mapped trigger from `triggerMap` or the passed trigger if the map is\n * undefined; otherwise, it uses the `triggerMap` value of the show\n * trigger; else it will just use the show trigger.\n */\n function getTriggers ( trigger ) {\n var show = trigger || options.trigger || defaultTriggerShow;\n var hide = triggerMap[show] || show;\n return {\n show: show,\n hide: hide\n };\n }\n\n var directiveName = snake_case( type );\n\n var startSym = $interpolate.startSymbol();\n var endSym = $interpolate.endSymbol();\n var template =\n '
'+\n '
';\n\n return {\n restrict: 'EA',\n scope: true,\n compile: function (tElem, tAttrs) {\n var tooltipLinker = $compile( template );\n\n return function link ( scope, element, attrs ) {\n var tooltip;\n var transitionTimeout;\n var popupTimeout;\n var appendToBody = angular.isDefined( options.appendToBody ) ? options.appendToBody : false;\n var triggers = getTriggers( undefined );\n var hasEnableExp = angular.isDefined(attrs[prefix+'Enable']);\n\n var positionTooltip = function () {\n\n var ttPosition = $position.positionElements(element, tooltip, scope.tt_placement, appendToBody);\n ttPosition.top += 'px';\n ttPosition.left += 'px';\n\n // Now set the calculated positioning.\n tooltip.css( ttPosition );\n };\n\n // By default, the tooltip is not open.\n // TODO add ability to start tooltip opened\n scope.tt_isOpen = false;\n\n function toggleTooltipBind () {\n if ( ! scope.tt_isOpen ) {\n showTooltipBind();\n } else {\n hideTooltipBind();\n }\n }\n\n // Show the tooltip with delay if specified, otherwise show it immediately\n function showTooltipBind() {\n if(hasEnableExp && !scope.$eval(attrs[prefix+'Enable'])) {\n return;\n }\n if ( scope.tt_popupDelay ) {\n // Do nothing if the tooltip was already scheduled to pop-up.\n // This happens if show is triggered multiple times before any hide is triggered.\n if (!popupTimeout) {\n popupTimeout = $timeout( show, scope.tt_popupDelay, false );\n popupTimeout.then(function(reposition){reposition();});\n }\n } else {\n show()();\n }\n }\n\n function hideTooltipBind () {\n scope.$apply(function () {\n hide();\n });\n }\n\n // Show the tooltip popup element.\n function show() {\n\n popupTimeout = null;\n\n // If there is a pending remove transition, we must cancel it, lest the\n // tooltip be mysteriously removed.\n if ( transitionTimeout ) {\n $timeout.cancel( transitionTimeout );\n transitionTimeout = null;\n }\n\n // Don't show empty tooltips.\n if ( ! scope.tt_content ) {\n return angular.noop;\n }\n\n createTooltip();\n\n // Set the initial positioning.\n tooltip.css({ top: 0, left: 0, display: 'block' });\n\n // Now we add it to the DOM because need some info about it. But it's not \n // visible yet anyway.\n if ( appendToBody ) {\n $document.find( 'body' ).append( tooltip );\n } else {\n element.after( tooltip );\n }\n\n positionTooltip();\n\n // And show the tooltip.\n scope.tt_isOpen = true;\n scope.$digest(); // digest required as $apply is not called\n\n // Return positioning function as promise callback for correct\n // positioning after draw.\n return positionTooltip;\n }\n\n // Hide the tooltip popup element.\n function hide() {\n // First things first: we don't show it anymore.\n scope.tt_isOpen = false;\n\n //if tooltip is going to be shown after delay, we must cancel this\n $timeout.cancel( popupTimeout );\n popupTimeout = null;\n\n // And now we remove it from the DOM. However, if we have animation, we \n // need to wait for it to expire beforehand.\n // FIXME: this is a placeholder for a port of the transitions library.\n if ( scope.tt_animation ) {\n if (!transitionTimeout) {\n transitionTimeout = $timeout(removeTooltip, 500);\n }\n } else {\n removeTooltip();\n }\n }\n\n function createTooltip() {\n // There can only be one tooltip element per directive shown at once.\n if (tooltip) {\n removeTooltip();\n }\n tooltip = tooltipLinker(scope, function () {});\n\n // Get contents rendered into the tooltip\n scope.$digest();\n }\n\n function removeTooltip() {\n transitionTimeout = null;\n if (tooltip) {\n tooltip.remove();\n tooltip = null;\n }\n }\n\n /**\n * Observe the relevant attributes.\n */\n attrs.$observe( type, function ( val ) {\n scope.tt_content = val;\n\n if (!val && scope.tt_isOpen ) {\n hide();\n }\n });\n\n attrs.$observe( prefix+'Title', function ( val ) {\n scope.tt_title = val;\n });\n\n attrs.$observe( prefix+'Placement', function ( val ) {\n scope.tt_placement = angular.isDefined( val ) ? val : options.placement;\n });\n\n attrs.$observe( prefix+'PopupDelay', function ( val ) {\n var delay = parseInt( val, 10 );\n scope.tt_popupDelay = ! isNaN(delay) ? delay : options.popupDelay;\n });\n\n var unregisterTriggers = function () {\n element.unbind(triggers.show, showTooltipBind);\n element.unbind(triggers.hide, hideTooltipBind);\n };\n\n attrs.$observe( prefix+'Trigger', function ( val ) {\n unregisterTriggers();\n\n triggers = getTriggers( val );\n\n if ( triggers.show === triggers.hide ) {\n element.bind( triggers.show, toggleTooltipBind );\n } else {\n element.bind( triggers.show, showTooltipBind );\n element.bind( triggers.hide, hideTooltipBind );\n }\n });\n\n var animation = scope.$eval(attrs[prefix + 'Animation']);\n scope.tt_animation = angular.isDefined(animation) ? !!animation : options.animation;\n\n attrs.$observe( prefix+'AppendToBody', function ( val ) {\n appendToBody = angular.isDefined( val ) ? $parse( val )( scope ) : appendToBody;\n });\n\n // if a tooltip is attached to we need to remove it on\n // location change as its parent scope will probably not be destroyed\n // by the change.\n if ( appendToBody ) {\n scope.$on('$locationChangeSuccess', function closeTooltipOnLocationChangeSuccess () {\n if ( scope.tt_isOpen ) {\n hide();\n }\n });\n }\n\n // Make sure tooltip is destroyed and removed.\n scope.$on('$destroy', function onDestroyTooltip() {\n $timeout.cancel( transitionTimeout );\n $timeout.cancel( popupTimeout );\n unregisterTriggers();\n removeTooltip();\n });\n };\n }\n };\n };\n }];\n})\n\n.directive( 'tooltipPopup', function () {\n return {\n restrict: 'EA',\n replace: true,\n scope: { content: '@', placement: '@', animation: '&', isOpen: '&' },\n templateUrl: 'template/tooltip/tooltip-popup.html'\n };\n})\n\n.directive( 'tooltip', [ '$tooltip', function ( $tooltip ) {\n return $tooltip( 'tooltip', 'tooltip', 'mouseenter' );\n}])\n\n.directive( 'tooltipHtmlUnsafePopup', function () {\n return {\n restrict: 'EA',\n replace: true,\n scope: { content: '@', placement: '@', animation: '&', isOpen: '&' },\n templateUrl: 'template/tooltip/tooltip-html-unsafe-popup.html'\n };\n})\n\n.directive( 'tooltipHtmlUnsafe', [ '$tooltip', function ( $tooltip ) {\n return $tooltip( 'tooltipHtmlUnsafe', 'tooltip', 'mouseenter' );\n}]);\n\n/**\n * The following features are still outstanding: popup delay, animation as a\n * function, placement as a function, inside, support for more triggers than\n * just mouse enter/leave, html popovers, and selector delegatation.\n */\nangular.module( 'ui.bootstrap.popover', [ 'ui.bootstrap.tooltip' ] )\n\n.directive( 'popoverPopup', function () {\n return {\n restrict: 'EA',\n replace: true,\n scope: { title: '@', content: '@', placement: '@', animation: '&', isOpen: '&' },\n templateUrl: 'template/popover/popover.html'\n };\n})\n\n.directive( 'popover', [ '$tooltip', function ( $tooltip ) {\n return $tooltip( 'popover', 'popover', 'click' );\n}]);\n\nangular.module('ui.bootstrap.progressbar', [])\n\n.constant('progressConfig', {\n animate: true,\n max: 100\n})\n\n.controller('ProgressController', ['$scope', '$attrs', 'progressConfig', function($scope, $attrs, progressConfig) {\n var self = this,\n animate = angular.isDefined($attrs.animate) ? $scope.$parent.$eval($attrs.animate) : progressConfig.animate;\n\n this.bars = [];\n $scope.max = angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : progressConfig.max;\n\n this.addBar = function(bar, element) {\n if ( !animate ) {\n element.css({'transition': 'none'});\n }\n\n this.bars.push(bar);\n\n bar.$watch('value', function( value ) {\n bar.percent = +(100 * value / $scope.max).toFixed(2);\n });\n\n bar.$on('$destroy', function() {\n element = null;\n self.removeBar(bar);\n });\n };\n\n this.removeBar = function(bar) {\n this.bars.splice(this.bars.indexOf(bar), 1);\n };\n}])\n\n.directive('progress', function() {\n return {\n restrict: 'EA',\n replace: true,\n transclude: true,\n controller: 'ProgressController',\n require: 'progress',\n scope: {},\n templateUrl: 'template/progressbar/progress.html'\n };\n})\n\n.directive('bar', function() {\n return {\n restrict: 'EA',\n replace: true,\n transclude: true,\n require: '^progress',\n scope: {\n value: '=',\n type: '@'\n },\n templateUrl: 'template/progressbar/bar.html',\n link: function(scope, element, attrs, progressCtrl) {\n progressCtrl.addBar(scope, element);\n }\n };\n})\n\n.directive('progressbar', function() {\n return {\n restrict: 'EA',\n replace: true,\n transclude: true,\n controller: 'ProgressController',\n scope: {\n value: '=',\n type: '@'\n },\n templateUrl: 'template/progressbar/progressbar.html',\n link: function(scope, element, attrs, progressCtrl) {\n progressCtrl.addBar(scope, angular.element(element.children()[0]));\n }\n };\n});\nangular.module('ui.bootstrap.rating', [])\n\n.constant('ratingConfig', {\n max: 5,\n stateOn: null,\n stateOff: null\n})\n\n.controller('RatingController', ['$scope', '$attrs', 'ratingConfig', function($scope, $attrs, ratingConfig) {\n var ngModelCtrl = { $setViewValue: angular.noop };\n\n this.init = function(ngModelCtrl_) {\n ngModelCtrl = ngModelCtrl_;\n ngModelCtrl.$render = this.render;\n\n this.stateOn = angular.isDefined($attrs.stateOn) ? $scope.$parent.$eval($attrs.stateOn) : ratingConfig.stateOn;\n this.stateOff = angular.isDefined($attrs.stateOff) ? $scope.$parent.$eval($attrs.stateOff) : ratingConfig.stateOff;\n\n var ratingStates = angular.isDefined($attrs.ratingStates) ? $scope.$parent.$eval($attrs.ratingStates) :\n new Array( angular.isDefined($attrs.max) ? $scope.$parent.$eval($attrs.max) : ratingConfig.max );\n $scope.range = this.buildTemplateObjects(ratingStates);\n };\n\n this.buildTemplateObjects = function(states) {\n for (var i = 0, n = states.length; i < n; i++) {\n states[i] = angular.extend({ index: i }, { stateOn: this.stateOn, stateOff: this.stateOff }, states[i]);\n }\n return states;\n };\n\n $scope.rate = function(value) {\n if ( !$scope.readonly && value >= 0 && value <= $scope.range.length ) {\n ngModelCtrl.$setViewValue(value);\n ngModelCtrl.$render();\n }\n };\n\n $scope.enter = function(value) {\n if ( !$scope.readonly ) {\n $scope.value = value;\n }\n $scope.onHover({value: value});\n };\n\n $scope.reset = function() {\n $scope.value = ngModelCtrl.$viewValue;\n $scope.onLeave();\n };\n\n $scope.onKeydown = function(evt) {\n if (/(37|38|39|40)/.test(evt.which)) {\n evt.preventDefault();\n evt.stopPropagation();\n $scope.rate( $scope.value + (evt.which === 38 || evt.which === 39 ? 1 : -1) );\n }\n };\n\n this.render = function() {\n $scope.value = ngModelCtrl.$viewValue;\n };\n}])\n\n.directive('rating', function() {\n return {\n restrict: 'EA',\n require: ['rating', 'ngModel'],\n scope: {\n readonly: '=?',\n onHover: '&',\n onLeave: '&'\n },\n controller: 'RatingController',\n templateUrl: 'template/rating/rating.html',\n replace: true,\n link: function(scope, element, attrs, ctrls) {\n var ratingCtrl = ctrls[0], ngModelCtrl = ctrls[1];\n\n if ( ngModelCtrl ) {\n ratingCtrl.init( ngModelCtrl );\n }\n }\n };\n});\n\n/**\n * @ngdoc overview\n * @name ui.bootstrap.tabs\n *\n * @description\n * AngularJS version of the tabs directive.\n */\n\nangular.module('ui.bootstrap.tabs', [])\n\n.controller('TabsetController', ['$scope', function TabsetCtrl($scope) {\n var ctrl = this,\n tabs = ctrl.tabs = $scope.tabs = [];\n\n ctrl.select = function(selectedTab) {\n angular.forEach(tabs, function(tab) {\n if (tab.active && tab !== selectedTab) {\n tab.active = false;\n tab.onDeselect();\n }\n });\n selectedTab.active = true;\n selectedTab.onSelect();\n };\n\n ctrl.addTab = function addTab(tab) {\n tabs.push(tab);\n // we can't run the select function on the first tab\n // since that would select it twice\n if (tabs.length === 1) {\n tab.active = true;\n } else if (tab.active) {\n ctrl.select(tab);\n }\n };\n\n ctrl.removeTab = function removeTab(tab) {\n var index = tabs.indexOf(tab);\n //Select a new tab if the tab to be removed is selected\n if (tab.active && tabs.length > 1) {\n //If this is the last tab, select the previous tab. else, the next tab.\n var newActiveIndex = index == tabs.length - 1 ? index - 1 : index + 1;\n ctrl.select(tabs[newActiveIndex]);\n }\n tabs.splice(index, 1);\n };\n}])\n\n/**\n * @ngdoc directive\n * @name ui.bootstrap.tabs.directive:tabset\n * @restrict EA\n *\n * @description\n * Tabset is the outer container for the tabs directive\n *\n * @param {boolean=} vertical Whether or not to use vertical styling for the tabs.\n * @param {boolean=} justified Whether or not to use justified styling for the tabs.\n *\n * @example\n\n \n \n First Content!\n Second Content!\n \n
\n \n First Vertical Content!\n Second Vertical Content!\n \n \n First Justified Content!\n Second Justified Content!\n \n
\n
\n */\n.directive('tabset', function() {\n return {\n restrict: 'EA',\n transclude: true,\n replace: true,\n scope: {\n type: '@'\n },\n controller: 'TabsetController',\n templateUrl: 'template/tabs/tabset.html',\n link: function(scope, element, attrs) {\n scope.vertical = angular.isDefined(attrs.vertical) ? scope.$parent.$eval(attrs.vertical) : false;\n scope.justified = angular.isDefined(attrs.justified) ? scope.$parent.$eval(attrs.justified) : false;\n }\n };\n})\n\n/**\n * @ngdoc directive\n * @name ui.bootstrap.tabs.directive:tab\n * @restrict EA\n *\n * @param {string=} heading The visible heading, or title, of the tab. Set HTML headings with {@link ui.bootstrap.tabs.directive:tabHeading tabHeading}.\n * @param {string=} select An expression to evaluate when the tab is selected.\n * @param {boolean=} active A binding, telling whether or not this tab is selected.\n * @param {boolean=} disabled A binding, telling whether or not this tab is disabled.\n *\n * @description\n * Creates a tab with a heading and content. Must be placed within a {@link ui.bootstrap.tabs.directive:tabset tabset}.\n *\n * @example\n\n \n
\n \n \n
\n \n First Tab\n \n Alert me!\n Second Tab, with alert callback and html heading!\n \n \n {{item.content}}\n \n \n
\n
\n \n function TabsDemoCtrl($scope) {\n $scope.items = [\n { title:\"Dynamic Title 1\", content:\"Dynamic Item 0\" },\n { title:\"Dynamic Title 2\", content:\"Dynamic Item 1\", disabled: true }\n ];\n\n $scope.alertMe = function() {\n setTimeout(function() {\n alert(\"You've selected the alert tab!\");\n });\n };\n };\n \n
\n */\n\n/**\n * @ngdoc directive\n * @name ui.bootstrap.tabs.directive:tabHeading\n * @restrict EA\n *\n * @description\n * Creates an HTML heading for a {@link ui.bootstrap.tabs.directive:tab tab}. Must be placed as a child of a tab element.\n *\n * @example\n\n \n \n \n HTML in my titles?!\n And some content, too!\n \n \n Icon heading?!?\n That's right.\n \n \n \n\n */\n.directive('tab', ['$parse', function($parse) {\n return {\n require: '^tabset',\n restrict: 'EA',\n replace: true,\n templateUrl: 'template/tabs/tab.html',\n transclude: true,\n scope: {\n active: '=?',\n heading: '@',\n onSelect: '&select', //This callback is called in contentHeadingTransclude\n //once it inserts the tab's content into the dom\n onDeselect: '&deselect'\n },\n controller: function() {\n //Empty controller so other directives can require being 'under' a tab\n },\n compile: function(elm, attrs, transclude) {\n return function postLink(scope, elm, attrs, tabsetCtrl) {\n scope.$watch('active', function(active) {\n if (active) {\n tabsetCtrl.select(scope);\n }\n });\n\n scope.disabled = false;\n if ( attrs.disabled ) {\n scope.$parent.$watch($parse(attrs.disabled), function(value) {\n scope.disabled = !! value;\n });\n }\n\n scope.select = function() {\n if ( !scope.disabled ) {\n scope.active = true;\n }\n };\n\n tabsetCtrl.addTab(scope);\n scope.$on('$destroy', function() {\n tabsetCtrl.removeTab(scope);\n });\n\n //We need to transclude later, once the content container is ready.\n //when this link happens, we're inside a tab heading.\n scope.$transcludeFn = transclude;\n };\n }\n };\n}])\n\n.directive('tabHeadingTransclude', [function() {\n return {\n restrict: 'A',\n require: '^tab',\n link: function(scope, elm, attrs, tabCtrl) {\n scope.$watch('headingElement', function updateHeadingElement(heading) {\n if (heading) {\n elm.html('');\n elm.append(heading);\n }\n });\n }\n };\n}])\n\n.directive('tabContentTransclude', function() {\n return {\n restrict: 'A',\n require: '^tabset',\n link: function(scope, elm, attrs) {\n var tab = scope.$eval(attrs.tabContentTransclude);\n\n //Now our tab is ready to be transcluded: both the tab heading area\n //and the tab content area are loaded. Transclude 'em both.\n tab.$transcludeFn(tab.$parent, function(contents) {\n angular.forEach(contents, function(node) {\n if (isTabHeading(node)) {\n //Let tabHeadingTransclude know.\n tab.headingElement = node;\n } else {\n elm.append(node);\n }\n });\n });\n }\n };\n function isTabHeading(node) {\n return node.tagName && (\n node.hasAttribute('tab-heading') ||\n node.hasAttribute('data-tab-heading') ||\n node.tagName.toLowerCase() === 'tab-heading' ||\n node.tagName.toLowerCase() === 'data-tab-heading'\n );\n }\n})\n\n;\n\nangular.module('ui.bootstrap.timepicker', [])\n\n.constant('timepickerConfig', {\n hourStep: 1,\n minuteStep: 1,\n showMeridian: true,\n meridians: null,\n readonlyInput: false,\n mousewheel: true\n})\n\n.controller('TimepickerController', ['$scope', '$attrs', '$parse', '$log', '$locale', 'timepickerConfig', function($scope, $attrs, $parse, $log, $locale, timepickerConfig) {\n var selected = new Date(),\n ngModelCtrl = { $setViewValue: angular.noop }, // nullModelCtrl\n meridians = angular.isDefined($attrs.meridians) ? $scope.$parent.$eval($attrs.meridians) : timepickerConfig.meridians || $locale.DATETIME_FORMATS.AMPMS;\n\n this.init = function( ngModelCtrl_, inputs ) {\n ngModelCtrl = ngModelCtrl_;\n ngModelCtrl.$render = this.render;\n\n var hoursInputEl = inputs.eq(0),\n minutesInputEl = inputs.eq(1);\n\n var mousewheel = angular.isDefined($attrs.mousewheel) ? $scope.$parent.$eval($attrs.mousewheel) : timepickerConfig.mousewheel;\n if ( mousewheel ) {\n this.setupMousewheelEvents( hoursInputEl, minutesInputEl );\n }\n\n $scope.readonlyInput = angular.isDefined($attrs.readonlyInput) ? $scope.$parent.$eval($attrs.readonlyInput) : timepickerConfig.readonlyInput;\n this.setupInputEvents( hoursInputEl, minutesInputEl );\n };\n\n var hourStep = timepickerConfig.hourStep;\n if ($attrs.hourStep) {\n $scope.$parent.$watch($parse($attrs.hourStep), function(value) {\n hourStep = parseInt(value, 10);\n });\n }\n\n var minuteStep = timepickerConfig.minuteStep;\n if ($attrs.minuteStep) {\n $scope.$parent.$watch($parse($attrs.minuteStep), function(value) {\n minuteStep = parseInt(value, 10);\n });\n }\n\n // 12H / 24H mode\n $scope.showMeridian = timepickerConfig.showMeridian;\n if ($attrs.showMeridian) {\n $scope.$parent.$watch($parse($attrs.showMeridian), function(value) {\n $scope.showMeridian = !!value;\n\n if ( ngModelCtrl.$error.time ) {\n // Evaluate from template\n var hours = getHoursFromTemplate(), minutes = getMinutesFromTemplate();\n if (angular.isDefined( hours ) && angular.isDefined( minutes )) {\n selected.setHours( hours );\n refresh();\n }\n } else {\n updateTemplate();\n }\n });\n }\n\n // Get $scope.hours in 24H mode if valid\n function getHoursFromTemplate ( ) {\n var hours = parseInt( $scope.hours, 10 );\n var valid = ( $scope.showMeridian ) ? (hours > 0 && hours < 13) : (hours >= 0 && hours < 24);\n if ( !valid ) {\n return undefined;\n }\n\n if ( $scope.showMeridian ) {\n if ( hours === 12 ) {\n hours = 0;\n }\n if ( $scope.meridian === meridians[1] ) {\n hours = hours + 12;\n }\n }\n return hours;\n }\n\n function getMinutesFromTemplate() {\n var minutes = parseInt($scope.minutes, 10);\n return ( minutes >= 0 && minutes < 60 ) ? minutes : undefined;\n }\n\n function pad( value ) {\n return ( angular.isDefined(value) && value.toString().length < 2 ) ? '0' + value : value;\n }\n\n // Respond on mousewheel spin\n this.setupMousewheelEvents = function( hoursInputEl, minutesInputEl ) {\n var isScrollingUp = function(e) {\n if (e.originalEvent) {\n e = e.originalEvent;\n }\n //pick correct delta variable depending on event\n var delta = (e.wheelDelta) ? e.wheelDelta : -e.deltaY;\n return (e.detail || delta > 0);\n };\n\n hoursInputEl.bind('mousewheel wheel', function(e) {\n $scope.$apply( (isScrollingUp(e)) ? $scope.incrementHours() : $scope.decrementHours() );\n e.preventDefault();\n });\n\n minutesInputEl.bind('mousewheel wheel', function(e) {\n $scope.$apply( (isScrollingUp(e)) ? $scope.incrementMinutes() : $scope.decrementMinutes() );\n e.preventDefault();\n });\n\n };\n\n this.setupInputEvents = function( hoursInputEl, minutesInputEl ) {\n if ( $scope.readonlyInput ) {\n $scope.updateHours = angular.noop;\n $scope.updateMinutes = angular.noop;\n return;\n }\n\n var invalidate = function(invalidHours, invalidMinutes) {\n ngModelCtrl.$setViewValue( null );\n ngModelCtrl.$setValidity('time', false);\n if (angular.isDefined(invalidHours)) {\n $scope.invalidHours = invalidHours;\n }\n if (angular.isDefined(invalidMinutes)) {\n $scope.invalidMinutes = invalidMinutes;\n }\n };\n\n $scope.updateHours = function() {\n var hours = getHoursFromTemplate();\n\n if ( angular.isDefined(hours) ) {\n selected.setHours( hours );\n refresh( 'h' );\n } else {\n invalidate(true);\n }\n };\n\n hoursInputEl.bind('blur', function(e) {\n if ( !$scope.invalidHours && $scope.hours < 10) {\n $scope.$apply( function() {\n $scope.hours = pad( $scope.hours );\n });\n }\n });\n\n $scope.updateMinutes = function() {\n var minutes = getMinutesFromTemplate();\n\n if ( angular.isDefined(minutes) ) {\n selected.setMinutes( minutes );\n refresh( 'm' );\n } else {\n invalidate(undefined, true);\n }\n };\n\n minutesInputEl.bind('blur', function(e) {\n if ( !$scope.invalidMinutes && $scope.minutes < 10 ) {\n $scope.$apply( function() {\n $scope.minutes = pad( $scope.minutes );\n });\n }\n });\n\n };\n\n this.render = function() {\n var date = ngModelCtrl.$modelValue ? new Date( ngModelCtrl.$modelValue ) : null;\n\n if ( isNaN(date) ) {\n ngModelCtrl.$setValidity('time', false);\n $log.error('Timepicker directive: \"ng-model\" value must be a Date object, a number of milliseconds since 01.01.1970 or a string representing an RFC2822 or ISO 8601 date.');\n } else {\n if ( date ) {\n selected = date;\n }\n makeValid();\n updateTemplate();\n }\n };\n\n // Call internally when we know that model is valid.\n function refresh( keyboardChange ) {\n makeValid();\n ngModelCtrl.$setViewValue( new Date(selected) );\n updateTemplate( keyboardChange );\n }\n\n function makeValid() {\n ngModelCtrl.$setValidity('time', true);\n $scope.invalidHours = false;\n $scope.invalidMinutes = false;\n }\n\n function updateTemplate( keyboardChange ) {\n var hours = selected.getHours(), minutes = selected.getMinutes();\n\n if ( $scope.showMeridian ) {\n hours = ( hours === 0 || hours === 12 ) ? 12 : hours % 12; // Convert 24 to 12 hour system\n }\n\n $scope.hours = keyboardChange === 'h' ? hours : pad(hours);\n $scope.minutes = keyboardChange === 'm' ? minutes : pad(minutes);\n $scope.meridian = selected.getHours() < 12 ? meridians[0] : meridians[1];\n }\n\n function addMinutes( minutes ) {\n var dt = new Date( selected.getTime() + minutes * 60000 );\n selected.setHours( dt.getHours(), dt.getMinutes() );\n refresh();\n }\n\n $scope.incrementHours = function() {\n addMinutes( hourStep * 60 );\n };\n $scope.decrementHours = function() {\n addMinutes( - hourStep * 60 );\n };\n $scope.incrementMinutes = function() {\n addMinutes( minuteStep );\n };\n $scope.decrementMinutes = function() {\n addMinutes( - minuteStep );\n };\n $scope.toggleMeridian = function() {\n addMinutes( 12 * 60 * (( selected.getHours() < 12 ) ? 1 : -1) );\n };\n}])\n\n.directive('timepicker', function () {\n return {\n restrict: 'EA',\n require: ['timepicker', '?^ngModel'],\n controller:'TimepickerController',\n replace: true,\n scope: {},\n templateUrl: 'template/timepicker/timepicker.html',\n link: function(scope, element, attrs, ctrls) {\n var timepickerCtrl = ctrls[0], ngModelCtrl = ctrls[1];\n\n if ( ngModelCtrl ) {\n timepickerCtrl.init( ngModelCtrl, element.find('input') );\n }\n }\n };\n});\n\nangular.module('ui.bootstrap.typeahead', ['ui.bootstrap.position', 'ui.bootstrap.bindHtml'])\n\n/**\n * A helper service that can parse typeahead's syntax (string provided by users)\n * Extracted to a separate service for ease of unit testing\n */\n .factory('typeaheadParser', ['$parse', function ($parse) {\n\n // 00000111000000000000022200000000000000003333333333333330000000000044000\n var TYPEAHEAD_REGEXP = /^\\s*([\\s\\S]+?)(?:\\s+as\\s+([\\s\\S]+?))?\\s+for\\s+(?:([\\$\\w][\\$\\w\\d]*))\\s+in\\s+([\\s\\S]+?)$/;\n\n return {\n parse:function (input) {\n\n var match = input.match(TYPEAHEAD_REGEXP);\n if (!match) {\n throw new Error(\n 'Expected typeahead specification in form of \"_modelValue_ (as _label_)? for _item_ in _collection_\"' +\n ' but got \"' + input + '\".');\n }\n\n return {\n itemName:match[3],\n source:$parse(match[4]),\n viewMapper:$parse(match[2] || match[1]),\n modelMapper:$parse(match[1])\n };\n }\n };\n}])\n\n .directive('typeahead', ['$compile', '$parse', '$q', '$timeout', '$document', '$position', 'typeaheadParser',\n function ($compile, $parse, $q, $timeout, $document, $position, typeaheadParser) {\n\n var HOT_KEYS = [9, 13, 27, 38, 40];\n\n return {\n require:'ngModel',\n link:function (originalScope, element, attrs, modelCtrl) {\n\n //SUPPORTED ATTRIBUTES (OPTIONS)\n\n //minimal no of characters that needs to be entered before typeahead kicks-in\n var minSearch = originalScope.$eval(attrs.typeaheadMinLength) || 1;\n\n //minimal wait time after last character typed before typehead kicks-in\n var waitTime = originalScope.$eval(attrs.typeaheadWaitMs) || 0;\n\n //should it restrict model values to the ones selected from the popup only?\n var isEditable = originalScope.$eval(attrs.typeaheadEditable) !== false;\n\n //binding to a variable that indicates if matches are being retrieved asynchronously\n var isLoadingSetter = $parse(attrs.typeaheadLoading).assign || angular.noop;\n\n //a callback executed when a match is selected\n var onSelectCallback = $parse(attrs.typeaheadOnSelect);\n\n var inputFormatter = attrs.typeaheadInputFormatter ? $parse(attrs.typeaheadInputFormatter) : undefined;\n\n var appendToBody = attrs.typeaheadAppendToBody ? originalScope.$eval(attrs.typeaheadAppendToBody) : false;\n\n //INTERNAL VARIABLES\n\n //model setter executed upon match selection\n var $setModelValue = $parse(attrs.ngModel).assign;\n\n //expressions used by typeahead\n var parserResult = typeaheadParser.parse(attrs.typeahead);\n\n var hasFocus;\n\n //create a child scope for the typeahead directive so we are not polluting original scope\n //with typeahead-specific data (matches, query etc.)\n var scope = originalScope.$new();\n originalScope.$on('$destroy', function(){\n scope.$destroy();\n });\n\n // WAI-ARIA\n var popupId = 'typeahead-' + scope.$id + '-' + Math.floor(Math.random() * 10000);\n element.attr({\n 'aria-autocomplete': 'list',\n 'aria-expanded': false,\n 'aria-owns': popupId\n });\n\n //pop-up element used to display matches\n var popUpEl = angular.element('
');\n popUpEl.attr({\n id: popupId,\n matches: 'matches',\n active: 'activeIdx',\n select: 'select(activeIdx)',\n query: 'query',\n position: 'position'\n });\n //custom item template\n if (angular.isDefined(attrs.typeaheadTemplateUrl)) {\n popUpEl.attr('template-url', attrs.typeaheadTemplateUrl);\n }\n\n var resetMatches = function() {\n scope.matches = [];\n scope.activeIdx = -1;\n element.attr('aria-expanded', false);\n };\n\n var getMatchId = function(index) {\n return popupId + '-option-' + index;\n };\n\n // Indicate that the specified match is the active (pre-selected) item in the list owned by this typeahead.\n // This attribute is added or removed automatically when the `activeIdx` changes.\n scope.$watch('activeIdx', function(index) {\n if (index < 0) {\n element.removeAttr('aria-activedescendant');\n } else {\n element.attr('aria-activedescendant', getMatchId(index));\n }\n });\n\n var getMatchesAsync = function(inputValue) {\n\n var locals = {$viewValue: inputValue};\n isLoadingSetter(originalScope, true);\n $q.when(parserResult.source(originalScope, locals)).then(function(matches) {\n\n //it might happen that several async queries were in progress if a user were typing fast\n //but we are interested only in responses that correspond to the current view value\n var onCurrentRequest = (inputValue === modelCtrl.$viewValue);\n if (onCurrentRequest && hasFocus) {\n if (matches.length > 0) {\n\n scope.activeIdx = 0;\n scope.matches.length = 0;\n\n //transform labels\n for(var i=0; i= minSearch) {\n if (waitTime > 0) {\n cancelPreviousTimeout();\n scheduleSearchWithTimeout(inputValue);\n } else {\n getMatchesAsync(inputValue);\n }\n } else {\n isLoadingSetter(originalScope, false);\n cancelPreviousTimeout();\n resetMatches();\n }\n\n if (isEditable) {\n return inputValue;\n } else {\n if (!inputValue) {\n // Reset in case user had typed something previously.\n modelCtrl.$setValidity('editable', true);\n return inputValue;\n } else {\n modelCtrl.$setValidity('editable', false);\n return undefined;\n }\n }\n });\n\n modelCtrl.$formatters.push(function (modelValue) {\n\n var candidateViewValue, emptyViewValue;\n var locals = {};\n\n if (inputFormatter) {\n\n locals['$model'] = modelValue;\n return inputFormatter(originalScope, locals);\n\n } else {\n\n //it might happen that we don't have enough info to properly render input value\n //we need to check for this situation and simply return model value if we can't apply custom formatting\n locals[parserResult.itemName] = modelValue;\n candidateViewValue = parserResult.viewMapper(originalScope, locals);\n locals[parserResult.itemName] = undefined;\n emptyViewValue = parserResult.viewMapper(originalScope, locals);\n\n return candidateViewValue!== emptyViewValue ? candidateViewValue : modelValue;\n }\n });\n\n scope.select = function (activeIdx) {\n //called from within the $digest() cycle\n var locals = {};\n var model, item;\n\n locals[parserResult.itemName] = item = scope.matches[activeIdx].model;\n model = parserResult.modelMapper(originalScope, locals);\n $setModelValue(originalScope, model);\n modelCtrl.$setValidity('editable', true);\n\n onSelectCallback(originalScope, {\n $item: item,\n $model: model,\n $label: parserResult.viewMapper(originalScope, locals)\n });\n\n resetMatches();\n\n //return focus to the input element if a match was selected via a mouse click event\n // use timeout to avoid $rootScope:inprog error\n $timeout(function() { element[0].focus(); }, 0, false);\n };\n\n //bind keyboard events: arrows up(38) / down(40), enter(13) and tab(9), esc(27)\n element.bind('keydown', function (evt) {\n\n //typeahead is open and an \"interesting\" key was pressed\n if (scope.matches.length === 0 || HOT_KEYS.indexOf(evt.which) === -1) {\n return;\n }\n\n evt.preventDefault();\n\n if (evt.which === 40) {\n scope.activeIdx = (scope.activeIdx + 1) % scope.matches.length;\n scope.$digest();\n\n } else if (evt.which === 38) {\n scope.activeIdx = (scope.activeIdx ? scope.activeIdx : scope.matches.length) - 1;\n scope.$digest();\n\n } else if (evt.which === 13 || evt.which === 9) {\n scope.$apply(function () {\n scope.select(scope.activeIdx);\n });\n\n } else if (evt.which === 27) {\n evt.stopPropagation();\n\n resetMatches();\n scope.$digest();\n }\n });\n\n element.bind('blur', function (evt) {\n hasFocus = false;\n });\n\n // Keep reference to click handler to unbind it.\n var dismissClickHandler = function (evt) {\n if (element[0] !== evt.target) {\n resetMatches();\n scope.$digest();\n }\n };\n\n $document.bind('click', dismissClickHandler);\n\n originalScope.$on('$destroy', function(){\n $document.unbind('click', dismissClickHandler);\n });\n\n var $popup = $compile(popUpEl)(scope);\n if ( appendToBody ) {\n $document.find('body').append($popup);\n } else {\n element.after($popup);\n }\n }\n };\n\n}])\n\n .directive('typeaheadPopup', function () {\n return {\n restrict:'EA',\n scope:{\n matches:'=',\n query:'=',\n active:'=',\n position:'=',\n select:'&'\n },\n replace:true,\n templateUrl:'template/typeahead/typeahead-popup.html',\n link:function (scope, element, attrs) {\n\n scope.templateUrl = attrs.templateUrl;\n\n scope.isOpen = function () {\n return scope.matches.length > 0;\n };\n\n scope.isActive = function (matchIdx) {\n return scope.active == matchIdx;\n };\n\n scope.selectActive = function (matchIdx) {\n scope.active = matchIdx;\n };\n\n scope.selectMatch = function (activeIdx) {\n scope.select({activeIdx:activeIdx});\n };\n }\n };\n })\n\n .directive('typeaheadMatch', ['$http', '$templateCache', '$compile', '$parse', function ($http, $templateCache, $compile, $parse) {\n return {\n restrict:'EA',\n scope:{\n index:'=',\n match:'=',\n query:'='\n },\n link:function (scope, element, attrs) {\n var tplUrl = $parse(attrs.templateUrl)(scope.$parent) || 'template/typeahead/typeahead-match.html';\n $http.get(tplUrl, {cache: $templateCache}).success(function(tplContent){\n element.replaceWith($compile(tplContent.trim())(scope));\n });\n }\n };\n }])\n\n .filter('typeaheadHighlight', function() {\n\n function escapeRegexp(queryToEscape) {\n return queryToEscape.replace(/([.?*+^$[\\]\\\\(){}|-])/g, '\\\\$1');\n }\n\n return function(matchItem, query) {\n return query ? ('' + matchItem).replace(new RegExp(escapeRegexp(query), 'gi'), '$&') : matchItem;\n };\n });\n\nangular.module(\"template/accordion/accordion-group.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/accordion/accordion-group.html\",\n \"
\\n\" +\n \"
\\n\" +\n \"

\\n\" +\n \" {{heading}}\\n\" +\n \"

\\n\" +\n \"
\\n\" +\n \"
\\n\" +\n \"\t
\\n\" +\n \"
\\n\" +\n \"
\");\n}]);\n\nangular.module(\"template/accordion/accordion.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/accordion/accordion.html\",\n \"
\");\n}]);\n\nangular.module(\"template/alert/alert.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/alert/alert.html\",\n \"
\\n\" +\n \" \\n\" +\n \"
\\n\" +\n \"
\\n\" +\n \"\");\n}]);\n\nangular.module(\"template/carousel/carousel.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/carousel/carousel.html\",\n \"
\\n\" +\n \"
    1\\\">\\n\" +\n \"
  1. \\n\" +\n \"
\\n\" +\n \"
\\n\" +\n \" 1\\\">\\n\" +\n \" 1\\\">\\n\" +\n \"
\\n\" +\n \"\");\n}]);\n\nangular.module(\"template/carousel/slide.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/carousel/slide.html\",\n \"
\\n\" +\n \"\");\n}]);\n\nangular.module(\"template/datepicker/datepicker.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/datepicker/datepicker.html\",\n \"
\\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \"
\");\n}]);\n\nangular.module(\"template/datepicker/day.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/datepicker/day.html\",\n \"\\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \"
{{label.abbr}}
{{ weekNumbers[$index] }}\\n\" +\n \" \\n\" +\n \"
\\n\" +\n \"\");\n}]);\n\nangular.module(\"template/datepicker/month.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/datepicker/month.html\",\n \"\\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \"
\\n\" +\n \" \\n\" +\n \"
\\n\" +\n \"\");\n}]);\n\nangular.module(\"template/datepicker/popup.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/datepicker/popup.html\",\n \"\\n\" +\n \"\");\n}]);\n\nangular.module(\"template/datepicker/year.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/datepicker/year.html\",\n \"\\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \" \\n\" +\n \"
\\n\" +\n \" \\n\" +\n \"
\\n\" +\n \"\");\n}]);\n\nangular.module(\"template/modal/backdrop.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/modal/backdrop.html\",\n \"
\\n\" +\n \"\");\n}]);\n\nangular.module(\"template/modal/window.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/modal/window.html\",\n \"
\\n\" +\n \"
\\n\" +\n \"
\");\n}]);\n\nangular.module(\"template/pagination/pager.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/pagination/pager.html\",\n \"\");\n}]);\n\nangular.module(\"template/pagination/pagination.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/pagination/pagination.html\",\n \"\");\n}]);\n\nangular.module(\"template/tooltip/tooltip-html-unsafe-popup.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/tooltip/tooltip-html-unsafe-popup.html\",\n \"
\\n\" +\n \"
\\n\" +\n \"
\\n\" +\n \"
\\n\" +\n \"\");\n}]);\n\nangular.module(\"template/tooltip/tooltip-popup.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/tooltip/tooltip-popup.html\",\n \"
\\n\" +\n \"
\\n\" +\n \"
\\n\" +\n \"
\\n\" +\n \"\");\n}]);\n\nangular.module(\"template/popover/popover.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/popover/popover.html\",\n \"
\\n\" +\n \"
\\n\" +\n \"\\n\" +\n \"
\\n\" +\n \"

\\n\" +\n \"
\\n\" +\n \"
\\n\" +\n \"
\\n\" +\n \"\");\n}]);\n\nangular.module(\"template/progressbar/bar.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/progressbar/bar.html\",\n \"
\");\n}]);\n\nangular.module(\"template/progressbar/progress.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/progressbar/progress.html\",\n \"
\");\n}]);\n\nangular.module(\"template/progressbar/progressbar.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/progressbar/progressbar.html\",\n \"
\\n\" +\n \"
\\n\" +\n \"
\");\n}]);\n\nangular.module(\"template/rating/rating.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/rating/rating.html\",\n \"\\n\" +\n \" \\n\" +\n \" ({{ $index < value ? '*' : ' ' }})\\n\" +\n \" \\n\" +\n \"\");\n}]);\n\nangular.module(\"template/tabs/tab.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/tabs/tab.html\",\n \"
  • \\n\" +\n \" {{heading}}\\n\" +\n \"
  • \\n\" +\n \"\");\n}]);\n\nangular.module(\"template/tabs/tabset.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/tabs/tabset.html\",\n \"
    \\n\" +\n \"
      \\n\" +\n \"
      \\n\" +\n \"
      \\n\" +\n \"
      \\n\" +\n \"
      \\n\" +\n \"
      \\n\" +\n \"\");\n}]);\n\nangular.module(\"template/timepicker/timepicker.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/timepicker/timepicker.html\",\n \"\\n\" +\n \"\t\\n\" +\n \"\t\t\\n\" +\n \"\t\t\t\\n\" +\n \"\t\t\t\\n\" +\n \"\t\t\t\\n\" +\n \"\t\t\t\\n\" +\n \"\t\t\\n\" +\n \"\t\t\\n\" +\n \"\t\t\t\\n\" +\n \"\t\t\t\\n\" +\n \"\t\t\t\\n\" +\n \"\t\t\t\\n\" +\n \"\t\t\\n\" +\n \"\t\t\\n\" +\n \"\t\t\t\\n\" +\n \"\t\t\t\\n\" +\n \"\t\t\t\\n\" +\n \"\t\t\t\\n\" +\n \"\t\t\\n\" +\n \"\t\\n\" +\n \"
       
      \\n\" +\n \"\t\t\t\t\\n\" +\n \"\t\t\t:\\n\" +\n \"\t\t\t\t\\n\" +\n \"\t\t\t
       
      \\n\" +\n \"\");\n}]);\n\nangular.module(\"template/typeahead/typeahead-match.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/typeahead/typeahead-match.html\",\n \"\");\n}]);\n\nangular.module(\"template/typeahead/typeahead-popup.html\", []).run([\"$templateCache\", function($templateCache) {\n $templateCache.put(\"template/typeahead/typeahead-popup.html\",\n \"\\n\" +\n \"\");\n}]);\n","/*\n * angular-confirm\n * http://schlogen.github.io/angular-confirm/\n * Version: 1.1.0 - 2015-14-07\n * License: Apache\n */\nangular.module('angular-confirm', ['ui.bootstrap'])\n .controller('ConfirmModalController', ['$scope', '$modalInstance', 'data', function ($scope, $modalInstance, data) {\n $scope.data = angular.copy(data);\n\n $scope.ok = function () {\n $modalInstance.close();\n };\n\n $scope.cancel = function () {\n $modalInstance.dismiss('cancel');\n };\n\n }])\n .value('$confirmModalDefaults', {\n template: '

      {{data.title}}

      ' +\n '
      ' +\n '
      ' +\n '' +\n '' +\n '
      ',\n controller: 'ConfirmModalController',\n defaultLabels: {\n title: 'Confirm',\n ok: 'OK',\n cancel: 'Cancel'\n }\n })\n .factory('$confirm', ['$modal', '$confirmModalDefaults', function ($modal, $confirmModalDefaults) {\n return function (data, settings) {\n settings = angular.extend($confirmModalDefaults, (settings || {}));\n\n data = angular.extend({}, settings.defaultLabels, data || {});\n\n if ('templateUrl' in settings && 'template' in settings) {\n delete settings.template;\n }\n\n settings.resolve = {\n data: function () {\n return data;\n }\n };\n\n return $modal.open(settings).result;\n };\n }])\n .directive('confirm', ['$confirm', function ($confirm) {\n return {\n priority: 1,\n restrict: 'A',\n scope: {\n confirmIf: \"=\",\n ngClick: '&',\n confirm: '@',\n confirmSettings: \"=\",\n confirmTitle: '@',\n confirmOk: '@',\n confirmCancel: '@'\n },\n link: function (scope, element, attrs) {\n\n\n element.unbind(\"click\").bind(\"click\", function ($event) {\n\n $event.preventDefault();\n\n if (angular.isUndefined(scope.confirmIf) || scope.confirmIf) {\n\n var data = {text: scope.confirm};\n if (scope.confirmTitle) {\n data.title = scope.confirmTitle;\n }\n if (scope.confirmOk) {\n data.ok = scope.confirmOk;\n }\n if (scope.confirmCancel) {\n data.cancel = scope.confirmCancel;\n }\n $confirm(data, scope.confirmSettings || {}).then(scope.ngClick);\n } else {\n\n scope.$apply(scope.ngClick);\n }\n });\n\n }\n }\n }]);\n","/*! ui-grid - v - 2014-09-17\n* Copyright (c) 2014 ; License: MIT */\n(function () {\n 'use strict';\n angular.module('ui.grid.i18n', []);\n angular.module('ui.grid', ['ui.grid.i18n']);\n})();\n(function () {\n 'use strict';\n angular.module('ui.grid').constant('uiGridConstants', {\n CUSTOM_FILTERS: /CUSTOM_FILTERS/g,\n COL_FIELD: /COL_FIELD/g,\n DISPLAY_CELL_TEMPLATE: /DISPLAY_CELL_TEMPLATE/g,\n TEMPLATE_REGEXP: /<.+>/,\n FUNC_REGEXP: /(\\([^)]*\\))?$/,\n DOT_REGEXP: /\\./g,\n APOS_REGEXP: /'/g,\n BRACKET_REGEXP: /^(.*)((?:\\s*\\[\\s*\\d+\\s*\\]\\s*)|(?:\\s*\\[\\s*\"(?:[^\"\\\\]|\\\\.)*\"\\s*\\]\\s*)|(?:\\s*\\[\\s*'(?:[^'\\\\]|\\\\.)*'\\s*\\]\\s*))(.*)$/,\n COL_CLASS_PREFIX: 'ui-grid-col',\n events: {\n GRID_SCROLL: 'uiGridScroll',\n COLUMN_MENU_SHOWN: 'uiGridColMenuShown',\n ITEM_DRAGGING: 'uiGridItemDragStart' // For any item being dragged\n },\n // copied from http://www.lsauer.com/2011/08/javascript-keymap-keycodes-in-json.html\n keymap: {\n TAB: 9,\n STRG: 17,\n CTRL: 17,\n CTRLRIGHT: 18,\n CTRLR: 18,\n SHIFT: 16,\n RETURN: 13,\n ENTER: 13,\n BACKSPACE: 8,\n BCKSP: 8,\n ALT: 18,\n ALTR: 17,\n ALTRIGHT: 17,\n SPACE: 32,\n WIN: 91,\n MAC: 91,\n FN: null,\n UP: 38,\n DOWN: 40,\n LEFT: 37,\n RIGHT: 39,\n ESC: 27,\n DEL: 46,\n F1: 112,\n F2: 113,\n F3: 114,\n F4: 115,\n F5: 116,\n F6: 117,\n F7: 118,\n F8: 119,\n F9: 120,\n F10: 121,\n F11: 122,\n F12: 123\n },\n ASC: 'asc',\n DESC: 'desc',\n filter: {\n STARTS_WITH: 2,\n ENDS_WITH: 4,\n EXACT: 8,\n CONTAINS: 16,\n GREATER_THAN: 32,\n GREATER_THAN_OR_EQUAL: 64,\n LESS_THAN: 128,\n LESS_THAN_OR_EQUAL: 256,\n NOT_EQUAL: 512\n },\n\n aggregationTypes: {\n sum: 2,\n count: 4,\n avg: 8,\n min: 16,\n max: 32\n },\n\n // TODO(c0bra): Create full list of these somehow. NOTE: do any allow a space before or after them?\n CURRENCY_SYMBOLS: ['ƒ', '$', '£', '$', '¤', '¥', '៛', '₩', '₱', '฿', '₫']\n });\n\n})();\nangular.module('ui.grid').directive('uiGridCell', ['$compile', '$log', '$parse', 'gridUtil', 'uiGridConstants', function ($compile, $log, $parse, gridUtil, uiGridConstants) {\n var uiGridCell = {\n priority: 0,\n scope: false,\n require: '?^uiGrid',\n compile: function() {\n return {\n pre: function($scope, $elm, $attrs, uiGridCtrl) {\n function compileTemplate() {\n var compiledElementFn = $scope.col.compiledElementFn;\n\n compiledElementFn($scope, function(clonedElement, scope) {\n $elm.append(clonedElement);\n });\n }\n\n // If the grid controller is present, use it to get the compiled cell template function\n if (uiGridCtrl) {\n compileTemplate();\n }\n // No controller, compile the element manually (for unit tests)\n else {\n var html = $scope.col.cellTemplate\n .replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)');\n var cellElement = $compile(html)($scope);\n $elm.append(cellElement);\n }\n },\n post: function($scope, $elm, $attrs, uiGridCtrl) {\n $elm.addClass($scope.col.getColClass(false));\n if ($scope.col.cellClass) {\n //var contents = angular.element($elm[0].getElementsByClassName('ui-grid-cell-contents'));\n var contents = $elm;\n if (angular.isFunction($scope.col.cellClass)) {\n contents.addClass($scope.col.cellClass($scope.grid, $scope.row, $scope.col, $scope.rowRenderIndex, $scope.colRenderIndex));\n }\n else {\n contents.addClass($scope.col.cellClass);\n }\n }\n }\n };\n }\n };\n\n return uiGridCell;\n}]);\n\n\n(function(){\n\nangular.module('ui.grid').directive('uiGridColumnMenu', ['$log', '$timeout', '$window', '$document', '$injector', 'gridUtil', 'uiGridConstants', 'i18nService', function ($log, $timeout, $window, $document, $injector, gridUtil, uiGridConstants, i18nService) {\n\n var uiGridColumnMenu = {\n priority: 0,\n scope: true,\n require: '?^uiGrid',\n templateUrl: 'ui-grid/uiGridColumnMenu',\n replace: true,\n link: function ($scope, $elm, $attrs, uiGridCtrl) {\n gridUtil.enableAnimations($elm);\n\n $scope.grid = uiGridCtrl.grid;\n\n var self = this;\n\n // Store a reference to this link/controller in the main uiGrid controller\n // to allow showMenu later\n uiGridCtrl.columnMenuScope = $scope;\n\n // Save whether we're shown or not so the columns can check\n self.shown = $scope.menuShown = false;\n\n // Put asc and desc sort directions in scope\n $scope.asc = uiGridConstants.ASC;\n $scope.desc = uiGridConstants.DESC;\n\n // $scope.i18n = i18nService;\n\n // Get the grid menu element. We'll use it to calculate positioning\n $scope.menu = $elm[0].querySelectorAll('.ui-grid-menu');\n\n // Get the inner menu part. It's what slides up/down\n $scope.inner = $elm[0].querySelectorAll('.ui-grid-menu-inner');\n\n /**\n * @ngdoc boolean\n * @name enableSorting\n * @propertyOf ui.grid.class:GridOptions.columnDef\n * @description (optional) True by default. When enabled, this setting adds sort\n * widgets to the column header, allowing sorting of the data in the individual column.\n */\n $scope.sortable = function() {\n if (uiGridCtrl.grid.options.enableSorting && typeof($scope.col) !== 'undefined' && $scope.col && $scope.col.enableSorting) {\n return true;\n }\n else {\n return false;\n }\n };\n\n /**\n * @ngdoc boolean\n * @name enableFiltering\n * @propertyOf ui.grid.class:GridOptions.columnDef\n * @description (optional) True by default. When enabled, this setting adds filter\n * widgets to the column header, allowing filtering of the data in the individual column.\n */\n $scope.filterable = function() {\n if (uiGridCtrl.grid.options.enableFiltering && typeof($scope.col) !== 'undefined' && $scope.col && $scope.col.enableFiltering) {\n return true;\n }\n else {\n return false;\n }\n };\n \n var defaultMenuItems = [\n // NOTE: disabling this in favor of a little filter text box\n // Column filter input\n // {\n // templateUrl: 'ui-grid/uiGridColumnFilter',\n // action: function($event) {\n // $event.stopPropagation();\n // $scope.filterColumn($event);\n // },\n // cancel: function ($event) {\n // $event.stopPropagation();\n\n // $scope.col.filter = {};\n // },\n // shown: function () {\n // return filterable();\n // }\n // },\n {\n title: i18nService.getSafeText('sort.ascending'),\n icon: 'ui-grid-icon-sort-alt-up',\n action: function($event) {\n $event.stopPropagation();\n $scope.sortColumn($event, uiGridConstants.ASC);\n },\n shown: function () {\n return $scope.sortable();\n },\n active: function() {\n return (typeof($scope.col) !== 'undefined' && typeof($scope.col.sort) !== 'undefined' && typeof($scope.col.sort.direction) !== 'undefined' && $scope.col.sort.direction === uiGridConstants.ASC);\n }\n },\n {\n title: i18nService.getSafeText('sort.descending'),\n icon: 'ui-grid-icon-sort-alt-down',\n action: function($event) {\n $event.stopPropagation();\n $scope.sortColumn($event, uiGridConstants.DESC);\n },\n shown: function() {\n return $scope.sortable();\n },\n active: function() {\n return (typeof($scope.col) !== 'undefined' && typeof($scope.col.sort) !== 'undefined' && typeof($scope.col.sort.direction) !== 'undefined' && $scope.col.sort.direction === uiGridConstants.DESC);\n }\n },\n {\n title: i18nService.getSafeText('sort.remove'),\n icon: 'ui-grid-icon-cancel',\n action: function ($event) {\n $event.stopPropagation();\n $scope.unsortColumn();\n },\n shown: function() {\n return ($scope.sortable() && typeof($scope.col) !== 'undefined' && (typeof($scope.col.sort) !== 'undefined' && typeof($scope.col.sort.direction) !== 'undefined') && $scope.col.sort.direction !== null);\n }\n },\n {\n title: i18nService.getSafeText('column.hide'),\n icon: 'ui-grid-icon-cancel',\n action: function ($event) {\n $event.stopPropagation();\n $scope.hideColumn();\n }\n }\n ];\n\n // Set the menu items for use with the column menu. Let's the user specify extra menu items per column if they want.\n $scope.menuItems = defaultMenuItems;\n $scope.$watch('col.menuItems', function (n, o) {\n if (typeof(n) !== 'undefined' && n && angular.isArray(n)) {\n n.forEach(function (item) {\n if (typeof(item.context) === 'undefined' || !item.context) {\n item.context = {};\n }\n item.context.col = $scope.col;\n });\n\n $scope.menuItems = defaultMenuItems.concat(n);\n }\n else {\n $scope.menuItems = defaultMenuItems;\n }\n });\n\n var $animate;\n try {\n $animate = $injector.get('$animate');\n }\n catch (e) {\n $log.info('$animate service not found (ngAnimate not add as a dependency?), menu animations will not occur');\n }\n\n // Show the menu\n $scope.showMenu = function(column, $columnElement) {\n // Swap to this column\n // note - store a reference to this column in 'self' so the columns can check whether they're the shown column or not\n self.col = $scope.col = column;\n\n // Remove an existing document click handler\n $document.off('click', documentClick);\n\n /* Reposition the menu below this column's element */\n var left = $columnElement[0].offsetLeft;\n var top = $columnElement[0].offsetTop;\n\n // Get the grid scrollLeft\n var offset = 0;\n if (column.grid.options.offsetLeft) {\n offset = column.grid.options.offsetLeft;\n }\n\n var height = gridUtil.elementHeight($columnElement, true);\n var width = gridUtil.elementWidth($columnElement, true);\n\n // Flag for whether we're hidden for showing via $animate\n var hidden = false;\n\n // Re-position the menu AFTER it's been shown, so we can calculate the width correctly.\n function reposition() {\n $timeout(function() {\n if (hidden && $animate) {\n $animate.removeClass($scope.inner, 'ng-hide');\n self.shown = $scope.menuShown = true;\n $scope.$broadcast('show-menu');\n }\n else if (angular.element($scope.inner).hasClass('ng-hide')) {\n angular.element($scope.inner).removeClass('ng-hide');\n }\n\n // var containerScrollLeft = $columnelement\n var containerId = column.renderContainer ? column.renderContainer : 'body';\n var renderContainer = column.grid.renderContainers[containerId];\n var containerScrolLeft = renderContainer.prevScrollLeft;\n\n var myWidth = gridUtil.elementWidth($scope.menu, true);\n\n // TODO(c0bra): use padding-left/padding-right based on document direction (ltr/rtl), place menu on proper side\n // Get the column menu right padding\n var paddingRight = parseInt(angular.element($scope.menu).css('padding-right'), 10);\n\n $log.debug('position', left + ' + ' + width + ' - ' + myWidth + ' + ' + paddingRight);\n\n // $elm.css('left', (left - offset + width - myWidth + paddingRight) + 'px');\n // $elm.css('left', (left + width - myWidth + paddingRight) + 'px');\n $elm.css('left', (left - containerScrolLeft + width - myWidth + paddingRight) + 'px');\n $elm.css('top', (top + height) + 'px');\n\n // Hide the menu on a click on the document\n $document.on('click', documentClick);\n });\n }\n\n if ($scope.menuShown && $animate) {\n // Animate closing the menu on the current column, then animate it opening on the other column\n $animate.addClass($scope.inner, 'ng-hide', reposition);\n hidden = true;\n }\n else {\n self.shown = $scope.menuShown = true;\n $scope.$broadcast('show-menu');\n reposition();\n }\n };\n\n // Hide the menu\n $scope.hideMenu = function() {\n delete self.col;\n delete $scope.col;\n self.shown = $scope.menuShown = false;\n $scope.$broadcast('hide-menu');\n };\n\n // Prevent clicks on the menu from bubbling up to the document and making it hide prematurely\n // $elm.on('click', function (event) {\n // event.stopPropagation();\n // });\n\n function documentClick() {\n $scope.$apply($scope.hideMenu);\n $document.off('click', documentClick);\n }\n \n function resizeHandler() {\n $scope.$apply($scope.hideMenu);\n }\n angular.element($window).bind('resize', resizeHandler);\n\n $scope.$on('$destroy', $scope.$on(uiGridConstants.events.GRID_SCROLL, function(evt, args) {\n $scope.hideMenu();\n // if (!$scope.$$phase) { $scope.$apply(); }\n }));\n\n $scope.$on('$destroy', $scope.$on(uiGridConstants.events.ITEM_DRAGGING, function(evt, args) {\n $scope.hideMenu();\n // if (!$scope.$$phase) { $scope.$apply(); }\n }));\n\n $scope.$on('$destroy', function() {\n angular.element($window).off('resize', resizeHandler);\n $document.off('click', documentClick);\n });\n\n /* Column methods */\n $scope.sortColumn = function (event, dir) {\n event.stopPropagation();\n\n uiGridCtrl.grid.sortColumn($scope.col, dir, true)\n .then(function () {\n uiGridCtrl.grid.refresh();\n $scope.hideMenu();\n });\n };\n\n $scope.unsortColumn = function () {\n $scope.col.unsort();\n\n uiGridCtrl.grid.refresh();\n $scope.hideMenu();\n };\n\n $scope.hideColumn = function () {\n $scope.col.colDef.visible = false;\n\n uiGridCtrl.grid.refresh();\n $scope.hideMenu();\n };\n },\n controller: ['$scope', function ($scope) {\n var self = this;\n \n $scope.$watch('menuItems', function (n, o) {\n self.menuItems = n;\n });\n }]\n };\n\n return uiGridColumnMenu;\n\n}]);\n\n})();\n(function () {\n 'use strict';\n\n angular.module('ui.grid').directive('uiGridFooterCell', ['$log', '$timeout', 'gridUtil', '$compile', function ($log, $timeout, gridUtil, $compile) {\n var uiGridFooterCell = {\n priority: 0,\n scope: {\n col: '=',\n row: '=',\n renderIndex: '='\n },\n replace: true,\n require: '^uiGrid',\n compile: function compile(tElement, tAttrs, transclude) {\n return {\n pre: function ($scope, $elm, $attrs, uiGridCtrl) {\n function compileTemplate(template) {\n gridUtil.getTemplate(template).then(function (contents) {\n var linkFunction = $compile(contents);\n var html = linkFunction($scope);\n $elm.append(html);\n });\n }\n\n //compile the footer template\n if ($scope.col.footerCellTemplate) {\n //compile the custom template\n compileTemplate($scope.col.footerCellTemplate);\n }\n else {\n //use default template\n compileTemplate('ui-grid/uiGridFooterCell');\n }\n },\n post: function ($scope, $elm, $attrs, uiGridCtrl) {\n //$elm.addClass($scope.col.getColClass(false));\n $scope.grid = uiGridCtrl.grid;\n }\n };\n }\n };\n\n return uiGridFooterCell;\n }]);\n\n})();\n\n(function () {\n 'use strict';\n\n angular.module('ui.grid').directive('uiGridFooter', ['$log', '$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', function ($log, $templateCache, $compile, uiGridConstants, gridUtil, $timeout) {\n var defaultTemplate = 'ui-grid/ui-grid-footer';\n\n return {\n restrict: 'EA',\n replace: true,\n // priority: 1000,\n require: ['^uiGrid', '^uiGridRenderContainer'],\n scope: true,\n compile: function ($elm, $attrs) {\n return {\n pre: function ($scope, $elm, $attrs, controllers) {\n var uiGridCtrl = controllers[0];\n var containerCtrl = controllers[1];\n\n $scope.grid = uiGridCtrl.grid;\n $scope.colContainer = containerCtrl.colContainer;\n\n containerCtrl.footer = $elm;\n\n var footerTemplate = ($scope.grid.options.footerTemplate) ? $scope.grid.options.footerTemplate : defaultTemplate;\n gridUtil.getTemplate(footerTemplate)\n .then(function (contents) {\n var template = angular.element(contents);\n\n var newElm = $compile(template)($scope);\n $elm.append(newElm);\n\n if (containerCtrl) {\n // Inject a reference to the footer viewport (if it exists) into the grid controller for use in the horizontal scroll handler below\n var footerViewport = $elm[0].getElementsByClassName('ui-grid-footer-viewport')[0];\n\n if (footerViewport) {\n containerCtrl.footerViewport = footerViewport;\n }\n }\n });\n },\n\n post: function ($scope, $elm, $attrs, controllers) {\n var uiGridCtrl = controllers[0];\n var containerCtrl = controllers[1];\n\n $log.debug('ui-grid-footer link');\n\n var grid = uiGridCtrl.grid;\n\n // Don't animate footer cells\n gridUtil.disableAnimations($elm);\n\n function updateColumnWidths() {\n var asterisksArray = [],\n percentArray = [],\n manualArray = [],\n asteriskNum = 0,\n totalWidth = 0;\n\n // Get the width of the viewport\n var availableWidth = containerCtrl.colContainer.getViewportWidth();\n\n if (typeof(uiGridCtrl.grid.verticalScrollbarWidth) !== 'undefined' && uiGridCtrl.grid.verticalScrollbarWidth !== undefined && uiGridCtrl.grid.verticalScrollbarWidth > 0) {\n availableWidth = availableWidth + uiGridCtrl.grid.verticalScrollbarWidth;\n }\n\n // The total number of columns\n // var equalWidthColumnCount = columnCount = uiGridCtrl.grid.options.columnDefs.length;\n // var equalWidth = availableWidth / equalWidthColumnCount;\n\n // The last column we processed\n var lastColumn;\n\n var manualWidthSum = 0;\n\n var canvasWidth = 0;\n\n var ret = '';\n\n\n // uiGridCtrl.grid.columns.forEach(function(column, i) {\n\n var columnCache = containerCtrl.colContainer.visibleColumnCache;\n\n columnCache.forEach(function (column, i) {\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + i + ' { width: ' + equalWidth + 'px; left: ' + left + 'px; }';\n //var colWidth = (typeof(c.width) !== 'undefined' && c.width !== undefined) ? c.width : equalWidth;\n\n // Skip hidden columns\n if (!column.visible) {\n return;\n }\n\n var colWidth,\n isPercent = false;\n\n if (!angular.isNumber(column.width)) {\n isPercent = isNaN(column.width) ? gridUtil.endsWith(column.width, \"%\") : false;\n }\n\n if (angular.isString(column.width) && column.width.indexOf('*') !== -1) { // we need to save it until the end to do the calulations on the remaining width.\n asteriskNum = parseInt(asteriskNum + column.width.length, 10);\n\n asterisksArray.push(column);\n }\n else if (isPercent) { // If the width is a percentage, save it until the very last.\n percentArray.push(column);\n }\n else if (angular.isNumber(column.width)) {\n manualWidthSum = parseInt(manualWidthSum + column.width, 10);\n\n canvasWidth = parseInt(canvasWidth, 10) + parseInt(column.width, 10);\n\n column.drawnWidth = column.width;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + column.width + 'px; }';\n }\n });\n\n // Get the remaining width (available width subtracted by the manual widths sum)\n var remainingWidth = availableWidth - manualWidthSum;\n\n var i, column, colWidth;\n\n if (percentArray.length > 0) {\n // Pre-process to make sure they're all within any min/max values\n for (i = 0; i < percentArray.length; i++) {\n column = percentArray[i];\n\n var percent = parseInt(column.width.replace(/%/g, ''), 10) / 100;\n\n colWidth = parseInt(percent * remainingWidth, 10);\n\n if (column.colDef.minWidth && colWidth < column.colDef.minWidth) {\n colWidth = column.colDef.minWidth;\n\n remainingWidth = remainingWidth - colWidth;\n\n canvasWidth += colWidth;\n column.drawnWidth = colWidth;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + colWidth + 'px; }';\n\n // Remove this element from the percent array so it's not processed below\n percentArray.splice(i, 1);\n }\n else if (column.colDef.maxWidth && colWidth > column.colDef.maxWidth) {\n colWidth = column.colDef.maxWidth;\n\n remainingWidth = remainingWidth - colWidth;\n\n canvasWidth += colWidth;\n column.drawnWidth = colWidth;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + colWidth + 'px; }';\n\n // Remove this element from the percent array so it's not processed below\n percentArray.splice(i, 1);\n }\n }\n\n percentArray.forEach(function (column) {\n var percent = parseInt(column.width.replace(/%/g, ''), 10) / 100;\n var colWidth = parseInt(percent * remainingWidth, 10);\n\n canvasWidth += colWidth;\n\n column.drawnWidth = colWidth;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + colWidth + 'px; }';\n });\n }\n\n if (asterisksArray.length > 0) {\n var asteriskVal = parseInt(remainingWidth / asteriskNum, 10);\n\n // Pre-process to make sure they're all within any min/max values\n for (i = 0; i < asterisksArray.length; i++) {\n column = asterisksArray[i];\n\n colWidth = parseInt(asteriskVal * column.width.length, 10);\n\n if (column.colDef.minWidth && colWidth < column.colDef.minWidth) {\n colWidth = column.colDef.minWidth;\n\n remainingWidth = remainingWidth - colWidth;\n asteriskNum--;\n\n canvasWidth += colWidth;\n column.drawnWidth = colWidth;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + colWidth + 'px; }';\n\n lastColumn = column;\n\n // Remove this element from the percent array so it's not processed below\n asterisksArray.splice(i, 1);\n }\n else if (column.colDef.maxWidth && colWidth > column.colDef.maxWidth) {\n colWidth = column.colDef.maxWidth;\n\n remainingWidth = remainingWidth - colWidth;\n asteriskNum--;\n\n canvasWidth += colWidth;\n column.drawnWidth = colWidth;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + colWidth + 'px; }';\n\n // Remove this element from the percent array so it's not processed below\n asterisksArray.splice(i, 1);\n }\n }\n\n // Redo the asterisk value, as we may have removed columns due to width constraints\n asteriskVal = parseInt(remainingWidth / asteriskNum, 10);\n\n asterisksArray.forEach(function (column) {\n var colWidth = parseInt(asteriskVal * column.width.length, 10);\n\n canvasWidth += colWidth;\n\n column.drawnWidth = colWidth;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + colWidth + 'px; }';\n });\n }\n\n // If the grid width didn't divide evenly into the column widths and we have pixels left over, dole them out to the columns one by one to make everything fit\n var leftoverWidth = availableWidth - parseInt(canvasWidth, 10);\n\n if (leftoverWidth > 0 && canvasWidth > 0 && canvasWidth < availableWidth) {\n var variableColumn = false;\n // uiGridCtrl.grid.columns.forEach(function(col) {\n columnCache.forEach(function (col) {\n if (col.width && !angular.isNumber(col.width)) {\n variableColumn = true;\n }\n });\n\n if (variableColumn) {\n var remFn = function (column) {\n if (leftoverWidth > 0) {\n column.drawnWidth = column.drawnWidth + 1;\n canvasWidth = canvasWidth + 1;\n leftoverWidth--;\n }\n };\n while (leftoverWidth > 0) {\n columnCache.forEach(remFn);\n }\n }\n }\n\n if (canvasWidth < availableWidth) {\n canvasWidth = availableWidth;\n }\n\n // Build the CSS\n // uiGridCtrl.grid.columns.forEach(function (column) {\n columnCache.forEach(function (column) {\n ret = ret + column.getColClassDefinition();\n });\n\n // Add the vertical scrollbar width back in to the canvas width, it's taken out in getCanvasWidth\n if (grid.verticalScrollbarWidth) {\n canvasWidth = canvasWidth + grid.verticalScrollbarWidth;\n }\n // canvasWidth = canvasWidth + 1;\n\n containerCtrl.colContainer.canvasWidth = parseInt(canvasWidth, 10);\n\n // Return the styles back to buildStyles which pops them into the `customStyles` scope variable\n return ret;\n }\n\n containerCtrl.footer = $elm;\n\n var footerViewport = $elm[0].getElementsByClassName('ui-grid-footer-viewport')[0];\n if (footerViewport) {\n containerCtrl.footerViewport = footerViewport;\n }\n\n //todo: remove this if by injecting gridCtrl into unit tests\n if (uiGridCtrl) {\n uiGridCtrl.grid.registerStyleComputation({\n priority: 5,\n func: updateColumnWidths\n });\n }\n }\n };\n }\n };\n }]);\n\n})();\n(function(){\n 'use strict';\n\n angular.module('ui.grid').directive('uiGridGroupPanel', [\"$compile\", \"uiGridConstants\", \"gridUtil\", function($compile, uiGridConstants, gridUtil) {\n var defaultTemplate = 'ui-grid/ui-grid-group-panel';\n\n return {\n restrict: 'EA',\n replace: true,\n require: '?^uiGrid',\n scope: false,\n compile: function($elm, $attrs) {\n return {\n pre: function ($scope, $elm, $attrs, uiGridCtrl) {\n var groupPanelTemplate = $scope.grid.options.groupPanelTemplate || defaultTemplate;\n\n gridUtil.getTemplate(groupPanelTemplate)\n .then(function (contents) {\n var template = angular.element(contents);\n \n var newElm = $compile(template)($scope);\n $elm.append(newElm);\n });\n },\n\n post: function ($scope, $elm, $attrs, uiGridCtrl) {\n $elm.bind('$destroy', function() {\n // scrollUnbinder();\n });\n }\n };\n }\n };\n }]);\n\n})();\n(function(){\n 'use strict';\n\n angular.module('ui.grid').directive('uiGridHeaderCell', ['$log', '$compile', '$timeout', '$window', '$document', 'gridUtil', 'uiGridConstants', \n function ($log, $compile, $timeout, $window, $document, gridUtil, uiGridConstants) {\n // Do stuff after mouse has been down this many ms on the header cell\n var mousedownTimeout = 500;\n\n var uiGridHeaderCell = {\n priority: 0,\n scope: {\n col: '=',\n row: '=',\n renderIndex: '='\n },\n require: '?^uiGrid',\n replace: true,\n compile: function() {\n return {\n pre: function ($scope, $elm, $attrs, uiGridCtrl) {\n var cellHeader = $compile($scope.col.headerCellTemplate)($scope);\n $elm.append(cellHeader);\n },\n \n post: function ($scope, $elm, $attrs, uiGridCtrl) {\n $scope.grid = uiGridCtrl.grid;\n \n $elm.addClass($scope.col.getColClass(false));\n // shane - No need for watch now that we trackby col name\n // $scope.$watch('col.index', function (newValue, oldValue) {\n // if (newValue === oldValue) { return; }\n // var className = $elm.attr('class');\n // className = className.replace(uiGridConstants.COL_CLASS_PREFIX + oldValue, uiGridConstants.COL_CLASS_PREFIX + newValue);\n // $elm.attr('class', className);\n // });\n \n // Hide the menu by default\n $scope.menuShown = false;\n \n // Put asc and desc sort directions in scope\n $scope.asc = uiGridConstants.ASC;\n $scope.desc = uiGridConstants.DESC;\n \n // Store a reference to menu element\n var $colMenu = angular.element( $elm[0].querySelectorAll('.ui-grid-header-cell-menu') );\n \n var $contentsElm = angular.element( $elm[0].querySelectorAll('.ui-grid-cell-contents') );\n \n // Figure out whether this column is sortable or not\n if (uiGridCtrl.grid.options.enableSorting && $scope.col.enableSorting) {\n $scope.sortable = true;\n }\n else {\n $scope.sortable = false;\n }\n \n if (uiGridCtrl.grid.options.enableFiltering && $scope.col.enableFiltering) {\n $scope.filterable = true;\n }\n else {\n $scope.filterable = false;\n }\n \n function handleClick(evt) {\n // If the shift key is being held down, add this column to the sort\n var add = false;\n if (evt.shiftKey) {\n add = true;\n }\n \n // Sort this column then rebuild the grid's rows\n uiGridCtrl.grid.sortColumn($scope.col, add)\n .then(function () {\n uiGridCtrl.columnMenuScope.hideMenu();\n uiGridCtrl.grid.refresh();\n });\n }\n \n // Long-click (for mobile)\n var cancelMousedownTimeout;\n var mousedownStartTime = 0;\n $contentsElm.on('mousedown', function(event) {\n if (typeof(event.originalEvent) !== 'undefined' && event.originalEvent !== undefined) {\n event = event.originalEvent;\n }\n \n // Don't show the menu if it's not the left button\n if (event.button && event.button !== 0) {\n return;\n }\n \n mousedownStartTime = (new Date()).getTime();\n \n cancelMousedownTimeout = $timeout(function() { }, mousedownTimeout);\n \n cancelMousedownTimeout.then(function () {\n uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm);\n });\n });\n \n $contentsElm.on('mouseup', function () {\n $timeout.cancel(cancelMousedownTimeout);\n });\n \n $scope.toggleMenu = function($event) {\n $event.stopPropagation();\n \n // If the menu is already showing...\n if (uiGridCtrl.columnMenuScope.menuShown) {\n // ... and we're the column the menu is on...\n if (uiGridCtrl.columnMenuScope.col === $scope.col) {\n // ... hide it\n uiGridCtrl.columnMenuScope.hideMenu();\n }\n // ... and we're NOT the column the menu is on\n else {\n // ... move the menu to our column\n uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm);\n }\n }\n // If the menu is NOT showing\n else {\n // ... show it on our column\n uiGridCtrl.columnMenuScope.showMenu($scope.col, $elm);\n }\n };\n \n // If this column is sortable, add a click event handler\n if ($scope.sortable) {\n $contentsElm.on('click', function(evt) {\n evt.stopPropagation();\n \n $timeout.cancel(cancelMousedownTimeout);\n \n var mousedownEndTime = (new Date()).getTime();\n var mousedownTime = mousedownEndTime - mousedownStartTime;\n \n if (mousedownTime > mousedownTimeout) {\n // long click, handled above with mousedown\n }\n else {\n // short click\n handleClick(evt);\n }\n });\n \n $scope.$on('$destroy', function () {\n // Cancel any pending long-click timeout\n $timeout.cancel(cancelMousedownTimeout);\n });\n }\n \n if ($scope.filterable) {\n $scope.$on('$destroy', $scope.$watch('col.filter.term', function(n, o) {\n uiGridCtrl.grid.refresh()\n .then(function () {\n if (uiGridCtrl.prevScrollArgs && uiGridCtrl.prevScrollArgs.y && uiGridCtrl.prevScrollArgs.y.percentage) {\n uiGridCtrl.fireScrollingEvent({ y: { percentage: uiGridCtrl.prevScrollArgs.y.percentage } });\n }\n // uiGridCtrl.fireEvent('force-vertical-scroll');\n });\n }));\n }\n }\n };\n }\n };\n\n return uiGridHeaderCell;\n }]);\n\n})();\n(function(){\n 'use strict';\n\n angular.module('ui.grid').directive('uiGridHeader', ['$log', '$templateCache', '$compile', 'uiGridConstants', 'gridUtil', '$timeout', function($log, $templateCache, $compile, uiGridConstants, gridUtil, $timeout) {\n var defaultTemplate = 'ui-grid/ui-grid-header';\n var emptyTemplate = 'ui-grid/ui-grid-no-header';\n\n return {\n restrict: 'EA',\n // templateUrl: 'ui-grid/ui-grid-header',\n replace: true,\n // priority: 1000,\n require: ['^uiGrid', '^uiGridRenderContainer'],\n scope: true,\n compile: function($elm, $attrs) {\n return {\n pre: function ($scope, $elm, $attrs, controllers) {\n var uiGridCtrl = controllers[0];\n var containerCtrl = controllers[1];\n\n $scope.grid = uiGridCtrl.grid;\n $scope.colContainer = containerCtrl.colContainer;\n\n containerCtrl.header = $elm;\n containerCtrl.colContainer.header = $elm;\n\n /**\n * @ngdoc property\n * @name hideHeader\n * @propertyOf ui.grid.class:GridOptions\n * @description Null by default. When set to true, this setting will replace the\n * standard header template with '
      ', resulting in no header being shown.\n */\n \n var headerTemplate;\n if ($scope.grid.options.hideHeader){\n headerTemplate = emptyTemplate;\n } else {\n headerTemplate = ($scope.grid.options.headerTemplate) ? $scope.grid.options.headerTemplate : defaultTemplate; \n }\n\n gridUtil.getTemplate(headerTemplate)\n .then(function (contents) {\n var template = angular.element(contents);\n \n var newElm = $compile(template)($scope);\n $elm.append(newElm);\n\n if (containerCtrl) {\n // Inject a reference to the header viewport (if it exists) into the grid controller for use in the horizontal scroll handler below\n var headerViewport = $elm[0].getElementsByClassName('ui-grid-header-viewport')[0];\n\n if (headerViewport) {\n containerCtrl.headerViewport = headerViewport;\n }\n }\n });\n },\n\n post: function ($scope, $elm, $attrs, controllers) {\n var uiGridCtrl = controllers[0];\n var containerCtrl = controllers[1];\n\n $log.debug('ui-grid-header link');\n\n var grid = uiGridCtrl.grid;\n\n // Don't animate header cells\n gridUtil.disableAnimations($elm);\n\n function updateColumnWidths() {\n var asterisksArray = [],\n percentArray = [],\n manualArray = [],\n asteriskNum = 0,\n totalWidth = 0;\n\n // Get the width of the viewport\n var availableWidth = containerCtrl.colContainer.getViewportWidth();\n\n if (typeof(uiGridCtrl.grid.verticalScrollbarWidth) !== 'undefined' && uiGridCtrl.grid.verticalScrollbarWidth !== undefined && uiGridCtrl.grid.verticalScrollbarWidth > 0) {\n availableWidth = availableWidth + uiGridCtrl.grid.verticalScrollbarWidth;\n }\n\n // The total number of columns\n // var equalWidthColumnCount = columnCount = uiGridCtrl.grid.options.columnDefs.length;\n // var equalWidth = availableWidth / equalWidthColumnCount;\n\n // The last column we processed\n var lastColumn;\n\n var manualWidthSum = 0;\n\n var canvasWidth = 0;\n\n var ret = '';\n\n\n // uiGridCtrl.grid.columns.forEach(function(column, i) {\n\n var columnCache = containerCtrl.colContainer.visibleColumnCache;\n\n columnCache.forEach(function(column, i) {\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + i + ' { width: ' + equalWidth + 'px; left: ' + left + 'px; }';\n //var colWidth = (typeof(c.width) !== 'undefined' && c.width !== undefined) ? c.width : equalWidth;\n\n // Skip hidden columns\n if (!column.visible) { return; }\n\n var colWidth,\n isPercent = false;\n\n if (!angular.isNumber(column.width)) {\n isPercent = isNaN(column.width) ? gridUtil.endsWith(column.width, \"%\") : false;\n }\n\n if (angular.isString(column.width) && column.width.indexOf('*') !== -1) { // we need to save it until the end to do the calulations on the remaining width.\n asteriskNum = parseInt(asteriskNum + column.width.length, 10);\n \n asterisksArray.push(column);\n }\n else if (isPercent) { // If the width is a percentage, save it until the very last.\n percentArray.push(column);\n }\n else if (angular.isNumber(column.width)) {\n manualWidthSum = parseInt(manualWidthSum + column.width, 10);\n \n canvasWidth = parseInt(canvasWidth, 10) + parseInt(column.width, 10);\n\n column.drawnWidth = column.width;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + column.width + 'px; }';\n }\n });\n\n // Get the remaining width (available width subtracted by the manual widths sum)\n var remainingWidth = availableWidth - manualWidthSum;\n\n var i, column, colWidth;\n\n if (percentArray.length > 0) {\n // Pre-process to make sure they're all within any min/max values\n for (i = 0; i < percentArray.length; i++) {\n column = percentArray[i];\n\n var percent = parseInt(column.width.replace(/%/g, ''), 10) / 100;\n\n colWidth = parseInt(percent * remainingWidth, 10);\n\n if (column.colDef.minWidth && colWidth < column.colDef.minWidth) {\n colWidth = column.colDef.minWidth;\n\n remainingWidth = remainingWidth - colWidth;\n\n canvasWidth += colWidth;\n column.drawnWidth = colWidth;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + colWidth + 'px; }';\n\n // Remove this element from the percent array so it's not processed below\n percentArray.splice(i, 1);\n }\n else if (column.colDef.maxWidth && colWidth > column.colDef.maxWidth) {\n colWidth = column.colDef.maxWidth;\n\n remainingWidth = remainingWidth - colWidth;\n\n canvasWidth += colWidth;\n column.drawnWidth = colWidth;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + colWidth + 'px; }';\n\n // Remove this element from the percent array so it's not processed below\n percentArray.splice(i, 1);\n }\n }\n\n percentArray.forEach(function(column) {\n var percent = parseInt(column.width.replace(/%/g, ''), 10) / 100;\n var colWidth = parseInt(percent * remainingWidth, 10);\n\n canvasWidth += colWidth;\n\n column.drawnWidth = colWidth;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + colWidth + 'px; }';\n });\n }\n\n if (asterisksArray.length > 0) {\n var asteriskVal = parseInt(remainingWidth / asteriskNum, 10);\n\n // Pre-process to make sure they're all within any min/max values\n for (i = 0; i < asterisksArray.length; i++) {\n column = asterisksArray[i];\n\n colWidth = parseInt(asteriskVal * column.width.length, 10);\n\n if (column.colDef.minWidth && colWidth < column.colDef.minWidth) {\n colWidth = column.colDef.minWidth;\n\n remainingWidth = remainingWidth - colWidth;\n asteriskNum--;\n\n canvasWidth += colWidth;\n column.drawnWidth = colWidth;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + colWidth + 'px; }';\n\n lastColumn = column;\n\n // Remove this element from the percent array so it's not processed below\n asterisksArray.splice(i, 1);\n }\n else if (column.colDef.maxWidth && colWidth > column.colDef.maxWidth) {\n colWidth = column.colDef.maxWidth;\n\n remainingWidth = remainingWidth - colWidth;\n asteriskNum--;\n\n canvasWidth += colWidth;\n column.drawnWidth = colWidth;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + colWidth + 'px; }';\n\n // Remove this element from the percent array so it's not processed below\n asterisksArray.splice(i, 1);\n }\n }\n\n // Redo the asterisk value, as we may have removed columns due to width constraints\n asteriskVal = parseInt(remainingWidth / asteriskNum, 10);\n\n asterisksArray.forEach(function(column) {\n var colWidth = parseInt(asteriskVal * column.width.length, 10);\n\n canvasWidth += colWidth;\n\n column.drawnWidth = colWidth;\n\n // ret = ret + ' .grid' + uiGridCtrl.grid.id + ' .col' + column.index + ' { width: ' + colWidth + 'px; }';\n });\n }\n\n // If the grid width didn't divide evenly into the column widths and we have pixels left over, dole them out to the columns one by one to make everything fit\n var leftoverWidth = availableWidth - parseInt(canvasWidth, 10);\n\n if (leftoverWidth > 0 && canvasWidth > 0 && canvasWidth < availableWidth) {\n var variableColumn = false;\n // uiGridCtrl.grid.columns.forEach(function(col) {\n columnCache.forEach(function(col) {\n if (col.width && !angular.isNumber(col.width)) {\n variableColumn = true;\n }\n });\n\n if (variableColumn) {\n var remFn = function (column) {\n if (leftoverWidth > 0) {\n column.drawnWidth = column.drawnWidth + 1;\n canvasWidth = canvasWidth + 1;\n leftoverWidth--;\n }\n };\n while (leftoverWidth > 0) {\n columnCache.forEach(remFn);\n }\n }\n }\n\n if (canvasWidth < availableWidth) {\n canvasWidth = availableWidth;\n }\n\n // Build the CSS\n // uiGridCtrl.grid.columns.forEach(function (column) {\n columnCache.forEach(function (column) {\n ret = ret + column.getColClassDefinition();\n });\n\n // Add the vertical scrollbar width back in to the canvas width, it's taken out in getCanvasWidth\n if (grid.verticalScrollbarWidth) {\n canvasWidth = canvasWidth + grid.verticalScrollbarWidth;\n }\n // canvasWidth = canvasWidth + 1;\n\n containerCtrl.colContainer.canvasWidth = parseInt(canvasWidth, 10);\n\n // Return the styles back to buildStyles which pops them into the `customStyles` scope variable\n return ret;\n }\n \n containerCtrl.header = $elm;\n \n var headerViewport = $elm[0].getElementsByClassName('ui-grid-header-viewport')[0];\n if (headerViewport) {\n containerCtrl.headerViewport = headerViewport;\n }\n\n //todo: remove this if by injecting gridCtrl into unit tests\n if (uiGridCtrl) {\n uiGridCtrl.grid.registerStyleComputation({\n priority: 5,\n func: updateColumnWidths\n });\n }\n }\n };\n }\n };\n }]);\n\n})();\n(function(){\n\n/**\n * @ngdoc directive\n * @name ui.grid.directive:uiGridColumnMenu\n * @element style\n * @restrict A\n *\n * @description\n * Allows us to interpolate expressions in `\n I am in a box.\n \n \n \n it('should apply the right class to the element', function () {\n element(by.css('.blah')).getCssValue('border')\n .then(function(c) {\n expect(c).toContain('1px solid');\n });\n });\n \n \n */\n\n\n angular.module('ui.grid').directive('uiGridStyle', ['$log', '$interpolate', function($log, $interpolate) {\n return {\n // restrict: 'A',\n // priority: 1000,\n // require: '?^uiGrid',\n link: function($scope, $elm, $attrs, uiGridCtrl) {\n $log.debug('ui-grid-style link');\n // if (uiGridCtrl === undefined) {\n // $log.warn('[ui-grid-style link] uiGridCtrl is undefined!');\n // }\n\n var interpolateFn = $interpolate($elm.text(), true);\n\n if (interpolateFn) {\n $scope.$watch(interpolateFn, function(value) {\n $elm.text(value);\n });\n }\n\n // uiGridCtrl.recalcRowStyles = function() {\n // var offset = (scope.options.offsetTop || 0) - (scope.options.excessRows * scope.options.rowHeight);\n // var rowHeight = scope.options.rowHeight;\n\n // var ret = '';\n // var rowStyleCount = uiGridCtrl.minRowsToRender() + (scope.options.excessRows * 2);\n // for (var i = 1; i <= rowStyleCount; i++) {\n // ret = ret + ' .grid' + scope.gridId + ' .ui-grid-row:nth-child(' + i + ') { top: ' + offset + 'px; }';\n // offset = offset + rowHeight;\n // }\n\n // scope.rowStyles = ret;\n // };\n\n // uiGridCtrl.styleComputions.push(uiGridCtrl.recalcRowStyles);\n\n }\n };\n }]);\n\n})();\n(function(){\n 'use strict';\n\n angular.module('ui.grid').directive('uiGridViewport', ['$log', 'gridUtil',\n function($log, gridUtil) {\n return {\n replace: true,\n scope: {},\n templateUrl: 'ui-grid/uiGridViewport',\n require: ['^uiGrid', '^uiGridRenderContainer'],\n link: function($scope, $elm, $attrs, controllers) {\n $log.debug('viewport post-link');\n\n var uiGridCtrl = controllers[0];\n var containerCtrl = controllers[1];\n\n $scope.containerCtrl = containerCtrl;\n\n var rowContainer = containerCtrl.rowContainer;\n var colContainer = containerCtrl.colContainer;\n\n var grid = uiGridCtrl.grid;\n\n // Put the containers in scope so we can get rows and columns from them\n $scope.rowContainer = containerCtrl.rowContainer;\n $scope.colContainer = containerCtrl.colContainer;\n\n // Register this viewport with its container \n containerCtrl.viewport = $elm;\n\n $elm.on('scroll', function (evt) {\n var newScrollTop = $elm[0].scrollTop;\n // var newScrollLeft = $elm[0].scrollLeft;\n var newScrollLeft = gridUtil.normalizeScrollLeft($elm);\n\n // Handle RTL here\n\n if (newScrollLeft !== colContainer.prevScrollLeft) {\n var xDiff = newScrollLeft - colContainer.prevScrollLeft;\n\n var horizScrollLength = (colContainer.getCanvasWidth() - colContainer.getViewportWidth());\n var horizScrollPercentage = newScrollLeft / horizScrollLength;\n\n colContainer.adjustScrollHorizontal(newScrollLeft, horizScrollPercentage);\n }\n\n if (newScrollTop !== rowContainer.prevScrollTop) {\n var yDiff = newScrollTop - rowContainer.prevScrollTop;\n\n // uiGridCtrl.fireScrollingEvent({ y: { pixels: diff } });\n var vertScrollLength = (rowContainer.getCanvasHeight() - rowContainer.getViewportHeight());\n // var vertScrollPercentage = (uiGridCtrl.prevScrollTop + yDiff) / vertScrollLength;\n var vertScrollPercentage = newScrollTop / vertScrollLength;\n\n if (vertScrollPercentage > 1) { vertScrollPercentage = 1; }\n if (vertScrollPercentage < 0) { vertScrollPercentage = 0; }\n \n rowContainer.adjustScrollVertical(newScrollTop, vertScrollPercentage);\n }\n });\n }\n };\n }\n ]);\n\n})();\n(function() {\n\nangular.module('ui.grid')\n.directive('uiGridVisible', function uiGridVisibleAction() {\n return function ($scope, $elm, $attr) {\n $scope.$watch($attr.uiGridVisible, function (visible) {\n // $elm.css('visibility', visible ? 'visible' : 'hidden');\n $elm[visible ? 'removeClass' : 'addClass']('ui-grid-invisible');\n });\n };\n});\n\n})();\n(function () {\n 'use strict';\n\n angular.module('ui.grid').controller('uiGridController', ['$scope', '$element', '$attrs', '$log', 'gridUtil', '$q', 'uiGridConstants',\n '$templateCache', 'gridClassFactory', '$timeout', '$parse', '$compile',\n function ($scope, $elm, $attrs, $log, gridUtil, $q, uiGridConstants,\n $templateCache, gridClassFactory, $timeout, $parse, $compile) {\n $log.debug('ui-grid controller');\n\n var self = this;\n\n // Extend options with ui-grid attribute reference\n self.grid = gridClassFactory.createGrid($scope.uiGrid);\n $elm.addClass('grid' + self.grid.id);\n self.grid.rtl = $elm.css('direction') === 'rtl';\n\n\n //add optional reference to externalScopes function to controller\n //so it can be retrieved in lower elements that have isolate scope\n self.getExternalScopes = $scope.getExternalScopes;\n\n // angular.extend(self.grid.options, );\n\n //all properties of grid are available on scope\n $scope.grid = self.grid;\n\n if ($attrs.uiGridColumns) {\n $attrs.$observe('uiGridColumns', function(value) {\n self.grid.options.columnDefs = value;\n self.grid.buildColumns()\n .then(function(){\n self.grid.preCompileCellTemplates();\n\n self.grid.refreshCanvas(true);\n });\n });\n }\n\n\n var dataWatchCollectionDereg;\n if (angular.isString($scope.uiGrid.data)) {\n dataWatchCollectionDereg = $scope.$parent.$watchCollection($scope.uiGrid.data, dataWatchFunction);\n }\n else {\n dataWatchCollectionDereg = $scope.$parent.$watchCollection(function() { return $scope.uiGrid.data; }, dataWatchFunction);\n }\n\n var columnDefWatchCollectionDereg = $scope.$parent.$watchCollection(function() { return $scope.uiGrid.columnDefs; }, columnDefsWatchFunction);\n\n function columnDefsWatchFunction(n, o) {\n if (n && n !== o) {\n self.grid.options.columnDefs = n;\n self.grid.buildColumns()\n .then(function(){\n\n self.grid.preCompileCellTemplates();\n\n self.grid.refreshCanvas(true);\n });\n }\n }\n\n function dataWatchFunction(n) {\n // $log.debug('dataWatch fired');\n var promises = [];\n\n if (n) {\n if (self.grid.columns.length === 0) {\n $log.debug('loading cols in dataWatchFunction');\n if (!$attrs.uiGridColumns && self.grid.options.columnDefs.length === 0) {\n self.grid.buildColumnDefsFromData(n);\n }\n promises.push(self.grid.buildColumns()\n .then(function() {\n self.grid.preCompileCellTemplates();}\n ));\n }\n $q.all(promises).then(function() {\n self.grid.modifyRows(n)\n .then(function () {\n // if (self.viewport) {\n self.grid.redrawInPlace();\n // }\n\n $scope.$evalAsync(function() {\n self.grid.refreshCanvas(true);\n });\n });\n });\n }\n }\n\n\n $scope.$on('$destroy', function() {\n dataWatchCollectionDereg();\n columnDefWatchCollectionDereg();\n });\n\n $scope.$watch(function () { return self.grid.styleComputations; }, function() {\n self.grid.refreshCanvas(true);\n });\n\n\n /* Event Methods */\n\n //todo: throttle this event?\n self.fireScrollingEvent = function(args) {\n $scope.$broadcast(uiGridConstants.events.GRID_SCROLL, args);\n };\n\n self.fireEvent = function(eventName, args) {\n // Add the grid to the event arguments if it's not there\n if (typeof(args) === 'undefined' || args === undefined) {\n args = {};\n }\n\n if (typeof(args.grid) === 'undefined' || args.grid === undefined) {\n args.grid = self.grid;\n }\n\n $scope.$broadcast(eventName, args);\n };\n\n self.innerCompile = function innerCompile(elm) {\n $compile(elm)($scope);\n };\n\n }]);\n\n/**\n * @ngdoc directive\n * @name ui.grid.directive:uiGrid\n * @element div\n * @restrict EA\n * @param {Object} uiGrid Options for the grid to use\n * @param {Object=} external-scopes Add external-scopes='someScopeObjectYouNeed' attribute so you can access\n * your scopes from within any custom templatedirective. You access by $scope.getExternalScopes() function\n *\n * @description Create a very basic grid.\n *\n * @example\n \n \n var app = angular.module('app', ['ui.grid']);\n\n app.controller('MainCtrl', ['$scope', function ($scope) {\n $scope.data = [\n { name: 'Bob', title: 'CEO' },\n { name: 'Frank', title: 'Lowly Developer' }\n ];\n }]);\n \n \n
      \n
      \n
      \n
      \n
      \n */\nangular.module('ui.grid').directive('uiGrid',\n [\n '$log',\n '$compile',\n '$templateCache',\n 'gridUtil',\n '$window',\n function(\n $log,\n $compile,\n $templateCache,\n gridUtil,\n $window\n ) {\n return {\n templateUrl: 'ui-grid/ui-grid',\n scope: {\n uiGrid: '=',\n getExternalScopes: '&?externalScopes' //optional functionwrapper around any needed external scope instances\n },\n replace: true,\n transclude: true,\n controller: 'uiGridController',\n compile: function () {\n return {\n post: function ($scope, $elm, $attrs, uiGridCtrl) {\n $log.debug('ui-grid postlink');\n\n var grid = uiGridCtrl.grid;\n\n // Initialize scrollbars (TODO: move to controller??)\n uiGridCtrl.scrollbars = [];\n\n //todo: assume it is ok to communicate that rendering is complete??\n grid.renderingComplete();\n\n grid.element = $elm;\n\n grid.gridWidth = $scope.gridWidth = gridUtil.elementWidth($elm);\n\n // Default canvasWidth to the grid width, in case we don't get any column definitions to calculate it from\n grid.canvasWidth = uiGridCtrl.grid.gridWidth;\n\n grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm);\n\n // If the grid isn't tall enough to fit a single row, it's kind of useless. Resize it to fit a minimum number of rows\n if (grid.gridHeight < grid.options.rowHeight) {\n // Figure out the new height\n var newHeight = grid.options.minRowsToShow * grid.options.rowHeight;\n\n $elm.css('height', newHeight + 'px');\n\n grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm);\n }\n\n // Run initial canvas refresh\n grid.refreshCanvas();\n\n //add pinned containers for row headers support\n //moved from pinning feature\n var left = angular.element('
      ');\n $elm.prepend(left);\n uiGridCtrl.innerCompile(left);\n\n var right = angular.element('
      ');\n $elm.append(right);\n uiGridCtrl.innerCompile(right);\n\n\n //if we add a left container after render, we need to watch and react\n $scope.$watch(function () { return grid.hasLeftContainer();}, function (newValue, oldValue) {\n if (newValue === oldValue) {\n return;\n }\n\n //todo: remove this code. it was commented out after moving from pinning because body is already float:left\n// var bodyContainer = angular.element($elm[0].querySelectorAll('[container-id=\"body\"]'));\n// if (newValue){\n// bodyContainer.attr('style', 'float: left; position: inherit');\n// }\n// else {\n// bodyContainer.attr('style', 'float: left; position: relative');\n// }\n\n grid.refreshCanvas(true);\n });\n\n //if we add a right container after render, we need to watch and react\n $scope.$watch(function () { return grid.hasRightContainer();}, function (newValue, oldValue) {\n if (newValue === oldValue) {\n return;\n }\n grid.refreshCanvas(true);\n });\n\n\n // Resize the grid on window resize events\n function gridResize($event) {\n grid.gridWidth = $scope.gridWidth = gridUtil.elementWidth($elm);\n grid.gridHeight = $scope.gridHeight = gridUtil.elementHeight($elm);\n\n grid.queueRefresh();\n }\n\n angular.element($window).on('resize', gridResize);\n\n // Unbind from window resize events when the grid is destroyed\n $elm.on('$destroy', function () {\n angular.element($window).off('resize', gridResize);\n });\n }\n };\n }\n };\n }\n ]);\n\n})();\n\n(function(){\n 'use strict';\n\n angular.module('ui.grid').directive('uiGridPinnedContainer', ['$log', function ($log) {\n return {\n restrict: 'EA',\n replace: true,\n template: '
      ',\n scope: {\n side: '=uiGridPinnedContainer'\n },\n require: '^uiGrid',\n compile: function compile() {\n return {\n post: function ($scope, $elm, $attrs, uiGridCtrl) {\n $log.debug('ui-grid-pinned-container ' + $scope.side + ' link');\n\n var grid = uiGridCtrl.grid;\n\n var myWidth = 0;\n\n // $elm.addClass($scope.side);\n\n function updateContainerDimensions() {\n // $log.debug('update ' + $scope.side + ' dimensions');\n\n var ret = '';\n\n // Column containers\n if ($scope.side === 'left' || $scope.side === 'right') {\n var cols = grid.renderContainers[$scope.side].visibleColumnCache;\n var width = 0;\n for (var i = 0; i < cols.length; i++) {\n var col = cols[i];\n width += col.drawnWidth;\n }\n\n myWidth = width;\n\n // $log.debug('myWidth', myWidth);\n\n // TODO(c0bra): Subtract sum of col widths from grid viewport width and update it\n $elm.attr('style', null);\n\n var myHeight = grid.renderContainers.body.getViewportHeight(); // + grid.horizontalScrollbarHeight;\n\n ret += '.grid' + grid.id + ' .ui-grid-pinned-container.' + $scope.side + ', .ui-grid-pinned-container.' + $scope.side + ' .ui-grid-viewport { width: ' + myWidth + 'px; height: ' + myHeight + 'px; } ';\n }\n\n return ret;\n }\n\n grid.renderContainers.body.registerViewportAdjuster(function (adjustment) {\n // Subtract our own width\n adjustment.width -= myWidth;\n\n return adjustment;\n });\n\n // Register style computation to adjust for columns in `side`'s render container\n grid.registerStyleComputation({\n priority: 15,\n func: updateContainerDimensions\n });\n }\n };\n }\n };\n }]);\n})();\n(function(){\n\nangular.module('ui.grid')\n.factory('Grid', ['$log', '$q', '$compile', '$parse', 'gridUtil', 'uiGridConstants', 'GridOptions', 'GridColumn', 'GridRow', 'GridApi', 'rowSorter', 'rowSearcher', 'GridRenderContainer', '$timeout',\n function($log, $q, $compile, $parse, gridUtil, uiGridConstants, GridOptions, GridColumn, GridRow, GridApi, rowSorter, rowSearcher, GridRenderContainer, $timeout) {\n\n/**\n * @ngdoc object\n * @name ui.grid.core.api:PublicApi\n * @description Public Api for the core grid features\n *\n */\n\n\n/**\n * @ngdoc function\n * @name ui.grid.class:Grid\n * @description Grid is the main viewModel. Any properties or methods needed to maintain state are defined in\n * * this prototype. One instance of Grid is created per Grid directive instance.\n * @param {object} options Object map of options to pass into the grid. An 'id' property is expected.\n */\n var Grid = function Grid(options) {\n var self = this;\n // Get the id out of the options, then remove it\n if (options !== undefined && typeof(options.id) !== 'undefined' && options.id) {\n if (!/^[_a-zA-Z0-9-]+$/.test(options.id)) {\n throw new Error(\"Grid id '\" + options.id + '\" is invalid. It must follow CSS selector syntax rules.');\n }\n }\n else {\n throw new Error('No ID provided. An ID must be given when creating a grid.');\n }\n\n self.id = options.id;\n delete options.id;\n\n // Get default options\n self.options = new GridOptions();\n\n // Extend the default options with what we were passed in\n angular.extend(self.options, options);\n\n self.headerHeight = self.options.headerRowHeight;\n self.footerHeight = self.options.showFooter === true ? self.options.footerRowHeight : 0;\n\n self.rtl = false;\n self.gridHeight = 0;\n self.gridWidth = 0;\n self.columnBuilders = [];\n self.rowBuilders = [];\n self.rowsProcessors = [];\n self.columnsProcessors = [];\n self.styleComputations = [];\n self.viewportAdjusters = [];\n self.rowHeaderColumns = [];\n\n // self.visibleRowCache = [];\n\n // Set of 'render' containers for self grid, which can render sets of rows\n self.renderContainers = {};\n\n // Create a\n self.renderContainers.body = new GridRenderContainer('body', self);\n\n self.cellValueGetterCache = {};\n\n // Cached function to use with custom row templates\n self.getRowTemplateFn = null;\n\n\n //representation of the rows on the grid.\n //these are wrapped references to the actual data rows (options.data)\n self.rows = [];\n\n //represents the columns on the grid\n self.columns = [];\n\n /**\n * @ngdoc boolean\n * @name isScrollingVertically\n * @propertyOf ui.grid.class:Grid\n * @description set to true when Grid is scrolling vertically. Set to false via debounced method\n */\n self.isScrollingVertically = false;\n\n /**\n * @ngdoc boolean\n * @name isScrollingHorizontally\n * @propertyOf ui.grid.class:Grid\n * @description set to true when Grid is scrolling horizontally. Set to false via debounced method\n */\n self.isScrollingHorizontally = false;\n\n var debouncedVertical = gridUtil.debounce(function () {\n self.isScrollingVertically = false;\n }, 300);\n\n var debouncedHorizontal = gridUtil.debounce(function () {\n self.isScrollingHorizontally = false;\n }, 300);\n\n\n /**\n * @ngdoc function\n * @name flagScrollingVertically\n * @methodOf ui.grid.class:Grid\n * @description sets isScrollingVertically to true and sets it to false in a debounced function\n */\n self.flagScrollingVertically = function() {\n self.isScrollingVertically = true;\n debouncedVertical();\n };\n\n /**\n * @ngdoc function\n * @name flagScrollingHorizontally\n * @methodOf ui.grid.class:Grid\n * @description sets isScrollingHorizontally to true and sets it to false in a debounced function\n */\n self.flagScrollingHorizontally = function() {\n self.isScrollingHorizontally = true;\n debouncedHorizontal();\n };\n\n\n\n self.api = new GridApi(self);\n\n /**\n * @ngdoc function\n * @name refresh\n * @methodOf ui.grid.core.api:PublicApi\n * @description Refresh the rendered grid on screen.\n * \n */\n this.api.registerMethod( 'core', 'refresh', this.refresh );\n\n /**\n * @ngdoc function\n * @name refreshRows\n * @methodOf ui.grid.core.api:PublicApi\n * @description Refresh the rendered grid on screen? Note: not functional at present\n * @returns {promise} promise that is resolved when render completes?\n * \n */\n this.api.registerMethod( 'core', 'refreshRows', this.refreshRows );\n};\n\n /**\n * @ngdoc function\n * @name isRTL\n * @methodOf ui.grid.class:Grid\n * @description Returns true if grid is RightToLeft\n */\n Grid.prototype.isRTL = function () {\n return this.rtl;\n };\n\n\n /**\n * @ngdoc function\n * @name registerColumnBuilder\n * @methodOf ui.grid.class:Grid\n * @description When the build creates columns from column definitions, the columnbuilders will be called to add\n * additional properties to the column.\n * @param {function(colDef, col, gridOptions)} columnsProcessor function to be called\n */\n Grid.prototype.registerColumnBuilder = function registerColumnBuilder(columnBuilder) {\n this.columnBuilders.push(columnBuilder);\n };\n\n /**\n * @ngdoc function\n * @name buildColumnDefsFromData\n * @methodOf ui.grid.class:Grid\n * @description Populates columnDefs from the provided data\n * @param {function(colDef, col, gridOptions)} rowBuilder function to be called\n */\n Grid.prototype.buildColumnDefsFromData = function (dataRows){\n this.options.columnDefs = gridUtil.getColumnsFromData(dataRows, this.options.excludeProperties);\n };\n\n /**\n * @ngdoc function\n * @name registerRowBuilder\n * @methodOf ui.grid.class:Grid\n * @description When the build creates rows from gridOptions.data, the rowBuilders will be called to add\n * additional properties to the row.\n * @param {function(colDef, col, gridOptions)} rowBuilder function to be called\n */\n Grid.prototype.registerRowBuilder = function registerRowBuilder(rowBuilder) {\n this.rowBuilders.push(rowBuilder);\n };\n\n /**\n * @ngdoc function\n * @name getColumn\n * @methodOf ui.grid.class:Grid\n * @description returns a grid column for the column name\n * @param {string} name column name\n */\n Grid.prototype.getColumn = function getColumn(name) {\n var columns = this.columns.filter(function (column) {\n return column.colDef.name === name;\n });\n return columns.length > 0 ? columns[0] : null;\n };\n\n /**\n * @ngdoc function\n * @name getColDef\n * @methodOf ui.grid.class:Grid\n * @description returns a grid colDef for the column name\n * @param {string} name column.field\n */\n Grid.prototype.getColDef = function getColDef(name) {\n var colDefs = this.options.columnDefs.filter(function (colDef) {\n return colDef.name === name;\n });\n return colDefs.length > 0 ? colDefs[0] : null;\n };\n\n /**\n * @ngdoc function\n * @name assignTypes\n * @methodOf ui.grid.class:Grid\n * @description uses the first row of data to assign colDef.type for any types not defined.\n */\n /**\n * @ngdoc property\n * @name type\n * @propertyOf ui.grid.class:GridOptions.columnDef\n * @description the type of the column, used in sorting. If not provided then the \n * grid will guess the type. Add this only if the grid guessing is not to your\n * satisfaction. Refer to {@link ui.grid.service:GridUtil.guessType gridUtil.guessType} for\n * a list of values the grid knows about.\n *\n */\n Grid.prototype.assignTypes = function(){\n var self = this;\n self.options.columnDefs.forEach(function (colDef, index) {\n\n //Assign colDef type if not specified\n if (!colDef.type) {\n var col = new GridColumn(colDef, index, self);\n var firstRow = self.rows.length > 0 ? self.rows[0] : null;\n if (firstRow) {\n colDef.type = gridUtil.guessType(self.getCellValue(firstRow, col));\n }\n else {\n $log.log('Unable to assign type from data, so defaulting to string');\n colDef.type = 'string';\n }\n }\n });\n };\n\n /**\n * @ngdoc function\n * @name addRowHeaderColumn\n * @methodOf ui.grid.class:Grid\n * @description adds a row header column to the grid\n * @param {object} column def\n */\n Grid.prototype.addRowHeaderColumn = function addRowHeaderColumn(colDef, index) {\n var self = this;\n //self.createLeftContainer();\n var rowHeaderCol = new GridColumn(colDef, self.rowHeaderColumns.length + 1, self);\n rowHeaderCol.isRowHeader = true;\n if (self.isRTL()) {\n self.createRightContainer();\n rowHeaderCol.renderContainer = 'right';\n }\n else {\n self.createLeftContainer();\n rowHeaderCol.renderContainer = 'left';\n }\n rowHeaderCol.cellTemplate = colDef.cellTemplate;\n rowHeaderCol.enableFiltering = false;\n rowHeaderCol.enableSorting = false;\n self.rowHeaderColumns.push(rowHeaderCol);\n };\n\n /**\n * @ngdoc function\n * @name buildColumns\n * @methodOf ui.grid.class:Grid\n * @description creates GridColumn objects from the columnDefinition. Calls each registered\n * columnBuilder to further process the column\n * @returns {Promise} a promise to load any needed column resources\n */\n Grid.prototype.buildColumns = function buildColumns() {\n $log.debug('buildColumns');\n var self = this;\n var builderPromises = [];\n var offset = self.rowHeaderColumns.length;\n\n //add row header columns to the grid columns array\n angular.forEach(self.rowHeaderColumns, function (rowHeaderColumn) {\n offset++;\n self.columns.push(rowHeaderColumn);\n });\n\n // Synchronize self.columns with self.options.columnDefs so that columns can also be removed.\n if (self.columns.length > self.options.columnDefs.length) {\n self.columns.forEach(function (column, index) {\n if (!self.getColDef(column.name)) {\n self.columns.splice(index, 1);\n }\n });\n }\n\n self.options.columnDefs.forEach(function (colDef, index) {\n self.preprocessColDef(colDef);\n var col = self.getColumn(colDef.name);\n\n if (!col) {\n col = new GridColumn(colDef, index + offset, self);\n self.columns.push(col);\n }\n else {\n col.updateColumnDef(colDef, col.index);\n }\n\n self.columnBuilders.forEach(function (builder) {\n builderPromises.push(builder.call(self, colDef, col, self.options));\n });\n });\n\n return $q.all(builderPromises);\n };\n\n/**\n * @ngdoc function\n * @name preCompileCellTemplates\n * @methodOf ui.grid.class:Grid\n * @description precompiles all cell templates\n */\n Grid.prototype.preCompileCellTemplates = function() {\n $log.info('pre-compiling cell templates');\n this.columns.forEach(function (col) {\n var html = col.cellTemplate.replace(uiGridConstants.COL_FIELD, 'grid.getCellValue(row, col)');\n\n var compiledElementFn = $compile(html);\n col.compiledElementFn = compiledElementFn;\n });\n };\n\n /**\n * @ngdoc function\n * @name createLeftContainer\n * @methodOf ui.grid.class:Grid\n * @description creates the left render container if it doesn't already exist\n */\n Grid.prototype.createLeftContainer = function() {\n if (!this.hasLeftContainer()) {\n this.renderContainers.left = new GridRenderContainer('left', this, { disableColumnOffset: true });\n }\n };\n\n /**\n * @ngdoc function\n * @name createRightContainer\n * @methodOf ui.grid.class:Grid\n * @description creates the right render container if it doesn't already exist\n */\n Grid.prototype.createRightContainer = function() {\n if (!this.hasRightContainer()) {\n this.renderContainers.right = new GridRenderContainer('right', this, { disableColumnOffset: true });\n }\n };\n\n /**\n * @ngdoc function\n * @name hasLeftContainer\n * @methodOf ui.grid.class:Grid\n * @description returns true if leftContainer exists\n */\n Grid.prototype.hasLeftContainer = function() {\n return this.renderContainers.left !== undefined;\n };\n\n /**\n * @ngdoc function\n * @name hasLeftContainer\n * @methodOf ui.grid.class:Grid\n * @description returns true if rightContainer exists\n */\n Grid.prototype.hasRightContainer = function() {\n return this.renderContainers.right !== undefined;\n };\n\n\n /**\n * undocumented function\n * @name preprocessColDef\n * @methodOf ui.grid.class:Grid\n * @description defaults the name property from field to maintain backwards compatibility with 2.x\n * validates that name or field is present\n */\n Grid.prototype.preprocessColDef = function preprocessColDef(colDef) {\n if (!colDef.field && !colDef.name) {\n throw new Error('colDef.name or colDef.field property is required');\n }\n\n //maintain backwards compatibility with 2.x\n //field was required in 2.x. now name is required\n if (colDef.name === undefined && colDef.field !== undefined) {\n colDef.name = colDef.field;\n }\n\n };\n\n // Return a list of items that exist in the `n` array but not the `o` array. Uses optional property accessors passed as third & fourth parameters\n Grid.prototype.newInN = function newInN(o, n, oAccessor, nAccessor) {\n var self = this;\n\n var t = [];\n for (var i=0; i 0 ? rows[0] : null;\n };\n\n\n /**\n * @ngdoc function\n * @name modifyRows\n * @methodOf ui.grid.class:Grid\n * @description creates or removes GridRow objects from the newRawData array. Calls each registered\n * rowBuilder to further process the row\n *\n * Rows are identified using the gridOptions.rowEquality function\n */\n Grid.prototype.modifyRows = function modifyRows(newRawData) {\n var self = this,\n i,\n newRow;\n\n if (self.rows.length === 0 && newRawData.length > 0) {\n if (self.options.enableRowHashing) {\n if (!self.rowHashMap) {\n self.createRowHashMap();\n }\n\n for (i=0; i 0) {\n var unfoundNewRows, unfoundOldRows, unfoundNewRowsToFind;\n\n // If row hashing is turned on\n if (self.options.enableRowHashing) {\n // Array of new rows that haven't been found in the old rowset\n unfoundNewRows = [];\n // Array of new rows that we explicitly HAVE to search for manually in the old row set. They cannot be looked up by their identity (because it doesn't exist).\n unfoundNewRowsToFind = [];\n // Map of rows that have been found in the new rowset\n var foundOldRows = {};\n // Array of old rows that have NOT been found in the new rowset\n unfoundOldRows = [];\n\n // Create the row HashMap if it doesn't exist already\n if (!self.rowHashMap) {\n self.createRowHashMap();\n }\n var rowhash = self.rowHashMap;\n \n // Make sure every new row has a hash\n for (i = 0; i < newRawData.length; i++) {\n newRow = newRawData[i];\n\n // Flag this row as needing to be manually found if it didn't come in with a $$hashKey\n var mustFind = false;\n if (!self.options.getRowIdentity(newRow)) {\n mustFind = true;\n }\n\n // See if the new row is already in the rowhash\n var found = rowhash.get(newRow);\n // If so...\n if (found) {\n // See if it's already being used by as GridRow\n if (found.row) {\n // If so, mark this new row as being found\n foundOldRows[self.options.rowIdentity(newRow)] = true;\n }\n }\n else {\n // Put the row in the hashmap with the index it corresponds to\n rowhash.put(newRow, {\n i: i,\n entity: newRow\n });\n \n // This row has to be searched for manually in the old row set\n if (mustFind) {\n unfoundNewRowsToFind.push(newRow);\n }\n else {\n unfoundNewRows.push(newRow);\n }\n }\n }\n\n // Build the list of unfound old rows\n for (i = 0; i < self.rows.length; i++) {\n var row = self.rows[i];\n var hash = self.options.rowIdentity(row.entity);\n if (!foundOldRows[hash]) {\n unfoundOldRows.push(row);\n }\n }\n }\n\n // Look for new rows\n var newRows = unfoundNewRows || [];\n\n // The unfound new rows is either `unfoundNewRowsToFind`, if row hashing is turned on, or straight `newRawData` if it isn't\n var unfoundNew = (unfoundNewRowsToFind || newRawData);\n\n // Search for real new rows in `unfoundNew` and concat them onto `newRows`\n newRows = newRows.concat(self.newInN(self.rows, unfoundNew, 'entity'));\n \n self.addRows(newRows); \n \n var deletedRows = self.getDeletedRows((unfoundOldRows || self.rows), newRawData);\n\n for (i = 0; i < deletedRows.length; i++) {\n if (self.options.enableRowHashing) {\n self.rowHashMap.remove(deletedRows[i].entity);\n }\n\n self.rows.splice( self.rows.indexOf(deletedRows[i]), 1 );\n }\n }\n // Empty data set\n else {\n // Reset the row HashMap\n self.createRowHashMap();\n\n // Reset the rows length!\n self.rows.length = 0;\n }\n \n var p1 = $q.when(self.processRowsProcessors(self.rows))\n .then(function (renderableRows) {\n return self.setVisibleRows(renderableRows);\n });\n\n var p2 = $q.when(self.processColumnsProcessors(self.columns))\n .then(function (renderableColumns) {\n return self.setVisibleColumns(renderableColumns);\n });\n\n return $q.all([p1, p2]);\n };\n\n Grid.prototype.getDeletedRows = function(oldRows, newRows) {\n var self = this;\n\n var olds = oldRows.filter(function (oldRow) {\n return !newRows.some(function (newItem) {\n return self.options.rowEquality(newItem, oldRow.entity);\n });\n });\n // var olds = self.newInN(newRows, oldRows, null, 'entity');\n // dump('olds', olds);\n return olds;\n };\n\n /**\n * Private Undocumented Method\n * @name addRows\n * @methodOf ui.grid.class:Grid\n * @description adds the newRawData array of rows to the grid and calls all registered\n * rowBuilders. this keyword will reference the grid\n */\n Grid.prototype.addRows = function addRows(newRawData) {\n var self = this;\n\n var existingRowCount = self.rows.length;\n for (var i=0; i < newRawData.length; i++) {\n var newRow = self.processRowBuilders(new GridRow(newRawData[i], i + existingRowCount, self));\n\n if (self.options.enableRowHashing) {\n var found = self.rowHashMap.get(newRow.entity);\n if (found) {\n found.row = newRow;\n }\n }\n\n self.rows.push(newRow);\n }\n };\n\n /**\n * @ngdoc function\n * @name processRowBuilders\n * @methodOf ui.grid.class:Grid\n * @description processes all RowBuilders for the gridRow\n * @param {GridRow} gridRow reference to gridRow\n * @returns {GridRow} the gridRow with all additional behavior added\n */\n Grid.prototype.processRowBuilders = function processRowBuilders(gridRow) {\n var self = this;\n\n self.rowBuilders.forEach(function (builder) {\n builder.call(self, gridRow, self.gridOptions);\n });\n\n return gridRow;\n };\n\n /**\n * @ngdoc function\n * @name registerStyleComputation\n * @methodOf ui.grid.class:Grid\n * @description registered a styleComputation function\n * \n * If the function returns a value it will be appended into the grid's `
      \"\n );\n\n\n $templateCache.put('ui-grid/uiGridCell',\n \"
      {{COL_FIELD CUSTOM_FILTERS}}
      \"\n );\n\n\n $templateCache.put('ui-grid/uiGridColumnFilter',\n \"
    •  
       
    • \"\n );\n\n\n $templateCache.put('ui-grid/uiGridColumnMenu',\n \"
      \"\n );\n\n\n $templateCache.put('ui-grid/uiGridFooterCell',\n \"
      {{ col.getAggregationValue() }}
      \"\n );\n\n\n $templateCache.put('ui-grid/uiGridHeaderCell',\n \"
       
      {{ col.displayName CUSTOM_FILTERS }}  
       
       
      \"\n );\n\n\n $templateCache.put('ui-grid/uiGridMenu',\n \"
      \"\n );\n\n\n $templateCache.put('ui-grid/uiGridMenuItem',\n \"
    • {{ title }}
    • \"\n );\n\n\n $templateCache.put('ui-grid/uiGridRenderContainer',\n \"
      \"\n );\n\n\n $templateCache.put('ui-grid/uiGridViewport',\n \"
      \"\n );\n\n\n $templateCache.put('ui-grid/cellEditor',\n \"
      \"\n );\n\n\n $templateCache.put('ui-grid/columnResizer',\n \"
      \"\n );\n\n\n $templateCache.put('ui-grid/selectionRowHeader',\n \"
      \"\n );\n\n\n $templateCache.put('ui-grid/selectionRowHeaderButtons',\n \"
       
      \"\n );\n\n}]);\n","/**\n * Autofill event polyfill ##version:1.0.0##\n * (c) 2014 Google, Inc.\n * License: MIT\n */\n(function(window) {\n var $ = window.jQuery || window.angular.element;\n var rootElement = window.document.documentElement,\n $rootElement = $(rootElement);\n\n addGlobalEventListener('change', markValue);\n addValueChangeByJsListener(markValue);\n\n $.prototype.checkAndTriggerAutoFillEvent = jqCheckAndTriggerAutoFillEvent;\n\n // Need to use blur and not change event\n // as Chrome does not fire change events in all cases an input is changed\n // (e.g. when starting to type and then finish the input by auto filling a username)\n addGlobalEventListener('blur', function(target) {\n // setTimeout needed for Chrome as it fills other\n // form fields a little later...\n window.setTimeout(function() {\n findParentForm(target).find('input').checkAndTriggerAutoFillEvent();\n }, 20);\n });\n\n function DOMContentLoadedListener() {\n // mark all values that are present when the DOM is ready.\n // We don't need to trigger a change event here,\n // as js libs start with those values already being set!\n forEach(document.getElementsByTagName('input'), markValue);\n\n // The timeout is needed for Chrome as it auto fills\n // login forms some time after DOMContentLoaded!\n window.setTimeout(function() {\n $rootElement.find('input').checkAndTriggerAutoFillEvent();\n }, 200);\n }\n\n // IE8 compatibility issue\n if(!window.document.addEventListener){\n window.document.attachEvent('DOMContentLoaded', DOMContentLoadedListener); \n }else{\n window.document.addEventListener('DOMContentLoaded', DOMContentLoadedListener, false);\n }\n\n return;\n\n // ----------\n\n function jqCheckAndTriggerAutoFillEvent() {\n var i, el;\n for (i=0; i 0) {\n forEach(this, function(el) {\n listener(el, newValue);\n });\n }\n return res;\n };\n }\n\n function addGlobalEventListener(eventName, listener) {\n // Use a capturing event listener so that\n // we also get the event when it's stopped!\n // Also, the blur event does not bubble.\n if(!rootElement.addEventListener){\n rootElement.attachEvent(eventName, onEvent); \n }else{\n rootElement.addEventListener(eventName, onEvent, true);\n }\n\n function onEvent(event) {\n var target = event.target;\n listener(target);\n }\n }\n\n function findParentForm(el) {\n while (el) {\n if (el.nodeName === 'FORM') {\n return $(el);\n }\n el = el.parentNode;\n }\n return $();\n }\n\n function forEach(arr, listener) {\n if (arr.forEach) {\n return arr.forEach(listener);\n }\n var i;\n for (i=0; i= 0;\n };\n\n // Invoke a method (with arguments) on every item in a collection.\n _.invoke = function(obj, method) {\n var args = slice.call(arguments, 2);\n var isFunc = _.isFunction(method);\n return _.map(obj, function(value) {\n return (isFunc ? method : value[method]).apply(value, args);\n });\n };\n\n // Convenience version of a common use case of `map`: fetching a property.\n _.pluck = function(obj, key) {\n return _.map(obj, _.property(key));\n };\n\n // Convenience version of a common use case of `filter`: selecting only objects\n // containing specific `key:value` pairs.\n _.where = function(obj, attrs) {\n return _.filter(obj, _.matches(attrs));\n };\n\n // Convenience version of a common use case of `find`: getting the first object\n // containing specific `key:value` pairs.\n _.findWhere = function(obj, attrs) {\n return _.find(obj, _.matches(attrs));\n };\n\n // Return the maximum element (or element-based computation).\n _.max = function(obj, iteratee, context) {\n var result = -Infinity, lastComputed = -Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = obj.length === +obj.length ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value > result) {\n result = value;\n }\n }\n } else {\n iteratee = _.iteratee(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed > lastComputed || computed === -Infinity && result === -Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Return the minimum element (or element-based computation).\n _.min = function(obj, iteratee, context) {\n var result = Infinity, lastComputed = Infinity,\n value, computed;\n if (iteratee == null && obj != null) {\n obj = obj.length === +obj.length ? obj : _.values(obj);\n for (var i = 0, length = obj.length; i < length; i++) {\n value = obj[i];\n if (value < result) {\n result = value;\n }\n }\n } else {\n iteratee = _.iteratee(iteratee, context);\n _.each(obj, function(value, index, list) {\n computed = iteratee(value, index, list);\n if (computed < lastComputed || computed === Infinity && result === Infinity) {\n result = value;\n lastComputed = computed;\n }\n });\n }\n return result;\n };\n\n // Shuffle a collection, using the modern version of the\n // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).\n _.shuffle = function(obj) {\n var set = obj && obj.length === +obj.length ? obj : _.values(obj);\n var length = set.length;\n var shuffled = Array(length);\n for (var index = 0, rand; index < length; index++) {\n rand = _.random(0, index);\n if (rand !== index) shuffled[index] = shuffled[rand];\n shuffled[rand] = set[index];\n }\n return shuffled;\n };\n\n // Sample **n** random values from a collection.\n // If **n** is not specified, returns a single random element.\n // The internal `guard` argument allows it to work with `map`.\n _.sample = function(obj, n, guard) {\n if (n == null || guard) {\n if (obj.length !== +obj.length) obj = _.values(obj);\n return obj[_.random(obj.length - 1)];\n }\n return _.shuffle(obj).slice(0, Math.max(0, n));\n };\n\n // Sort the object's values by a criterion produced by an iteratee.\n _.sortBy = function(obj, iteratee, context) {\n iteratee = _.iteratee(iteratee, context);\n return _.pluck(_.map(obj, function(value, index, list) {\n return {\n value: value,\n index: index,\n criteria: iteratee(value, index, list)\n };\n }).sort(function(left, right) {\n var a = left.criteria;\n var b = right.criteria;\n if (a !== b) {\n if (a > b || a === void 0) return 1;\n if (a < b || b === void 0) return -1;\n }\n return left.index - right.index;\n }), 'value');\n };\n\n // An internal function used for aggregate \"group by\" operations.\n var group = function(behavior) {\n return function(obj, iteratee, context) {\n var result = {};\n iteratee = _.iteratee(iteratee, context);\n _.each(obj, function(value, index) {\n var key = iteratee(value, index, obj);\n behavior(result, value, key);\n });\n return result;\n };\n };\n\n // Groups the object's values by a criterion. Pass either a string attribute\n // to group by, or a function that returns the criterion.\n _.groupBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key].push(value); else result[key] = [value];\n });\n\n // Indexes the object's values by a criterion, similar to `groupBy`, but for\n // when you know that your index values will be unique.\n _.indexBy = group(function(result, value, key) {\n result[key] = value;\n });\n\n // Counts instances of an object that group by a certain criterion. Pass\n // either a string attribute to count by, or a function that returns the\n // criterion.\n _.countBy = group(function(result, value, key) {\n if (_.has(result, key)) result[key]++; else result[key] = 1;\n });\n\n // Use a comparator function to figure out the smallest index at which\n // an object should be inserted so as to maintain order. Uses binary search.\n _.sortedIndex = function(array, obj, iteratee, context) {\n iteratee = _.iteratee(iteratee, context, 1);\n var value = iteratee(obj);\n var low = 0, high = array.length;\n while (low < high) {\n var mid = low + high >>> 1;\n if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;\n }\n return low;\n };\n\n // Safely create a real, live array from anything iterable.\n _.toArray = function(obj) {\n if (!obj) return [];\n if (_.isArray(obj)) return slice.call(obj);\n if (obj.length === +obj.length) return _.map(obj, _.identity);\n return _.values(obj);\n };\n\n // Return the number of elements in an object.\n _.size = function(obj) {\n if (obj == null) return 0;\n return obj.length === +obj.length ? obj.length : _.keys(obj).length;\n };\n\n // Split a collection into two arrays: one whose elements all satisfy the given\n // predicate, and one whose elements all do not satisfy the predicate.\n _.partition = function(obj, predicate, context) {\n predicate = _.iteratee(predicate, context);\n var pass = [], fail = [];\n _.each(obj, function(value, key, obj) {\n (predicate(value, key, obj) ? pass : fail).push(value);\n });\n return [pass, fail];\n };\n\n // Array Functions\n // ---------------\n\n // Get the first element of an array. Passing **n** will return the first N\n // values in the array. Aliased as `head` and `take`. The **guard** check\n // allows it to work with `_.map`.\n _.first = _.head = _.take = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[0];\n if (n < 0) return [];\n return slice.call(array, 0, n);\n };\n\n // Returns everything but the last entry of the array. Especially useful on\n // the arguments object. Passing **n** will return all the values in\n // the array, excluding the last N. The **guard** check allows it to work with\n // `_.map`.\n _.initial = function(array, n, guard) {\n return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));\n };\n\n // Get the last element of an array. Passing **n** will return the last N\n // values in the array. The **guard** check allows it to work with `_.map`.\n _.last = function(array, n, guard) {\n if (array == null) return void 0;\n if (n == null || guard) return array[array.length - 1];\n return slice.call(array, Math.max(array.length - n, 0));\n };\n\n // Returns everything but the first entry of the array. Aliased as `tail` and `drop`.\n // Especially useful on the arguments object. Passing an **n** will return\n // the rest N values in the array. The **guard**\n // check allows it to work with `_.map`.\n _.rest = _.tail = _.drop = function(array, n, guard) {\n return slice.call(array, n == null || guard ? 1 : n);\n };\n\n // Trim out all falsy values from an array.\n _.compact = function(array) {\n return _.filter(array, _.identity);\n };\n\n // Internal implementation of a recursive `flatten` function.\n var flatten = function(input, shallow, strict, output) {\n if (shallow && _.every(input, _.isArray)) {\n return concat.apply(output, input);\n }\n for (var i = 0, length = input.length; i < length; i++) {\n var value = input[i];\n if (!_.isArray(value) && !_.isArguments(value)) {\n if (!strict) output.push(value);\n } else if (shallow) {\n push.apply(output, value);\n } else {\n flatten(value, shallow, strict, output);\n }\n }\n return output;\n };\n\n // Flatten out an array, either recursively (by default), or just one level.\n _.flatten = function(array, shallow) {\n return flatten(array, shallow, false, []);\n };\n\n // Return a version of the array that does not contain the specified value(s).\n _.without = function(array) {\n return _.difference(array, slice.call(arguments, 1));\n };\n\n // Produce a duplicate-free version of the array. If the array has already\n // been sorted, you have the option of using a faster algorithm.\n // Aliased as `unique`.\n _.uniq = _.unique = function(array, isSorted, iteratee, context) {\n if (array == null) return [];\n if (!_.isBoolean(isSorted)) {\n context = iteratee;\n iteratee = isSorted;\n isSorted = false;\n }\n if (iteratee != null) iteratee = _.iteratee(iteratee, context);\n var result = [];\n var seen = [];\n for (var i = 0, length = array.length; i < length; i++) {\n var value = array[i];\n if (isSorted) {\n if (!i || seen !== value) result.push(value);\n seen = value;\n } else if (iteratee) {\n var computed = iteratee(value, i, array);\n if (_.indexOf(seen, computed) < 0) {\n seen.push(computed);\n result.push(value);\n }\n } else if (_.indexOf(result, value) < 0) {\n result.push(value);\n }\n }\n return result;\n };\n\n // Produce an array that contains the union: each distinct element from all of\n // the passed-in arrays.\n _.union = function() {\n return _.uniq(flatten(arguments, true, true, []));\n };\n\n // Produce an array that contains every item shared between all the\n // passed-in arrays.\n _.intersection = function(array) {\n if (array == null) return [];\n var result = [];\n var argsLength = arguments.length;\n for (var i = 0, length = array.length; i < length; i++) {\n var item = array[i];\n if (_.contains(result, item)) continue;\n for (var j = 1; j < argsLength; j++) {\n if (!_.contains(arguments[j], item)) break;\n }\n if (j === argsLength) result.push(item);\n }\n return result;\n };\n\n // Take the difference between one array and a number of other arrays.\n // Only the elements present in just the first array will remain.\n _.difference = function(array) {\n var rest = flatten(slice.call(arguments, 1), true, true, []);\n return _.filter(array, function(value){\n return !_.contains(rest, value);\n });\n };\n\n // Zip together multiple lists into a single array -- elements that share\n // an index go together.\n _.zip = function(array) {\n if (array == null) return [];\n var length = _.max(arguments, 'length').length;\n var results = Array(length);\n for (var i = 0; i < length; i++) {\n results[i] = _.pluck(arguments, i);\n }\n return results;\n };\n\n // Converts lists into objects. Pass either a single array of `[key, value]`\n // pairs, or two parallel arrays of the same length -- one of keys, and one of\n // the corresponding values.\n _.object = function(list, values) {\n if (list == null) return {};\n var result = {};\n for (var i = 0, length = list.length; i < length; i++) {\n if (values) {\n result[list[i]] = values[i];\n } else {\n result[list[i][0]] = list[i][1];\n }\n }\n return result;\n };\n\n // Return the position of the first occurrence of an item in an array,\n // or -1 if the item is not included in the array.\n // If the array is large and already in sort order, pass `true`\n // for **isSorted** to use binary search.\n _.indexOf = function(array, item, isSorted) {\n if (array == null) return -1;\n var i = 0, length = array.length;\n if (isSorted) {\n if (typeof isSorted == 'number') {\n i = isSorted < 0 ? Math.max(0, length + isSorted) : isSorted;\n } else {\n i = _.sortedIndex(array, item);\n return array[i] === item ? i : -1;\n }\n }\n for (; i < length; i++) if (array[i] === item) return i;\n return -1;\n };\n\n _.lastIndexOf = function(array, item, from) {\n if (array == null) return -1;\n var idx = array.length;\n if (typeof from == 'number') {\n idx = from < 0 ? idx + from + 1 : Math.min(idx, from + 1);\n }\n while (--idx >= 0) if (array[idx] === item) return idx;\n return -1;\n };\n\n // Generate an integer Array containing an arithmetic progression. A port of\n // the native Python `range()` function. See\n // [the Python documentation](http://docs.python.org/library/functions.html#range).\n _.range = function(start, stop, step) {\n if (arguments.length <= 1) {\n stop = start || 0;\n start = 0;\n }\n step = step || 1;\n\n var length = Math.max(Math.ceil((stop - start) / step), 0);\n var range = Array(length);\n\n for (var idx = 0; idx < length; idx++, start += step) {\n range[idx] = start;\n }\n\n return range;\n };\n\n // Function (ahem) Functions\n // ------------------\n\n // Reusable constructor function for prototype setting.\n var Ctor = function(){};\n\n // Create a function bound to a given object (assigning `this`, and arguments,\n // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if\n // available.\n _.bind = function(func, context) {\n var args, bound;\n if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));\n if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function');\n args = slice.call(arguments, 2);\n bound = function() {\n if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));\n Ctor.prototype = func.prototype;\n var self = new Ctor;\n Ctor.prototype = null;\n var result = func.apply(self, args.concat(slice.call(arguments)));\n if (_.isObject(result)) return result;\n return self;\n };\n return bound;\n };\n\n // Partially apply a function by creating a version that has had some of its\n // arguments pre-filled, without changing its dynamic `this` context. _ acts\n // as a placeholder, allowing any combination of arguments to be pre-filled.\n _.partial = function(func) {\n var boundArgs = slice.call(arguments, 1);\n return function() {\n var position = 0;\n var args = boundArgs.slice();\n for (var i = 0, length = args.length; i < length; i++) {\n if (args[i] === _) args[i] = arguments[position++];\n }\n while (position < arguments.length) args.push(arguments[position++]);\n return func.apply(this, args);\n };\n };\n\n // Bind a number of an object's methods to that object. Remaining arguments\n // are the method names to be bound. Useful for ensuring that all callbacks\n // defined on an object belong to it.\n _.bindAll = function(obj) {\n var i, length = arguments.length, key;\n if (length <= 1) throw new Error('bindAll must be passed function names');\n for (i = 1; i < length; i++) {\n key = arguments[i];\n obj[key] = _.bind(obj[key], obj);\n }\n return obj;\n };\n\n // Memoize an expensive function by storing its results.\n _.memoize = function(func, hasher) {\n var memoize = function(key) {\n var cache = memoize.cache;\n var address = hasher ? hasher.apply(this, arguments) : key;\n if (!_.has(cache, address)) cache[address] = func.apply(this, arguments);\n return cache[address];\n };\n memoize.cache = {};\n return memoize;\n };\n\n // Delays a function for the given number of milliseconds, and then calls\n // it with the arguments supplied.\n _.delay = function(func, wait) {\n var args = slice.call(arguments, 2);\n return setTimeout(function(){\n return func.apply(null, args);\n }, wait);\n };\n\n // Defers a function, scheduling it to run after the current call stack has\n // cleared.\n _.defer = function(func) {\n return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));\n };\n\n // Returns a function, that, when invoked, will only be triggered at most once\n // during a given window of time. Normally, the throttled function will run\n // as much as it can, without ever going more than once per `wait` duration;\n // but if you'd like to disable the execution on the leading edge, pass\n // `{leading: false}`. To disable execution on the trailing edge, ditto.\n _.throttle = function(func, wait, options) {\n var context, args, result;\n var timeout = null;\n var previous = 0;\n if (!options) options = {};\n var later = function() {\n previous = options.leading === false ? 0 : _.now();\n timeout = null;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n };\n return function() {\n var now = _.now();\n if (!previous && options.leading === false) previous = now;\n var remaining = wait - (now - previous);\n context = this;\n args = arguments;\n if (remaining <= 0 || remaining > wait) {\n clearTimeout(timeout);\n timeout = null;\n previous = now;\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n } else if (!timeout && options.trailing !== false) {\n timeout = setTimeout(later, remaining);\n }\n return result;\n };\n };\n\n // Returns a function, that, as long as it continues to be invoked, will not\n // be triggered. The function will be called after it stops being called for\n // N milliseconds. If `immediate` is passed, trigger the function on the\n // leading edge, instead of the trailing.\n _.debounce = function(func, wait, immediate) {\n var timeout, args, context, timestamp, result;\n\n var later = function() {\n var last = _.now() - timestamp;\n\n if (last < wait && last > 0) {\n timeout = setTimeout(later, wait - last);\n } else {\n timeout = null;\n if (!immediate) {\n result = func.apply(context, args);\n if (!timeout) context = args = null;\n }\n }\n };\n\n return function() {\n context = this;\n args = arguments;\n timestamp = _.now();\n var callNow = immediate && !timeout;\n if (!timeout) timeout = setTimeout(later, wait);\n if (callNow) {\n result = func.apply(context, args);\n context = args = null;\n }\n\n return result;\n };\n };\n\n // Returns the first function passed as an argument to the second,\n // allowing you to adjust arguments, run code before and after, and\n // conditionally execute the original function.\n _.wrap = function(func, wrapper) {\n return _.partial(wrapper, func);\n };\n\n // Returns a negated version of the passed-in predicate.\n _.negate = function(predicate) {\n return function() {\n return !predicate.apply(this, arguments);\n };\n };\n\n // Returns a function that is the composition of a list of functions, each\n // consuming the return value of the function that follows.\n _.compose = function() {\n var args = arguments;\n var start = args.length - 1;\n return function() {\n var i = start;\n var result = args[start].apply(this, arguments);\n while (i--) result = args[i].call(this, result);\n return result;\n };\n };\n\n // Returns a function that will only be executed after being called N times.\n _.after = function(times, func) {\n return function() {\n if (--times < 1) {\n return func.apply(this, arguments);\n }\n };\n };\n\n // Returns a function that will only be executed before being called N times.\n _.before = function(times, func) {\n var memo;\n return function() {\n if (--times > 0) {\n memo = func.apply(this, arguments);\n } else {\n func = null;\n }\n return memo;\n };\n };\n\n // Returns a function that will be executed at most one time, no matter how\n // often you call it. Useful for lazy initialization.\n _.once = _.partial(_.before, 2);\n\n // Object Functions\n // ----------------\n\n // Retrieve the names of an object's properties.\n // Delegates to **ECMAScript 5**'s native `Object.keys`\n _.keys = function(obj) {\n if (!_.isObject(obj)) return [];\n if (nativeKeys) return nativeKeys(obj);\n var keys = [];\n for (var key in obj) if (_.has(obj, key)) keys.push(key);\n return keys;\n };\n\n // Retrieve the values of an object's properties.\n _.values = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var values = Array(length);\n for (var i = 0; i < length; i++) {\n values[i] = obj[keys[i]];\n }\n return values;\n };\n\n // Convert an object into a list of `[key, value]` pairs.\n _.pairs = function(obj) {\n var keys = _.keys(obj);\n var length = keys.length;\n var pairs = Array(length);\n for (var i = 0; i < length; i++) {\n pairs[i] = [keys[i], obj[keys[i]]];\n }\n return pairs;\n };\n\n // Invert the keys and values of an object. The values must be serializable.\n _.invert = function(obj) {\n var result = {};\n var keys = _.keys(obj);\n for (var i = 0, length = keys.length; i < length; i++) {\n result[obj[keys[i]]] = keys[i];\n }\n return result;\n };\n\n // Return a sorted list of the function names available on the object.\n // Aliased as `methods`\n _.functions = _.methods = function(obj) {\n var names = [];\n for (var key in obj) {\n if (_.isFunction(obj[key])) names.push(key);\n }\n return names.sort();\n };\n\n // Extend a given object with all the properties in passed-in object(s).\n _.extend = function(obj) {\n if (!_.isObject(obj)) return obj;\n var source, prop;\n for (var i = 1, length = arguments.length; i < length; i++) {\n source = arguments[i];\n for (prop in source) {\n if (hasOwnProperty.call(source, prop)) {\n obj[prop] = source[prop];\n }\n }\n }\n return obj;\n };\n\n // Return a copy of the object only containing the whitelisted properties.\n _.pick = function(obj, iteratee, context) {\n var result = {}, key;\n if (obj == null) return result;\n if (_.isFunction(iteratee)) {\n iteratee = createCallback(iteratee, context);\n for (key in obj) {\n var value = obj[key];\n if (iteratee(value, key, obj)) result[key] = value;\n }\n } else {\n var keys = concat.apply([], slice.call(arguments, 1));\n obj = new Object(obj);\n for (var i = 0, length = keys.length; i < length; i++) {\n key = keys[i];\n if (key in obj) result[key] = obj[key];\n }\n }\n return result;\n };\n\n // Return a copy of the object without the blacklisted properties.\n _.omit = function(obj, iteratee, context) {\n if (_.isFunction(iteratee)) {\n iteratee = _.negate(iteratee);\n } else {\n var keys = _.map(concat.apply([], slice.call(arguments, 1)), String);\n iteratee = function(value, key) {\n return !_.contains(keys, key);\n };\n }\n return _.pick(obj, iteratee, context);\n };\n\n // Fill in a given object with default properties.\n _.defaults = function(obj) {\n if (!_.isObject(obj)) return obj;\n for (var i = 1, length = arguments.length; i < length; i++) {\n var source = arguments[i];\n for (var prop in source) {\n if (obj[prop] === void 0) obj[prop] = source[prop];\n }\n }\n return obj;\n };\n\n // Create a (shallow-cloned) duplicate of an object.\n _.clone = function(obj) {\n if (!_.isObject(obj)) return obj;\n return _.isArray(obj) ? obj.slice() : _.extend({}, obj);\n };\n\n // Invokes interceptor with the obj, and then returns obj.\n // The primary purpose of this method is to \"tap into\" a method chain, in\n // order to perform operations on intermediate results within the chain.\n _.tap = function(obj, interceptor) {\n interceptor(obj);\n return obj;\n };\n\n // Internal recursive comparison function for `isEqual`.\n var eq = function(a, b, aStack, bStack) {\n // Identical objects are equal. `0 === -0`, but they aren't identical.\n // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).\n if (a === b) return a !== 0 || 1 / a === 1 / b;\n // A strict comparison is necessary because `null == undefined`.\n if (a == null || b == null) return a === b;\n // Unwrap any wrapped objects.\n if (a instanceof _) a = a._wrapped;\n if (b instanceof _) b = b._wrapped;\n // Compare `[[Class]]` names.\n var className = toString.call(a);\n if (className !== toString.call(b)) return false;\n switch (className) {\n // Strings, numbers, regular expressions, dates, and booleans are compared by value.\n case '[object RegExp]':\n // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')\n case '[object String]':\n // Primitives and their corresponding object wrappers are equivalent; thus, `\"5\"` is\n // equivalent to `new String(\"5\")`.\n return '' + a === '' + b;\n case '[object Number]':\n // `NaN`s are equivalent, but non-reflexive.\n // Object(NaN) is equivalent to NaN\n if (+a !== +a) return +b !== +b;\n // An `egal` comparison is performed for other numeric values.\n return +a === 0 ? 1 / +a === 1 / b : +a === +b;\n case '[object Date]':\n case '[object Boolean]':\n // Coerce dates and booleans to numeric primitive values. Dates are compared by their\n // millisecond representations. Note that invalid dates with millisecond representations\n // of `NaN` are not equivalent.\n return +a === +b;\n }\n if (typeof a != 'object' || typeof b != 'object') return false;\n // Assume equality for cyclic structures. The algorithm for detecting cyclic\n // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.\n var length = aStack.length;\n while (length--) {\n // Linear search. Performance is inversely proportional to the number of\n // unique nested structures.\n if (aStack[length] === a) return bStack[length] === b;\n }\n // Objects with different constructors are not equivalent, but `Object`s\n // from different frames are.\n var aCtor = a.constructor, bCtor = b.constructor;\n if (\n aCtor !== bCtor &&\n // Handle Object.create(x) cases\n 'constructor' in a && 'constructor' in b &&\n !(_.isFunction(aCtor) && aCtor instanceof aCtor &&\n _.isFunction(bCtor) && bCtor instanceof bCtor)\n ) {\n return false;\n }\n // Add the first object to the stack of traversed objects.\n aStack.push(a);\n bStack.push(b);\n var size, result;\n // Recursively compare objects and arrays.\n if (className === '[object Array]') {\n // Compare array lengths to determine if a deep comparison is necessary.\n size = a.length;\n result = size === b.length;\n if (result) {\n // Deep compare the contents, ignoring non-numeric properties.\n while (size--) {\n if (!(result = eq(a[size], b[size], aStack, bStack))) break;\n }\n }\n } else {\n // Deep compare objects.\n var keys = _.keys(a), key;\n size = keys.length;\n // Ensure that both objects contain the same number of properties before comparing deep equality.\n result = _.keys(b).length === size;\n if (result) {\n while (size--) {\n // Deep compare each member\n key = keys[size];\n if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;\n }\n }\n }\n // Remove the first object from the stack of traversed objects.\n aStack.pop();\n bStack.pop();\n return result;\n };\n\n // Perform a deep comparison to check if two objects are equal.\n _.isEqual = function(a, b) {\n return eq(a, b, [], []);\n };\n\n // Is a given array, string, or object empty?\n // An \"empty\" object has no enumerable own-properties.\n _.isEmpty = function(obj) {\n if (obj == null) return true;\n if (_.isArray(obj) || _.isString(obj) || _.isArguments(obj)) return obj.length === 0;\n for (var key in obj) if (_.has(obj, key)) return false;\n return true;\n };\n\n // Is a given value a DOM element?\n _.isElement = function(obj) {\n return !!(obj && obj.nodeType === 1);\n };\n\n // Is a given value an array?\n // Delegates to ECMA5's native Array.isArray\n _.isArray = nativeIsArray || function(obj) {\n return toString.call(obj) === '[object Array]';\n };\n\n // Is a given variable an object?\n _.isObject = function(obj) {\n var type = typeof obj;\n return type === 'function' || type === 'object' && !!obj;\n };\n\n // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp.\n _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {\n _['is' + name] = function(obj) {\n return toString.call(obj) === '[object ' + name + ']';\n };\n });\n\n // Define a fallback version of the method in browsers (ahem, IE), where\n // there isn't any inspectable \"Arguments\" type.\n if (!_.isArguments(arguments)) {\n _.isArguments = function(obj) {\n return _.has(obj, 'callee');\n };\n }\n\n // Optimize `isFunction` if appropriate. Work around an IE 11 bug.\n if (typeof /./ !== 'function') {\n _.isFunction = function(obj) {\n return typeof obj == 'function' || false;\n };\n }\n\n // Is a given object a finite number?\n _.isFinite = function(obj) {\n return isFinite(obj) && !isNaN(parseFloat(obj));\n };\n\n // Is the given value `NaN`? (NaN is the only number which does not equal itself).\n _.isNaN = function(obj) {\n return _.isNumber(obj) && obj !== +obj;\n };\n\n // Is a given value a boolean?\n _.isBoolean = function(obj) {\n return obj === true || obj === false || toString.call(obj) === '[object Boolean]';\n };\n\n // Is a given value equal to null?\n _.isNull = function(obj) {\n return obj === null;\n };\n\n // Is a given variable undefined?\n _.isUndefined = function(obj) {\n return obj === void 0;\n };\n\n // Shortcut function for checking if an object has a given property directly\n // on itself (in other words, not on a prototype).\n _.has = function(obj, key) {\n return obj != null && hasOwnProperty.call(obj, key);\n };\n\n // Utility Functions\n // -----------------\n\n // Run Underscore.js in *noConflict* mode, returning the `_` variable to its\n // previous owner. Returns a reference to the Underscore object.\n _.noConflict = function() {\n root._ = previousUnderscore;\n return this;\n };\n\n // Keep the identity function around for default iteratees.\n _.identity = function(value) {\n return value;\n };\n\n // Predicate-generating functions. Often useful outside of Underscore.\n _.constant = function(value) {\n return function() {\n return value;\n };\n };\n\n _.noop = function(){};\n\n _.property = function(key) {\n return function(obj) {\n return obj[key];\n };\n };\n\n // Returns a predicate for checking whether an object has a given set of `key:value` pairs.\n _.matches = function(attrs) {\n var pairs = _.pairs(attrs), length = pairs.length;\n return function(obj) {\n if (obj == null) return !length;\n obj = new Object(obj);\n for (var i = 0; i < length; i++) {\n var pair = pairs[i], key = pair[0];\n if (pair[1] !== obj[key] || !(key in obj)) return false;\n }\n return true;\n };\n };\n\n // Run a function **n** times.\n _.times = function(n, iteratee, context) {\n var accum = Array(Math.max(0, n));\n iteratee = createCallback(iteratee, context, 1);\n for (var i = 0; i < n; i++) accum[i] = iteratee(i);\n return accum;\n };\n\n // Return a random integer between min and max (inclusive).\n _.random = function(min, max) {\n if (max == null) {\n max = min;\n min = 0;\n }\n return min + Math.floor(Math.random() * (max - min + 1));\n };\n\n // A (possibly faster) way to get the current timestamp as an integer.\n _.now = Date.now || function() {\n return new Date().getTime();\n };\n\n // List of HTML entities for escaping.\n var escapeMap = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '`': '`'\n };\n var unescapeMap = _.invert(escapeMap);\n\n // Functions for escaping and unescaping strings to/from HTML interpolation.\n var createEscaper = function(map) {\n var escaper = function(match) {\n return map[match];\n };\n // Regexes for identifying a key that needs to be escaped\n var source = '(?:' + _.keys(map).join('|') + ')';\n var testRegexp = RegExp(source);\n var replaceRegexp = RegExp(source, 'g');\n return function(string) {\n string = string == null ? '' : '' + string;\n return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;\n };\n };\n _.escape = createEscaper(escapeMap);\n _.unescape = createEscaper(unescapeMap);\n\n // If the value of the named `property` is a function then invoke it with the\n // `object` as context; otherwise, return it.\n _.result = function(object, property) {\n if (object == null) return void 0;\n var value = object[property];\n return _.isFunction(value) ? object[property]() : value;\n };\n\n // Generate a unique integer id (unique within the entire client session).\n // Useful for temporary DOM ids.\n var idCounter = 0;\n _.uniqueId = function(prefix) {\n var id = ++idCounter + '';\n return prefix ? prefix + id : id;\n };\n\n // By default, Underscore uses ERB-style template delimiters, change the\n // following template settings to use alternative delimiters.\n _.templateSettings = {\n evaluate : /<%([\\s\\S]+?)%>/g,\n interpolate : /<%=([\\s\\S]+?)%>/g,\n escape : /<%-([\\s\\S]+?)%>/g\n };\n\n // When customizing `templateSettings`, if you don't want to define an\n // interpolation, evaluation or escaping regex, we need one that is\n // guaranteed not to match.\n var noMatch = /(.)^/;\n\n // Certain characters need to be escaped so that they can be put into a\n // string literal.\n var escapes = {\n \"'\": \"'\",\n '\\\\': '\\\\',\n '\\r': 'r',\n '\\n': 'n',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n var escaper = /\\\\|'|\\r|\\n|\\u2028|\\u2029/g;\n\n var escapeChar = function(match) {\n return '\\\\' + escapes[match];\n };\n\n // JavaScript micro-templating, similar to John Resig's implementation.\n // Underscore templating handles arbitrary delimiters, preserves whitespace,\n // and correctly escapes quotes within interpolated code.\n // NB: `oldSettings` only exists for backwards compatibility.\n _.template = function(text, settings, oldSettings) {\n if (!settings && oldSettings) settings = oldSettings;\n settings = _.defaults({}, settings, _.templateSettings);\n\n // Combine delimiters into one regular expression via alternation.\n var matcher = RegExp([\n (settings.escape || noMatch).source,\n (settings.interpolate || noMatch).source,\n (settings.evaluate || noMatch).source\n ].join('|') + '|$', 'g');\n\n // Compile the template source, escaping string literals appropriately.\n var index = 0;\n var source = \"__p+='\";\n text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {\n source += text.slice(index, offset).replace(escaper, escapeChar);\n index = offset + match.length;\n\n if (escape) {\n source += \"'+\\n((__t=(\" + escape + \"))==null?'':_.escape(__t))+\\n'\";\n } else if (interpolate) {\n source += \"'+\\n((__t=(\" + interpolate + \"))==null?'':__t)+\\n'\";\n } else if (evaluate) {\n source += \"';\\n\" + evaluate + \"\\n__p+='\";\n }\n\n // Adobe VMs need the match returned to produce the correct offest.\n return match;\n });\n source += \"';\\n\";\n\n // If a variable is not specified, place data values in local scope.\n if (!settings.variable) source = 'with(obj||{}){\\n' + source + '}\\n';\n\n source = \"var __t,__p='',__j=Array.prototype.join,\" +\n \"print=function(){__p+=__j.call(arguments,'');};\\n\" +\n source + 'return __p;\\n';\n\n try {\n var render = new Function(settings.variable || 'obj', '_', source);\n } catch (e) {\n e.source = source;\n throw e;\n }\n\n var template = function(data) {\n return render.call(this, data, _);\n };\n\n // Provide the compiled source as a convenience for precompilation.\n var argument = settings.variable || 'obj';\n template.source = 'function(' + argument + '){\\n' + source + '}';\n\n return template;\n };\n\n // Add a \"chain\" function. Start chaining a wrapped Underscore object.\n _.chain = function(obj) {\n var instance = _(obj);\n instance._chain = true;\n return instance;\n };\n\n // OOP\n // ---------------\n // If Underscore is called as a function, it returns a wrapped object that\n // can be used OO-style. This wrapper holds altered versions of all the\n // underscore functions. Wrapped objects may be chained.\n\n // Helper function to continue chaining intermediate results.\n var result = function(obj) {\n return this._chain ? _(obj).chain() : obj;\n };\n\n // Add your own custom functions to the Underscore object.\n _.mixin = function(obj) {\n _.each(_.functions(obj), function(name) {\n var func = _[name] = obj[name];\n _.prototype[name] = function() {\n var args = [this._wrapped];\n push.apply(args, arguments);\n return result.call(this, func.apply(_, args));\n };\n });\n };\n\n // Add all of the Underscore functions to the wrapper object.\n _.mixin(_);\n\n // Add all mutator Array functions to the wrapper.\n _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n var obj = this._wrapped;\n method.apply(obj, arguments);\n if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0];\n return result.call(this, obj);\n };\n });\n\n // Add all accessor Array functions to the wrapper.\n _.each(['concat', 'join', 'slice'], function(name) {\n var method = ArrayProto[name];\n _.prototype[name] = function() {\n return result.call(this, method.apply(this._wrapped, arguments));\n };\n });\n\n // Extracts the result from a wrapped and chained object.\n _.prototype.value = function() {\n return this._wrapped;\n };\n\n // AMD registration happens at the end for compatibility with AMD loaders\n // that may not enforce next-turn semantics on modules. Even though general\n // practice for AMD registration is to be anonymous, underscore registers\n // as a named module because, like jQuery, it is a base library that is\n // popular enough to be bundled in a third party lib, but not be part of\n // an AMD load request. Those cases could generate an error when an\n // anonymous define() is called outside of a loader request.\n if (typeof define === 'function' && define.amd) {\n define('underscore', [], function() {\n return _;\n });\n }\n}.call(this));\n","/**\n * @license\n * lodash 3.3.1 (Custom Build) \n * Build: `lodash modern -o ./lodash.js`\n * Copyright 2012-2015 The Dojo Foundation \n * Based on Underscore.js 1.8.2 \n * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n * Available under MIT license \n */\n; (function () {\n\n /** Used as a safe reference for `undefined` in pre-ES5 environments. */\n var undefined;\n\n /** Used as the semantic version number. */\n var VERSION = '3.3.1';\n\n /** Used to compose bitmasks for wrapper metadata. */\n var BIND_FLAG = 1,\n BIND_KEY_FLAG = 2,\n CURRY_BOUND_FLAG = 4,\n CURRY_FLAG = 8,\n CURRY_RIGHT_FLAG = 16,\n PARTIAL_FLAG = 32,\n PARTIAL_RIGHT_FLAG = 64,\n REARG_FLAG = 128,\n ARY_FLAG = 256;\n\n /** Used as default options for `_.trunc`. */\n var DEFAULT_TRUNC_LENGTH = 30,\n DEFAULT_TRUNC_OMISSION = '...';\n\n /** Used to detect when a function becomes hot. */\n var HOT_COUNT = 150,\n HOT_SPAN = 16;\n\n /** Used to indicate the type of lazy iteratees. */\n var LAZY_FILTER_FLAG = 0,\n LAZY_MAP_FLAG = 1,\n LAZY_WHILE_FLAG = 2;\n\n /** Used as the `TypeError` message for \"Functions\" methods. */\n var FUNC_ERROR_TEXT = 'Expected a function';\n\n /** Used as the internal argument placeholder. */\n var PLACEHOLDER = '__lodash_placeholder__';\n\n /** `Object#toString` result references. */\n var argsTag = '[object Arguments]',\n arrayTag = '[object Array]',\n boolTag = '[object Boolean]',\n dateTag = '[object Date]',\n errorTag = '[object Error]',\n funcTag = '[object Function]',\n mapTag = '[object Map]',\n numberTag = '[object Number]',\n objectTag = '[object Object]',\n regexpTag = '[object RegExp]',\n setTag = '[object Set]',\n stringTag = '[object String]',\n weakMapTag = '[object WeakMap]';\n\n var arrayBufferTag = '[object ArrayBuffer]',\n float32Tag = '[object Float32Array]',\n float64Tag = '[object Float64Array]',\n int8Tag = '[object Int8Array]',\n int16Tag = '[object Int16Array]',\n int32Tag = '[object Int32Array]',\n uint8Tag = '[object Uint8Array]',\n uint8ClampedTag = '[object Uint8ClampedArray]',\n uint16Tag = '[object Uint16Array]',\n uint32Tag = '[object Uint32Array]';\n\n /** Used to match empty string literals in compiled template source. */\n var reEmptyStringLeading = /\\b__p \\+= '';/g,\n reEmptyStringMiddle = /\\b(__p \\+=) '' \\+/g,\n reEmptyStringTrailing = /(__e\\(.*?\\)|\\b__t\\)) \\+\\n'';/g;\n\n /** Used to match HTML entities and HTML characters. */\n var reEscapedHtml = /&(?:amp|lt|gt|quot|#39|#96);/g,\n reUnescapedHtml = /[&<>\"'`]/g,\n reHasEscapedHtml = RegExp(reEscapedHtml.source),\n reHasUnescapedHtml = RegExp(reUnescapedHtml.source);\n\n /** Used to match template delimiters. */\n var reEscape = /<%-([\\s\\S]+?)%>/g,\n reEvaluate = /<%([\\s\\S]+?)%>/g,\n reInterpolate = /<%=([\\s\\S]+?)%>/g;\n\n /**\n * Used to match ES template delimiters.\n * See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-template-literal-lexical-components)\n * for more details.\n */\n var reEsTemplate = /\\$\\{([^\\\\}]*(?:\\\\.[^\\\\}]*)*)\\}/g;\n\n /** Used to match `RegExp` flags from their coerced string values. */\n var reFlags = /\\w*$/;\n\n /** Used to detect named functions. */\n var reFuncName = /^\\s*function[ \\n\\r\\t]+\\w/;\n\n /** Used to detect hexadecimal string values. */\n var reHexPrefix = /^0[xX]/;\n\n /** Used to detect host constructors (Safari > 5). */\n var reHostCtor = /^\\[object .+?Constructor\\]$/;\n\n /** Used to match latin-1 supplementary letters (excluding mathematical operators). */\n var reLatin1 = /[\\xc0-\\xd6\\xd8-\\xde\\xdf-\\xf6\\xf8-\\xff]/g;\n\n /** Used to ensure capturing order of template delimiters. */\n var reNoMatch = /($^)/;\n\n /**\n * Used to match `RegExp` special characters.\n * See this [article on `RegExp` characters](http://www.regular-expressions.info/characters.html#special)\n * for more details.\n */\n var reRegExpChars = /[.*+?^${}()|[\\]\\/\\\\]/g,\n reHasRegExpChars = RegExp(reRegExpChars.source);\n\n /** Used to detect functions containing a `this` reference. */\n var reThis = /\\bthis\\b/;\n\n /** Used to match unescaped characters in compiled string literals. */\n var reUnescapedString = /['\\n\\r\\u2028\\u2029\\\\]/g;\n\n /** Used to match words to create compound words. */\n var reWords = (function () {\n var upper = '[A-Z\\\\xc0-\\\\xd6\\\\xd8-\\\\xde]',\n lower = '[a-z\\\\xdf-\\\\xf6\\\\xf8-\\\\xff]+';\n\n return RegExp(upper + '{2,}(?=' + upper + lower + ')|' + upper + '?' + lower + '|' + upper + '+|[0-9]+', 'g');\n }());\n\n /** Used to detect and test for whitespace. */\n var whitespace = (\n // Basic whitespace characters.\n ' \\t\\x0b\\f\\xa0\\ufeff' +\n\n // Line terminators.\n '\\n\\r\\u2028\\u2029' +\n\n // Unicode category \"Zs\" space separators.\n '\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000'\n );\n\n /** Used to assign default `context` object properties. */\n var contextProps = [\n 'Array', 'ArrayBuffer', 'Date', 'Error', 'Float32Array', 'Float64Array',\n 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number',\n 'Object', 'RegExp', 'Set', 'String', '_', 'clearTimeout', 'document',\n 'isFinite', 'parseInt', 'setTimeout', 'TypeError', 'Uint8Array',\n 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',\n 'window', 'WinRTError'\n ];\n\n /** Used to make template sourceURLs easier to identify. */\n var templateCounter = -1;\n\n /** Used to identify `toStringTag` values of typed arrays. */\n var typedArrayTags = {};\n typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =\n typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =\n typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =\n typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =\n typedArrayTags[uint32Tag] = true;\n typedArrayTags[argsTag] = typedArrayTags[arrayTag] =\n typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =\n typedArrayTags[dateTag] = typedArrayTags[errorTag] =\n typedArrayTags[funcTag] = typedArrayTags[mapTag] =\n typedArrayTags[numberTag] = typedArrayTags[objectTag] =\n typedArrayTags[regexpTag] = typedArrayTags[setTag] =\n typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;\n\n /** Used to identify `toStringTag` values supported by `_.clone`. */\n var cloneableTags = {};\n cloneableTags[argsTag] = cloneableTags[arrayTag] =\n cloneableTags[arrayBufferTag] = cloneableTags[boolTag] =\n cloneableTags[dateTag] = cloneableTags[float32Tag] =\n cloneableTags[float64Tag] = cloneableTags[int8Tag] =\n cloneableTags[int16Tag] = cloneableTags[int32Tag] =\n cloneableTags[numberTag] = cloneableTags[objectTag] =\n cloneableTags[regexpTag] = cloneableTags[stringTag] =\n cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =\n cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;\n cloneableTags[errorTag] = cloneableTags[funcTag] =\n cloneableTags[mapTag] = cloneableTags[setTag] =\n cloneableTags[weakMapTag] = false;\n\n /** Used as an internal `_.debounce` options object by `_.throttle`. */\n var debounceOptions = {\n 'leading': false,\n 'maxWait': 0,\n 'trailing': false\n };\n\n /** Used to map latin-1 supplementary letters to basic latin letters. */\n var deburredLetters = {\n '\\xc0': 'A', '\\xc1': 'A', '\\xc2': 'A', '\\xc3': 'A', '\\xc4': 'A', '\\xc5': 'A',\n '\\xe0': 'a', '\\xe1': 'a', '\\xe2': 'a', '\\xe3': 'a', '\\xe4': 'a', '\\xe5': 'a',\n '\\xc7': 'C', '\\xe7': 'c',\n '\\xd0': 'D', '\\xf0': 'd',\n '\\xc8': 'E', '\\xc9': 'E', '\\xca': 'E', '\\xcb': 'E',\n '\\xe8': 'e', '\\xe9': 'e', '\\xea': 'e', '\\xeb': 'e',\n '\\xcC': 'I', '\\xcd': 'I', '\\xce': 'I', '\\xcf': 'I',\n '\\xeC': 'i', '\\xed': 'i', '\\xee': 'i', '\\xef': 'i',\n '\\xd1': 'N', '\\xf1': 'n',\n '\\xd2': 'O', '\\xd3': 'O', '\\xd4': 'O', '\\xd5': 'O', '\\xd6': 'O', '\\xd8': 'O',\n '\\xf2': 'o', '\\xf3': 'o', '\\xf4': 'o', '\\xf5': 'o', '\\xf6': 'o', '\\xf8': 'o',\n '\\xd9': 'U', '\\xda': 'U', '\\xdb': 'U', '\\xdc': 'U',\n '\\xf9': 'u', '\\xfa': 'u', '\\xfb': 'u', '\\xfc': 'u',\n '\\xdd': 'Y', '\\xfd': 'y', '\\xff': 'y',\n '\\xc6': 'Ae', '\\xe6': 'ae',\n '\\xde': 'Th', '\\xfe': 'th',\n '\\xdf': 'ss'\n };\n\n /** Used to map characters to HTML entities. */\n var htmlEscapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '\"': '"',\n \"'\": ''',\n '`': '`'\n };\n\n /** Used to map HTML entities to characters. */\n var htmlUnescapes = {\n '&': '&',\n '<': '<',\n '>': '>',\n '"': '\"',\n ''': \"'\",\n '`': '`'\n };\n\n /** Used to determine if values are of the language type `Object`. */\n var objectTypes = {\n 'function': true,\n 'object': true\n };\n\n /** Used to escape characters for inclusion in compiled string literals. */\n var stringEscapes = {\n '\\\\': '\\\\',\n \"'\": \"'\",\n '\\n': 'n',\n '\\r': 'r',\n '\\u2028': 'u2028',\n '\\u2029': 'u2029'\n };\n\n /**\n * Used as a reference to the global object.\n *\n * The `this` value is used if it is the global object to avoid Greasemonkey's\n * restricted `window` object, otherwise the `window` object is used.\n */\n var root = (objectTypes[typeof window] && window !== (this && this.window)) ? window : this;\n\n /** Detect free variable `exports`. */\n var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;\n\n /** Detect free variable `module`. */\n var freeModule = objectTypes[typeof module] && module && !module.nodeType && module;\n\n /** Detect free variable `global` from Node.js or Browserified code and use it as `root`. */\n var freeGlobal = freeExports && freeModule && typeof global == 'object' && global;\n if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal)) {\n root = freeGlobal;\n }\n\n /** Detect the popular CommonJS extension `module.exports`. */\n var moduleExports = freeModule && freeModule.exports === freeExports && freeExports;\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * The base implementation of `compareAscending` which compares values and\n * sorts them in ascending order without guaranteeing a stable sort.\n *\n * @private\n * @param {*} value The value to compare to `other`.\n * @param {*} other The value to compare to `value`.\n * @returns {number} Returns the sort order indicator for `value`.\n */\n function baseCompareAscending(value, other) {\n if (value !== other) {\n var valIsReflexive = value === value,\n othIsReflexive = other === other;\n\n if (value > other || !valIsReflexive || (typeof value == 'undefined' && othIsReflexive)) {\n return 1;\n }\n if (value < other || !othIsReflexive || (typeof other == 'undefined' && valIsReflexive)) {\n return -1;\n }\n }\n return 0;\n }\n\n /**\n * The base implementation of `_.indexOf` without support for binary searches.\n *\n * @private\n * @param {Array} array The array to search.\n * @param {*} value The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {number} Returns the index of the matched value, else `-1`.\n */\n function baseIndexOf(array, value, fromIndex) {\n if (value !== value) {\n return indexOfNaN(array, fromIndex);\n }\n var index = (fromIndex || 0) - 1,\n length = array.length;\n\n while (++index < length) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * The base implementation of `_.isFunction` without support for environments\n * with incorrect `typeof` results.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n */\n function baseIsFunction(value) {\n // Avoid a Chakra JIT bug in compatibility modes of IE 11.\n // See https://github.com/jashkenas/underscore/issues/1621 for more details.\n return typeof value == 'function' || false;\n }\n\n /**\n * The base implementation of `_.sortBy` and `_.sortByAll` which uses `comparer`\n * to define the sort order of `array` and replaces criteria objects with their\n * corresponding values.\n *\n * @private\n * @param {Array} array The array to sort.\n * @param {Function} comparer The function to define sort order.\n * @returns {Array} Returns `array`.\n */\n function baseSortBy(array, comparer) {\n var length = array.length;\n\n array.sort(comparer);\n while (length--) {\n array[length] = array[length].value;\n }\n return array;\n }\n\n /**\n * Converts `value` to a string if it is not one. An empty string is returned\n * for `null` or `undefined` values.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {string} Returns the string.\n */\n function baseToString(value) {\n if (typeof value == 'string') {\n return value;\n }\n return value == null ? '' : (value + '');\n }\n\n /**\n * Used by `_.max` and `_.min` as the default callback for string values.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the code unit of the first character of the string.\n */\n function charAtCallback(string) {\n return string.charCodeAt(0);\n }\n\n /**\n * Used by `_.trim` and `_.trimLeft` to get the index of the first character\n * of `string` that is not found in `chars`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @param {string} chars The characters to find.\n * @returns {number} Returns the index of the first character not found in `chars`.\n */\n function charsLeftIndex(string, chars) {\n var index = -1,\n length = string.length;\n\n while (++index < length && chars.indexOf(string.charAt(index)) > -1) { }\n return index;\n }\n\n /**\n * Used by `_.trim` and `_.trimRight` to get the index of the last character\n * of `string` that is not found in `chars`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @param {string} chars The characters to find.\n * @returns {number} Returns the index of the last character not found in `chars`.\n */\n function charsRightIndex(string, chars) {\n var index = string.length;\n\n while (index-- && chars.indexOf(string.charAt(index)) > -1) { }\n return index;\n }\n\n /**\n * Used by `_.sortBy` to compare transformed elements of a collection and stable\n * sort them in ascending order.\n *\n * @private\n * @param {Object} object The object to compare to `other`.\n * @param {Object} other The object to compare to `object`.\n * @returns {number} Returns the sort order indicator for `object`.\n */\n function compareAscending(object, other) {\n return baseCompareAscending(object.criteria, other.criteria) || (object.index - other.index);\n }\n\n /**\n * Used by `_.sortByAll` to compare multiple properties of each element\n * in a collection and stable sort them in ascending order.\n *\n * @private\n * @param {Object} object The object to compare to `other`.\n * @param {Object} other The object to compare to `object`.\n * @returns {number} Returns the sort order indicator for `object`.\n */\n function compareMultipleAscending(object, other) {\n var index = -1,\n objCriteria = object.criteria,\n othCriteria = other.criteria,\n length = objCriteria.length;\n\n while (++index < length) {\n var result = baseCompareAscending(objCriteria[index], othCriteria[index]);\n if (result) {\n return result;\n }\n }\n // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications\n // that causes it, under certain circumstances, to provide the same value for\n // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247\n // for more details.\n //\n // This also ensures a stable sort in V8 and other engines.\n // See https://code.google.com/p/v8/issues/detail?id=90 for more details.\n return object.index - other.index;\n }\n\n /**\n * Used by `_.deburr` to convert latin-1 supplementary letters to basic latin letters.\n *\n * @private\n * @param {string} letter The matched letter to deburr.\n * @returns {string} Returns the deburred letter.\n */\n function deburrLetter(letter) {\n return deburredLetters[letter];\n }\n\n /**\n * Used by `_.escape` to convert characters to HTML entities.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n function escapeHtmlChar(chr) {\n return htmlEscapes[chr];\n }\n\n /**\n * Used by `_.template` to escape characters for inclusion in compiled\n * string literals.\n *\n * @private\n * @param {string} chr The matched character to escape.\n * @returns {string} Returns the escaped character.\n */\n function escapeStringChar(chr) {\n return '\\\\' + stringEscapes[chr];\n }\n\n /**\n * Gets the index at which the first occurrence of `NaN` is found in `array`.\n * If `fromRight` is provided elements of `array` are iterated from right to left.\n *\n * @private\n * @param {Array} array The array to search.\n * @param {number} [fromIndex] The index to search from.\n * @param {boolean} [fromRight] Specify iterating from right to left.\n * @returns {number} Returns the index of the matched `NaN`, else `-1`.\n */\n function indexOfNaN(array, fromIndex, fromRight) {\n var length = array.length,\n index = fromRight ? (fromIndex || length) : ((fromIndex || 0) - 1);\n\n while ((fromRight ? index-- : ++index < length)) {\n var other = array[index];\n if (other !== other) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * Checks if `value` is object-like.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is object-like, else `false`.\n */\n function isObjectLike(value) {\n return (value && typeof value == 'object') || false;\n }\n\n /**\n * Used by `trimmedLeftIndex` and `trimmedRightIndex` to determine if a\n * character code is whitespace.\n *\n * @private\n * @param {number} charCode The character code to inspect.\n * @returns {boolean} Returns `true` if `charCode` is whitespace, else `false`.\n */\n function isSpace(charCode) {\n return ((charCode <= 160 && (charCode >= 9 && charCode <= 13) || charCode == 32 || charCode == 160) || charCode == 5760 || charCode == 6158 ||\n (charCode >= 8192 && (charCode <= 8202 || charCode == 8232 || charCode == 8233 || charCode == 8239 || charCode == 8287 || charCode == 12288 || charCode == 65279)));\n }\n\n /**\n * Replaces all `placeholder` elements in `array` with an internal placeholder\n * and returns an array of their indexes.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {*} placeholder The placeholder to replace.\n * @returns {Array} Returns the new array of placeholder indexes.\n */\n function replaceHolders(array, placeholder) {\n var index = -1,\n length = array.length,\n resIndex = -1,\n result = [];\n\n while (++index < length) {\n if (array[index] === placeholder) {\n array[index] = PLACEHOLDER;\n result[++resIndex] = index;\n }\n }\n return result;\n }\n\n /**\n * An implementation of `_.uniq` optimized for sorted arrays without support\n * for callback shorthands and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The function invoked per iteration.\n * @returns {Array} Returns the new duplicate-value-free array.\n */\n function sortedUniq(array, iteratee) {\n var seen,\n index = -1,\n length = array.length,\n resIndex = -1,\n result = [];\n\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value, index, array) : value;\n\n if (!index || seen !== computed) {\n seen = computed;\n result[++resIndex] = value;\n }\n }\n return result;\n }\n\n /**\n * Used by `_.trim` and `_.trimLeft` to get the index of the first non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the first non-whitespace character.\n */\n function trimmedLeftIndex(string) {\n var index = -1,\n length = string.length;\n\n while (++index < length && isSpace(string.charCodeAt(index))) { }\n return index;\n }\n\n /**\n * Used by `_.trim` and `_.trimRight` to get the index of the last non-whitespace\n * character of `string`.\n *\n * @private\n * @param {string} string The string to inspect.\n * @returns {number} Returns the index of the last non-whitespace character.\n */\n function trimmedRightIndex(string) {\n var index = string.length;\n\n while (index-- && isSpace(string.charCodeAt(index))) { }\n return index;\n }\n\n /**\n * Used by `_.unescape` to convert HTML entities to characters.\n *\n * @private\n * @param {string} chr The matched character to unescape.\n * @returns {string} Returns the unescaped character.\n */\n function unescapeHtmlChar(chr) {\n return htmlUnescapes[chr];\n }\n\n /*--------------------------------------------------------------------------*/\n\n /**\n * Create a new pristine `lodash` function using the given `context` object.\n *\n * @static\n * @memberOf _\n * @category Utility\n * @param {Object} [context=root] The context object.\n * @returns {Function} Returns a new `lodash` function.\n * @example\n *\n * _.mixin({ 'add': function(a, b) { return a + b; } });\n *\n * var lodash = _.runInContext();\n * lodash.mixin({ 'sub': function(a, b) { return a - b; } });\n *\n * _.isFunction(_.add);\n * // => true\n * _.isFunction(_.sub);\n * // => false\n *\n * lodash.isFunction(lodash.add);\n * // => false\n * lodash.isFunction(lodash.sub);\n * // => true\n *\n * // using `context` to mock `Date#getTime` use in `_.now`\n * var mock = _.runInContext({\n * 'Date': function() {\n * return { 'getTime': getTimeMock };\n * }\n * });\n *\n * // or creating a suped-up `defer` in Node.js\n * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;\n */\n function runInContext(context) {\n // Avoid issues with some ES3 environments that attempt to use values, named\n // after built-in constructors like `Object`, for the creation of literals.\n // ES5 clears this up by stating that literals must use built-in constructors.\n // See https://es5.github.io/#x11.1.5 for more details.\n context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root;\n\n /** Native constructor references. */\n var Array = context.Array,\n Date = context.Date,\n Error = context.Error,\n Function = context.Function,\n Math = context.Math,\n Number = context.Number,\n Object = context.Object,\n RegExp = context.RegExp,\n String = context.String,\n TypeError = context.TypeError;\n\n /** Used for native method references. */\n var arrayProto = Array.prototype,\n objectProto = Object.prototype;\n\n /** Used to detect DOM support. */\n var document = (document = context.window) && document.document;\n\n /** Used to resolve the decompiled source of functions. */\n var fnToString = Function.prototype.toString;\n\n /** Used to the length of n-tuples for `_.unzip`. */\n var getLength = baseProperty('length');\n\n /** Used to check objects for own properties. */\n var hasOwnProperty = objectProto.hasOwnProperty;\n\n /** Used to generate unique IDs. */\n var idCounter = 0;\n\n /**\n * Used to resolve the `toStringTag` of values.\n * See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)\n * for more details.\n */\n var objToString = objectProto.toString;\n\n /** Used to restore the original `_` reference in `_.noConflict`. */\n var oldDash = context._;\n\n /** Used to detect if a method is native. */\n var reNative = RegExp('^' +\n escapeRegExp(objToString)\n .replace(/toString|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g, '$1.*?') + '$'\n );\n\n /** Native method references. */\n var ArrayBuffer = isNative(ArrayBuffer = context.ArrayBuffer) && ArrayBuffer,\n bufferSlice = isNative(bufferSlice = ArrayBuffer && new ArrayBuffer(0).slice) && bufferSlice,\n ceil = Math.ceil,\n clearTimeout = context.clearTimeout,\n floor = Math.floor,\n getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf,\n push = arrayProto.push,\n propertyIsEnumerable = objectProto.propertyIsEnumerable,\n Set = isNative(Set = context.Set) && Set,\n setTimeout = context.setTimeout,\n splice = arrayProto.splice,\n Uint8Array = isNative(Uint8Array = context.Uint8Array) && Uint8Array,\n WeakMap = isNative(WeakMap = context.WeakMap) && WeakMap;\n\n /** Used to clone array buffers. */\n var Float64Array = (function () {\n // Safari 5 errors when using an array buffer to initialize a typed array\n // where the array buffer's `byteLength` is not a multiple of the typed\n // array's `BYTES_PER_ELEMENT`.\n try {\n var func = isNative(func = context.Float64Array) && func,\n result = new func(new ArrayBuffer(10), 0, 1) && func;\n } catch (e) { }\n return result;\n }());\n\n /* Native method references for those with the same name as other `lodash` methods. */\n var nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray,\n nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate,\n nativeIsFinite = context.isFinite,\n nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys,\n nativeMax = Math.max,\n nativeMin = Math.min,\n nativeNow = isNative(nativeNow = Date.now) && nativeNow,\n nativeNumIsFinite = isNative(nativeNumIsFinite = Number.isFinite) && nativeNumIsFinite,\n nativeParseInt = context.parseInt,\n nativeRandom = Math.random;\n\n /** Used as references for `-Infinity` and `Infinity`. */\n var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY,\n POSITIVE_INFINITY = Number.POSITIVE_INFINITY;\n\n /** Used as references for the maximum length and index of an array. */\n var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1,\n MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,\n HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;\n\n /** Used as the size, in bytes, of each `Float64Array` element. */\n var FLOAT64_BYTES_PER_ELEMENT = Float64Array ? Float64Array.BYTES_PER_ELEMENT : 0;\n\n /**\n * Used as the maximum length of an array-like value.\n * See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.max_safe_integer)\n * for more details.\n */\n var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1;\n\n /** Used to store function metadata. */\n var metaMap = WeakMap && new WeakMap;\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` object which wraps `value` to enable implicit chaining.\n * Methods that operate on and return arrays, collections, and functions can\n * be chained together. Methods that return a boolean or single value will\n * automatically end the chain returning the unwrapped value. Explicit chaining\n * may be enabled using `_.chain`. The execution of chained methods is lazy,\n * that is, execution is deferred until `_#value` is implicitly or explicitly\n * called.\n *\n * Lazy evaluation allows several methods to support shortcut fusion. Shortcut\n * fusion is an optimization that merges iteratees to avoid creating intermediate\n * arrays and reduce the number of iteratee executions.\n *\n * Chaining is supported in custom builds as long as the `_#value` method is\n * directly or indirectly included in the build.\n *\n * In addition to lodash methods, wrappers also have the following `Array` methods:\n * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`,\n * and `unshift`\n *\n * The wrapper methods that support shortcut fusion are:\n * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`,\n * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`,\n * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`,\n * and `where`\n *\n * The chainable wrapper methods are:\n * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`,\n * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`,\n * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defer`, `delay`,\n * `difference`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `fill`,\n * `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, `forEach`,\n * `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `functions`,\n * `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, `invoke`, `keys`,\n * `keysIn`, `map`, `mapValues`, `matches`, `matchesProperty`, `memoize`, `merge`,\n * `mixin`, `negate`, `noop`, `omit`, `once`, `pairs`, `partial`, `partialRight`,\n * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`,\n * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `reverse`,\n * `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, `splice`, `spread`,\n * `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `tap`, `throttle`,\n * `thru`, `times`, `toArray`, `toPlainObject`, `transform`, `union`, `uniq`,\n * `unshift`, `unzip`, `values`, `valuesIn`, `where`, `without`, `wrap`, `xor`,\n * `zip`, and `zipObject`\n *\n * The wrapper methods that are **not** chainable by default are:\n * `attempt`, `camelCase`, `capitalize`, `clone`, `cloneDeep`, `deburr`,\n * `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`,\n * `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, `has`,\n * `identity`, `includes`, `indexOf`, `isArguments`, `isArray`, `isBoolean`,\n * `isDate`, `isElement`, `isEmpty`, `isEqual`, `isError`, `isFinite`,\n * `isFunction`, `isMatch`, `isNative`, `isNaN`, `isNull`, `isNumber`,\n * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`,\n * `isTypedArray`, `join`, `kebabCase`, `last`, `lastIndexOf`, `max`, `min`,\n * `noConflict`, `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`,\n * `random`, `reduce`, `reduceRight`, `repeat`, `result`, `runInContext`,\n * `shift`, `size`, `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`,\n * `startCase`, `startsWith`, `template`, `trim`, `trimLeft`, `trimRight`,\n * `trunc`, `unescape`, `uniqueId`, `value`, and `words`\n *\n * The wrapper method `sample` will return a wrapped value when `n` is provided,\n * otherwise an unwrapped value is returned.\n *\n * @name _\n * @constructor\n * @category Chain\n * @param {*} value The value to wrap in a `lodash` instance.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var wrapped = _([1, 2, 3]);\n *\n * // returns an unwrapped value\n * wrapped.reduce(function(sum, n) {\n * return sum + n;\n * });\n * // => 6\n *\n * // returns a wrapped value\n * var squares = wrapped.map(function(n) {\n * return n * n;\n * });\n *\n * _.isArray(squares);\n * // => false\n *\n * _.isArray(squares.value());\n * // => true\n */\n function lodash(value) {\n if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {\n if (value instanceof LodashWrapper) {\n return value;\n }\n if (hasOwnProperty.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) {\n return wrapperClone(value);\n }\n }\n return new LodashWrapper(value);\n }\n\n /**\n * The function whose prototype all chaining wrappers inherit from.\n *\n * @private\n */\n function baseLodash() {\n // No operation performed.\n }\n\n /**\n * The base constructor for creating `lodash` wrapper objects.\n *\n * @private\n * @param {*} value The value to wrap.\n * @param {boolean} [chainAll] Enable chaining for all wrapper methods.\n * @param {Array} [actions=[]] Actions to peform to resolve the unwrapped value.\n */\n function LodashWrapper(value, chainAll, actions) {\n this.__wrapped__ = value;\n this.__actions__ = actions || [];\n this.__chain__ = !!chainAll;\n }\n\n /**\n * An object environment feature flags.\n *\n * @static\n * @memberOf _\n * @type Object\n */\n var support = lodash.support = {};\n\n (function (x) {\n\n /**\n * Detect if functions can be decompiled by `Function#toString`\n * (all but Firefox OS certified apps, older Opera mobile browsers, and\n * the PlayStation 3; forced `false` for Windows 8 apps).\n *\n * @memberOf _.support\n * @type boolean\n */\n support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext);\n\n /**\n * Detect if `Function#name` is supported (all but IE).\n *\n * @memberOf _.support\n * @type boolean\n */\n support.funcNames = typeof Function.name == 'string';\n\n /**\n * Detect if the DOM is supported.\n *\n * @memberOf _.support\n * @type boolean\n */\n try {\n support.dom = document.createDocumentFragment().nodeType === 11;\n } catch (e) {\n support.dom = false;\n }\n\n /**\n * Detect if `arguments` object indexes are non-enumerable.\n *\n * In Firefox < 4, IE < 9, PhantomJS, and Safari < 5.1 `arguments` object\n * indexes are non-enumerable. Chrome < 25 and Node.js < 0.11.0 treat\n * `arguments` object indexes as non-enumerable and fail `hasOwnProperty`\n * checks for indexes that exceed their function's formal parameters with\n * associated values of `0`.\n *\n * @memberOf _.support\n * @type boolean\n */\n try {\n support.nonEnumArgs = !propertyIsEnumerable.call(arguments, 1);\n } catch (e) {\n support.nonEnumArgs = true;\n }\n }(0, 0));\n\n /**\n * By default, the template delimiters used by lodash are like those in\n * embedded Ruby (ERB). Change the following template settings to use\n * alternative delimiters.\n *\n * @static\n * @memberOf _\n * @type Object\n */\n lodash.templateSettings = {\n\n /**\n * Used to detect `data` property values to be HTML-escaped.\n *\n * @memberOf _.templateSettings\n * @type RegExp\n */\n 'escape': reEscape,\n\n /**\n * Used to detect code to be evaluated.\n *\n * @memberOf _.templateSettings\n * @type RegExp\n */\n 'evaluate': reEvaluate,\n\n /**\n * Used to detect `data` property values to inject.\n *\n * @memberOf _.templateSettings\n * @type RegExp\n */\n 'interpolate': reInterpolate,\n\n /**\n * Used to reference the data object in the template text.\n *\n * @memberOf _.templateSettings\n * @type string\n */\n 'variable': '',\n\n /**\n * Used to import variables into the compiled template.\n *\n * @memberOf _.templateSettings\n * @type Object\n */\n 'imports': {\n\n /**\n * A reference to the `lodash` function.\n *\n * @memberOf _.templateSettings.imports\n * @type Function\n */\n '_': lodash\n }\n };\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.\n *\n * @private\n * @param {*} value The value to wrap.\n */\n function LazyWrapper(value) {\n this.__wrapped__ = value;\n this.__actions__ = null;\n this.__dir__ = 1;\n this.__dropCount__ = 0;\n this.__filtered__ = false;\n this.__iteratees__ = null;\n this.__takeCount__ = POSITIVE_INFINITY;\n this.__views__ = null;\n }\n\n /**\n * Creates a clone of the lazy wrapper object.\n *\n * @private\n * @name clone\n * @memberOf LazyWrapper\n * @returns {Object} Returns the cloned `LazyWrapper` object.\n */\n function lazyClone() {\n var actions = this.__actions__,\n iteratees = this.__iteratees__,\n views = this.__views__,\n result = new LazyWrapper(this.__wrapped__);\n\n result.__actions__ = actions ? arrayCopy(actions) : null;\n result.__dir__ = this.__dir__;\n result.__dropCount__ = this.__dropCount__;\n result.__filtered__ = this.__filtered__;\n result.__iteratees__ = iteratees ? arrayCopy(iteratees) : null;\n result.__takeCount__ = this.__takeCount__;\n result.__views__ = views ? arrayCopy(views) : null;\n return result;\n }\n\n /**\n * Reverses the direction of lazy iteration.\n *\n * @private\n * @name reverse\n * @memberOf LazyWrapper\n * @returns {Object} Returns the new reversed `LazyWrapper` object.\n */\n function lazyReverse() {\n if (this.__filtered__) {\n var result = new LazyWrapper(this);\n result.__dir__ = -1;\n result.__filtered__ = true;\n } else {\n result = this.clone();\n result.__dir__ *= -1;\n }\n return result;\n }\n\n /**\n * Extracts the unwrapped value from its lazy wrapper.\n *\n * @private\n * @name value\n * @memberOf LazyWrapper\n * @returns {*} Returns the unwrapped value.\n */\n function lazyValue() {\n var array = this.__wrapped__.value();\n if (!isArray(array)) {\n return baseWrapperValue(array, this.__actions__);\n }\n var dir = this.__dir__,\n isRight = dir < 0,\n view = getView(0, array.length, this.__views__),\n start = view.start,\n end = view.end,\n length = end - start,\n dropCount = this.__dropCount__,\n takeCount = nativeMin(length, this.__takeCount__),\n index = isRight ? end : start - 1,\n iteratees = this.__iteratees__,\n iterLength = iteratees ? iteratees.length : 0,\n resIndex = 0,\n result = [];\n\n outer:\n while (length-- && resIndex < takeCount) {\n index += dir;\n\n var iterIndex = -1,\n value = array[index];\n\n while (++iterIndex < iterLength) {\n var data = iteratees[iterIndex],\n iteratee = data.iteratee,\n computed = iteratee(value, index, array),\n type = data.type;\n\n if (type == LAZY_MAP_FLAG) {\n value = computed;\n } else if (!computed) {\n if (type == LAZY_FILTER_FLAG) {\n continue outer;\n } else {\n break outer;\n }\n }\n }\n if (dropCount) {\n dropCount--;\n } else {\n result[resIndex++] = value;\n }\n }\n return result;\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a cache object to store key/value pairs.\n *\n * @private\n * @static\n * @name Cache\n * @memberOf _.memoize\n */\n function MapCache() {\n this.__data__ = {};\n }\n\n /**\n * Removes `key` and its value from the cache.\n *\n * @private\n * @name delete\n * @memberOf _.memoize.Cache\n * @param {string} key The key of the value to remove.\n * @returns {boolean} Returns `true` if the entry was removed successfully, else `false`.\n */\n function mapDelete(key) {\n return this.has(key) && delete this.__data__[key];\n }\n\n /**\n * Gets the cached value for `key`.\n *\n * @private\n * @name get\n * @memberOf _.memoize.Cache\n * @param {string} key The key of the value to get.\n * @returns {*} Returns the cached value.\n */\n function mapGet(key) {\n return key == '__proto__' ? undefined : this.__data__[key];\n }\n\n /**\n * Checks if a cached value for `key` exists.\n *\n * @private\n * @name has\n * @memberOf _.memoize.Cache\n * @param {string} key The key of the entry to check.\n * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.\n */\n function mapHas(key) {\n return key != '__proto__' && hasOwnProperty.call(this.__data__, key);\n }\n\n /**\n * Adds `value` to `key` of the cache.\n *\n * @private\n * @name set\n * @memberOf _.memoize.Cache\n * @param {string} key The key of the value to cache.\n * @param {*} value The value to cache.\n * @returns {Object} Returns the cache object.\n */\n function mapSet(key, value) {\n if (key != '__proto__') {\n this.__data__[key] = value;\n }\n return this;\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n *\n * Creates a cache object to store unique values.\n *\n * @private\n * @param {Array} [values] The values to cache.\n */\n function SetCache(values) {\n var length = values ? values.length : 0;\n\n this.data = { 'hash': nativeCreate(null), 'set': new Set };\n while (length--) {\n this.push(values[length]);\n }\n }\n\n /**\n * Checks if `value` is in `cache` mimicking the return signature of\n * `_.indexOf` by returning `0` if the value is found, else `-1`.\n *\n * @private\n * @param {Object} cache The cache to search.\n * @param {*} value The value to search for.\n * @returns {number} Returns `0` if `value` is found, else `-1`.\n */\n function cacheIndexOf(cache, value) {\n var data = cache.data,\n result = (typeof value == 'string' || isObject(value)) ? data.set.has(value) : data.hash[value];\n\n return result ? 0 : -1;\n }\n\n /**\n * Adds `value` to the cache.\n *\n * @private\n * @name push\n * @memberOf SetCache\n * @param {*} value The value to cache.\n */\n function cachePush(value) {\n var data = this.data;\n if (typeof value == 'string' || isObject(value)) {\n data.set.add(value);\n } else {\n data.hash[value] = true;\n }\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Copies the values of `source` to `array`.\n *\n * @private\n * @param {Array} source The array to copy values from.\n * @param {Array} [array=[]] The array to copy values to.\n * @returns {Array} Returns `array`.\n */\n function arrayCopy(source, array) {\n var index = -1,\n length = source.length;\n\n array || (array = Array(length));\n while (++index < length) {\n array[index] = source[index];\n }\n return array;\n }\n\n /**\n * A specialized version of `_.forEach` for arrays without support for callback\n * shorthands or `this` binding.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEach(array, iteratee) {\n var index = -1,\n length = array.length;\n\n while (++index < length) {\n if (iteratee(array[index], index, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.forEachRight` for arrays without support for\n * callback shorthands or `this` binding.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns `array`.\n */\n function arrayEachRight(array, iteratee) {\n var length = array.length;\n\n while (length--) {\n if (iteratee(array[length], length, array) === false) {\n break;\n }\n }\n return array;\n }\n\n /**\n * A specialized version of `_.every` for arrays without support for callback\n * shorthands or `this` binding.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n */\n function arrayEvery(array, predicate) {\n var index = -1,\n length = array.length;\n\n while (++index < length) {\n if (!predicate(array[index], index, array)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * A specialized version of `_.filter` for arrays without support for callback\n * shorthands or `this` binding.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function arrayFilter(array, predicate) {\n var index = -1,\n length = array.length,\n resIndex = -1,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result[++resIndex] = value;\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.map` for arrays without support for callback\n * shorthands or `this` binding.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function arrayMap(array, iteratee) {\n var index = -1,\n length = array.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = iteratee(array[index], index, array);\n }\n return result;\n }\n\n /**\n * A specialized version of `_.max` for arrays without support for iteratees.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @returns {*} Returns the maximum value.\n */\n function arrayMax(array) {\n var index = -1,\n length = array.length,\n result = NEGATIVE_INFINITY;\n\n while (++index < length) {\n var value = array[index];\n if (value > result) {\n result = value;\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.min` for arrays without support for iteratees.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @returns {*} Returns the minimum value.\n */\n function arrayMin(array) {\n var index = -1,\n length = array.length,\n result = POSITIVE_INFINITY;\n\n while (++index < length) {\n var value = array[index];\n if (value < result) {\n result = value;\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.reduce` for arrays without support for callback\n * shorthands or `this` binding.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initFromArray] Specify using the first element of `array`\n * as the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduce(array, iteratee, accumulator, initFromArray) {\n var index = -1,\n length = array.length;\n\n if (initFromArray && length) {\n accumulator = array[++index];\n }\n while (++index < length) {\n accumulator = iteratee(accumulator, array[index], index, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.reduceRight` for arrays without support for\n * callback shorthands or `this` binding.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {boolean} [initFromArray] Specify using the last element of `array`\n * as the initial value.\n * @returns {*} Returns the accumulated value.\n */\n function arrayReduceRight(array, iteratee, accumulator, initFromArray) {\n var length = array.length;\n if (initFromArray && length) {\n accumulator = array[--length];\n }\n while (length--) {\n accumulator = iteratee(accumulator, array[length], length, array);\n }\n return accumulator;\n }\n\n /**\n * A specialized version of `_.some` for arrays without support for callback\n * shorthands or `this` binding.\n *\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function arraySome(array, predicate) {\n var index = -1,\n length = array.length;\n\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return true;\n }\n }\n return false;\n }\n\n /**\n * Used by `_.defaults` to customize its `_.assign` use.\n *\n * @private\n * @param {*} objectValue The destination object property value.\n * @param {*} sourceValue The source object property value.\n * @returns {*} Returns the value to assign to the destination object.\n */\n function assignDefaults(objectValue, sourceValue) {\n return typeof objectValue == 'undefined' ? sourceValue : objectValue;\n }\n\n /**\n * Used by `_.template` to customize its `_.assign` use.\n *\n * **Note:** This method is like `assignDefaults` except that it ignores\n * inherited property values when checking if a property is `undefined`.\n *\n * @private\n * @param {*} objectValue The destination object property value.\n * @param {*} sourceValue The source object property value.\n * @param {string} key The key associated with the object and source values.\n * @param {Object} object The destination object.\n * @returns {*} Returns the value to assign to the destination object.\n */\n function assignOwnDefaults(objectValue, sourceValue, key, object) {\n return (typeof objectValue == 'undefined' || !hasOwnProperty.call(object, key))\n ? sourceValue\n : objectValue;\n }\n\n /**\n * The base implementation of `_.assign` without support for argument juggling,\n * multiple sources, and `this` binding `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {Function} [customizer] The function to customize assigning values.\n * @returns {Object} Returns the destination object.\n */\n function baseAssign(object, source, customizer) {\n var props = keys(source);\n if (!customizer) {\n return baseCopy(source, object, props);\n }\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index],\n value = object[key],\n result = customizer(value, source[key], key, object, source);\n\n if ((result === result ? result !== value : value === value) ||\n (typeof value == 'undefined' && !(key in object))) {\n object[key] = result;\n }\n }\n return object;\n }\n\n /**\n * The base implementation of `_.at` without support for strings and individual\n * key arguments.\n *\n * @private\n * @param {Array|Object} collection The collection to iterate over.\n * @param {number[]|string[]} [props] The property names or indexes of elements to pick.\n * @returns {Array} Returns the new array of picked elements.\n */\n function baseAt(collection, props) {\n var index = -1,\n length = collection.length,\n isArr = isLength(length),\n propsLength = props.length,\n result = Array(propsLength);\n\n while (++index < propsLength) {\n var key = props[index];\n if (isArr) {\n key = parseFloat(key);\n result[index] = isIndex(key, length) ? collection[key] : undefined;\n } else {\n result[index] = collection[key];\n }\n }\n return result;\n }\n\n /**\n * Copies the properties of `source` to `object`.\n *\n * @private\n * @param {Object} source The object to copy properties from.\n * @param {Object} [object={}] The object to copy properties to.\n * @param {Array} props The property names to copy.\n * @returns {Object} Returns `object`.\n */\n function baseCopy(source, object, props) {\n if (!props) {\n props = object;\n object = {};\n }\n var index = -1,\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n object[key] = source[key];\n }\n return object;\n }\n\n /**\n * The base implementation of `_.bindAll` without support for individual\n * method name arguments.\n *\n * @private\n * @param {Object} object The object to bind and assign the bound methods to.\n * @param {string[]} methodNames The object method names to bind.\n * @returns {Object} Returns `object`.\n */\n function baseBindAll(object, methodNames) {\n var index = -1,\n length = methodNames.length;\n\n while (++index < length) {\n var key = methodNames[index];\n object[key] = createWrapper(object[key], BIND_FLAG, object);\n }\n return object;\n }\n\n /**\n * The base implementation of `_.callback` which supports specifying the\n * number of arguments to provide to `func`.\n *\n * @private\n * @param {*} [func=_.identity] The value to convert to a callback.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {number} [argCount] The number of arguments to provide to `func`.\n * @returns {Function} Returns the callback.\n */\n function baseCallback(func, thisArg, argCount) {\n var type = typeof func;\n if (type == 'function') {\n return (typeof thisArg != 'undefined' && isBindable(func))\n ? bindCallback(func, thisArg, argCount)\n : func;\n }\n if (func == null) {\n return identity;\n }\n if (type == 'object') {\n return baseMatches(func);\n }\n return typeof thisArg == 'undefined'\n ? baseProperty(func + '')\n : baseMatchesProperty(func + '', thisArg);\n }\n\n /**\n * The base implementation of `_.clone` without support for argument juggling\n * and `this` binding `customizer` functions.\n *\n * @private\n * @param {*} value The value to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @param {Function} [customizer] The function to customize cloning values.\n * @param {string} [key] The key of `value`.\n * @param {Object} [object] The object `value` belongs to.\n * @param {Array} [stackA=[]] Tracks traversed source objects.\n * @param {Array} [stackB=[]] Associates clones with source counterparts.\n * @returns {*} Returns the cloned value.\n */\n function baseClone(value, isDeep, customizer, key, object, stackA, stackB) {\n var result;\n if (customizer) {\n result = object ? customizer(value, key, object) : customizer(value);\n }\n if (typeof result != 'undefined') {\n return result;\n }\n if (!isObject(value)) {\n return value;\n }\n var isArr = isArray(value);\n if (isArr) {\n result = initCloneArray(value);\n if (!isDeep) {\n return arrayCopy(value, result);\n }\n } else {\n var tag = objToString.call(value),\n isFunc = tag == funcTag;\n\n if (tag == objectTag || tag == argsTag || (isFunc && !object)) {\n result = initCloneObject(isFunc ? {} : value);\n if (!isDeep) {\n return baseCopy(value, result, keys(value));\n }\n } else {\n return cloneableTags[tag]\n ? initCloneByTag(value, tag, isDeep)\n : (object ? value : {});\n }\n }\n // Check for circular references and return corresponding clone.\n stackA || (stackA = []);\n stackB || (stackB = []);\n\n var length = stackA.length;\n while (length--) {\n if (stackA[length] == value) {\n return stackB[length];\n }\n }\n // Add the source value to the stack of traversed objects and associate it with its clone.\n stackA.push(value);\n stackB.push(result);\n\n // Recursively populate clone (susceptible to call stack limits).\n (isArr ? arrayEach : baseForOwn)(value, function (subValue, key) {\n result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB);\n });\n return result;\n }\n\n /**\n * The base implementation of `_.create` without support for assigning\n * properties to the created object.\n *\n * @private\n * @param {Object} prototype The object to inherit from.\n * @returns {Object} Returns the new object.\n */\n var baseCreate = (function () {\n function Object() { }\n return function (prototype) {\n if (isObject(prototype)) {\n Object.prototype = prototype;\n var result = new Object;\n Object.prototype = null;\n }\n return result || context.Object();\n };\n }());\n\n /**\n * The base implementation of `_.delay` and `_.defer` which accepts an index\n * of where to slice the arguments to provide to `func`.\n *\n * @private\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {Object} args The `arguments` object to slice and provide to `func`.\n * @returns {number} Returns the timer id.\n */\n function baseDelay(func, wait, args, fromIndex) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return setTimeout(function () { func.apply(undefined, baseSlice(args, fromIndex)); }, wait);\n }\n\n /**\n * The base implementation of `_.difference` which accepts a single array\n * of values to exclude.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Array} values The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n */\n function baseDifference(array, values) {\n var length = array ? array.length : 0,\n result = [];\n\n if (!length) {\n return result;\n }\n var index = -1,\n indexOf = getIndexOf(),\n isCommon = indexOf == baseIndexOf,\n cache = (isCommon && values.length >= 200) ? createCache(values) : null,\n valuesLength = values.length;\n\n if (cache) {\n indexOf = cacheIndexOf;\n isCommon = false;\n values = cache;\n }\n outer:\n while (++index < length) {\n var value = array[index];\n\n if (isCommon && value === value) {\n var valuesIndex = valuesLength;\n while (valuesIndex--) {\n if (values[valuesIndex] === value) {\n continue outer;\n }\n }\n result.push(value);\n }\n else if (indexOf(values, value) < 0) {\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.forEach` without support for callback\n * shorthands and `this` binding.\n *\n * @private\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object|string} Returns `collection`.\n */\n function baseEach(collection, iteratee) {\n var length = collection ? collection.length : 0;\n if (!isLength(length)) {\n return baseForOwn(collection, iteratee);\n }\n var index = -1,\n iterable = toObject(collection);\n\n while (++index < length) {\n if (iteratee(iterable[index], index, iterable) === false) {\n break;\n }\n }\n return collection;\n }\n\n /**\n * The base implementation of `_.forEachRight` without support for callback\n * shorthands and `this` binding.\n *\n * @private\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array|Object|string} Returns `collection`.\n */\n function baseEachRight(collection, iteratee) {\n var length = collection ? collection.length : 0;\n if (!isLength(length)) {\n return baseForOwnRight(collection, iteratee);\n }\n var iterable = toObject(collection);\n while (length--) {\n if (iteratee(iterable[length], length, iterable) === false) {\n break;\n }\n }\n return collection;\n }\n\n /**\n * The base implementation of `_.every` without support for callback\n * shorthands or `this` binding.\n *\n * @private\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`\n */\n function baseEvery(collection, predicate) {\n var result = true;\n baseEach(collection, function (value, index, collection) {\n result = !!predicate(value, index, collection);\n return result;\n });\n return result;\n }\n\n /**\n * The base implementation of `_.fill` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n */\n function baseFill(array, value, start, end) {\n var length = array.length;\n\n start = start == null ? 0 : (+start || 0);\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = (typeof end == 'undefined' || end > length) ? length : (+end || 0);\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : end >>> 0;\n start >>>= 0;\n\n while (start < length) {\n array[start++] = value;\n }\n return array;\n }\n\n /**\n * The base implementation of `_.filter` without support for callback\n * shorthands or `this` binding.\n *\n * @private\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Array} Returns the new filtered array.\n */\n function baseFilter(collection, predicate) {\n var result = [];\n baseEach(collection, function (value, index, collection) {\n if (predicate(value, index, collection)) {\n result.push(value);\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.find`, `_.findLast`, `_.findKey`, and `_.findLastKey`,\n * without support for callback shorthands and `this` binding, which iterates\n * over `collection` using the provided `eachFunc`.\n *\n * @private\n * @param {Array|Object|string} collection The collection to search.\n * @param {Function} predicate The function invoked per iteration.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @param {boolean} [retKey] Specify returning the key of the found element\n * instead of the element itself.\n * @returns {*} Returns the found element or its key, else `undefined`.\n */\n function baseFind(collection, predicate, eachFunc, retKey) {\n var result;\n eachFunc(collection, function (value, key, collection) {\n if (predicate(value, key, collection)) {\n result = retKey ? key : value;\n return false;\n }\n });\n return result;\n }\n\n /**\n * The base implementation of `_.flatten` with added support for restricting\n * flattening and specifying the start index.\n *\n * @private\n * @param {Array} array The array to flatten.\n * @param {boolean} [isDeep] Specify a deep flatten.\n * @param {boolean} [isStrict] Restrict flattening to arrays and `arguments` objects.\n * @param {number} [fromIndex=0] The index to start from.\n * @returns {Array} Returns the new flattened array.\n */\n function baseFlatten(array, isDeep, isStrict, fromIndex) {\n var index = (fromIndex || 0) - 1,\n length = array.length,\n resIndex = -1,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n\n if (isObjectLike(value) && isLength(value.length) && (isArray(value) || isArguments(value))) {\n if (isDeep) {\n // Recursively flatten arrays (susceptible to call stack limits).\n value = baseFlatten(value, isDeep, isStrict);\n }\n var valIndex = -1,\n valLength = value.length;\n\n result.length += valLength;\n while (++valIndex < valLength) {\n result[++resIndex] = value[valIndex];\n }\n } else if (!isStrict) {\n result[++resIndex] = value;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `baseForIn` and `baseForOwn` which iterates\n * over `object` properties returned by `keysFunc` invoking `iteratee` for\n * each property. Iterator functions may exit iteration early by explicitly\n * returning `false`.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n function baseFor(object, iteratee, keysFunc) {\n var index = -1,\n iterable = toObject(object),\n props = keysFunc(object),\n length = props.length;\n\n while (++index < length) {\n var key = props[index];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n }\n\n /**\n * This function is like `baseFor` except that it iterates over properties\n * in the opposite order.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {Function} keysFunc The function to get the keys of `object`.\n * @returns {Object} Returns `object`.\n */\n function baseForRight(object, iteratee, keysFunc) {\n var iterable = toObject(object),\n props = keysFunc(object),\n length = props.length;\n\n while (length--) {\n var key = props[length];\n if (iteratee(iterable[key], key, iterable) === false) {\n break;\n }\n }\n return object;\n }\n\n /**\n * The base implementation of `_.forIn` without support for callback\n * shorthands and `this` binding.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForIn(object, iteratee) {\n return baseFor(object, iteratee, keysIn);\n }\n\n /**\n * The base implementation of `_.forOwn` without support for callback\n * shorthands and `this` binding.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwn(object, iteratee) {\n return baseFor(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.forOwnRight` without support for callback\n * shorthands and `this` binding.\n *\n * @private\n * @param {Object} object The object to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Object} Returns `object`.\n */\n function baseForOwnRight(object, iteratee) {\n return baseForRight(object, iteratee, keys);\n }\n\n /**\n * The base implementation of `_.functions` which creates an array of\n * `object` function property names filtered from those provided.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Array} props The property names to filter.\n * @returns {Array} Returns the new array of filtered property names.\n */\n function baseFunctions(object, props) {\n var index = -1,\n length = props.length,\n resIndex = -1,\n result = [];\n\n while (++index < length) {\n var key = props[index];\n if (isFunction(object[key])) {\n result[++resIndex] = key;\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.invoke` which requires additional arguments\n * to be provided as an array of arguments rather than individually.\n *\n * @private\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function|string} methodName The name of the method to invoke or\n * the function invoked per iteration.\n * @param {Array} [args] The arguments to invoke the method with.\n * @returns {Array} Returns the array of results.\n */\n function baseInvoke(collection, methodName, args) {\n var index = -1,\n isFunc = typeof methodName == 'function',\n length = collection ? collection.length : 0,\n result = isLength(length) ? Array(length) : [];\n\n baseEach(collection, function (value) {\n var func = isFunc ? methodName : (value != null && value[methodName]);\n result[++index] = func ? func.apply(value, args) : undefined;\n });\n return result;\n }\n\n /**\n * The base implementation of `_.isEqual` without support for `this` binding\n * `customizer` functions.\n *\n * @private\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {Function} [customizer] The function to customize comparing values.\n * @param {boolean} [isWhere] Specify performing partial comparisons.\n * @param {Array} [stackA] Tracks traversed `value` objects.\n * @param {Array} [stackB] Tracks traversed `other` objects.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n */\n function baseIsEqual(value, other, customizer, isWhere, stackA, stackB) {\n // Exit early for identical values.\n if (value === other) {\n // Treat `+0` vs. `-0` as not equal.\n return value !== 0 || (1 / value == 1 / other);\n }\n var valType = typeof value,\n othType = typeof other;\n\n // Exit early for unlike primitive values.\n if ((valType != 'function' && valType != 'object' && othType != 'function' && othType != 'object') ||\n value == null || other == null) {\n // Return `false` unless both values are `NaN`.\n return value !== value && other !== other;\n }\n return baseIsEqualDeep(value, other, baseIsEqual, customizer, isWhere, stackA, stackB);\n }\n\n /**\n * A specialized version of `baseIsEqual` for arrays and objects which performs\n * deep comparisons and tracks traversed objects enabling objects with circular\n * references to be compared.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Function} [customizer] The function to customize comparing objects.\n * @param {boolean} [isWhere] Specify performing partial comparisons.\n * @param {Array} [stackA=[]] Tracks traversed `value` objects.\n * @param {Array} [stackB=[]] Tracks traversed `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function baseIsEqualDeep(object, other, equalFunc, customizer, isWhere, stackA, stackB) {\n var objIsArr = isArray(object),\n othIsArr = isArray(other),\n objTag = arrayTag,\n othTag = arrayTag;\n\n if (!objIsArr) {\n objTag = objToString.call(object);\n if (objTag == argsTag) {\n objTag = objectTag;\n } else if (objTag != objectTag) {\n objIsArr = isTypedArray(object);\n }\n }\n if (!othIsArr) {\n othTag = objToString.call(other);\n if (othTag == argsTag) {\n othTag = objectTag;\n } else if (othTag != objectTag) {\n othIsArr = isTypedArray(other);\n }\n }\n var objIsObj = objTag == objectTag,\n othIsObj = othTag == objectTag,\n isSameTag = objTag == othTag;\n\n if (isSameTag && !(objIsArr || objIsObj)) {\n return equalByTag(object, other, objTag);\n }\n var valWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),\n othWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');\n\n if (valWrapped || othWrapped) {\n return equalFunc(valWrapped ? object.value() : object, othWrapped ? other.value() : other, customizer, isWhere, stackA, stackB);\n }\n if (!isSameTag) {\n return false;\n }\n // Assume cyclic values are equal.\n // For more information on detecting circular references see https://es5.github.io/#JO.\n stackA || (stackA = []);\n stackB || (stackB = []);\n\n var length = stackA.length;\n while (length--) {\n if (stackA[length] == object) {\n return stackB[length] == other;\n }\n }\n // Add `object` and `other` to the stack of traversed objects.\n stackA.push(object);\n stackB.push(other);\n\n var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isWhere, stackA, stackB);\n\n stackA.pop();\n stackB.pop();\n\n return result;\n }\n\n /**\n * The base implementation of `_.isMatch` without support for callback\n * shorthands or `this` binding.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @param {Array} props The source property names to match.\n * @param {Array} values The source values to match.\n * @param {Array} strictCompareFlags Strict comparison flags for source values.\n * @param {Function} [customizer] The function to customize comparing objects.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n */\n function baseIsMatch(object, props, values, strictCompareFlags, customizer) {\n var length = props.length;\n if (object == null) {\n return !length;\n }\n var index = -1,\n noCustomizer = !customizer;\n\n while (++index < length) {\n if ((noCustomizer && strictCompareFlags[index])\n ? values[index] !== object[props[index]]\n : !hasOwnProperty.call(object, props[index])\n ) {\n return false;\n }\n }\n index = -1;\n while (++index < length) {\n var key = props[index];\n if (noCustomizer && strictCompareFlags[index]) {\n var result = hasOwnProperty.call(object, key);\n } else {\n var objValue = object[key],\n srcValue = values[index];\n\n result = customizer ? customizer(objValue, srcValue, key) : undefined;\n if (typeof result == 'undefined') {\n result = baseIsEqual(srcValue, objValue, customizer, true);\n }\n }\n if (!result) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * The base implementation of `_.map` without support for callback shorthands\n * or `this` binding.\n *\n * @private\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @returns {Array} Returns the new mapped array.\n */\n function baseMap(collection, iteratee) {\n var result = [];\n baseEach(collection, function (value, key, collection) {\n result.push(iteratee(value, key, collection));\n });\n return result;\n }\n\n /**\n * The base implementation of `_.matches` which does not clone `source`.\n *\n * @private\n * @param {Object} source The object of property values to match.\n * @returns {Function} Returns the new function.\n */\n function baseMatches(source) {\n var props = keys(source),\n length = props.length;\n\n if (length == 1) {\n var key = props[0],\n value = source[key];\n\n if (isStrictComparable(value)) {\n return function (object) {\n return object != null && object[key] === value && hasOwnProperty.call(object, key);\n };\n }\n }\n var values = Array(length),\n strictCompareFlags = Array(length);\n\n while (length--) {\n value = source[props[length]];\n values[length] = value;\n strictCompareFlags[length] = isStrictComparable(value);\n }\n return function (object) {\n return baseIsMatch(object, props, values, strictCompareFlags);\n };\n }\n\n /**\n * The base implementation of `_.matchesProperty` which does not coerce `key`\n * to a string.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @param {*} value The value to compare.\n * @returns {Function} Returns the new function.\n */\n function baseMatchesProperty(key, value) {\n if (isStrictComparable(value)) {\n return function (object) {\n return object != null && object[key] === value;\n };\n }\n return function (object) {\n return object != null && baseIsEqual(value, object[key], null, true);\n };\n }\n\n /**\n * The base implementation of `_.merge` without support for argument juggling,\n * multiple sources, and `this` binding `customizer` functions.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {Function} [customizer] The function to customize merging properties.\n * @param {Array} [stackA=[]] Tracks traversed source objects.\n * @param {Array} [stackB=[]] Associates values with source counterparts.\n * @returns {Object} Returns the destination object.\n */\n function baseMerge(object, source, customizer, stackA, stackB) {\n if (!isObject(object)) {\n return object;\n }\n var isSrcArr = isLength(source.length) && (isArray(source) || isTypedArray(source));\n (isSrcArr ? arrayEach : baseForOwn)(source, function (srcValue, key, source) {\n if (isObjectLike(srcValue)) {\n stackA || (stackA = []);\n stackB || (stackB = []);\n return baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB);\n }\n var value = object[key],\n result = customizer ? customizer(value, srcValue, key, object, source) : undefined,\n isCommon = typeof result == 'undefined';\n\n if (isCommon) {\n result = srcValue;\n }\n if ((isSrcArr || typeof result != 'undefined') &&\n (isCommon || (result === result ? result !== value : value === value))) {\n object[key] = result;\n }\n });\n return object;\n }\n\n /**\n * A specialized version of `baseMerge` for arrays and objects which performs\n * deep merges and tracks traversed objects enabling objects with circular\n * references to be merged.\n *\n * @private\n * @param {Object} object The destination object.\n * @param {Object} source The source object.\n * @param {string} key The key of the value to merge.\n * @param {Function} mergeFunc The function to merge values.\n * @param {Function} [customizer] The function to customize merging properties.\n * @param {Array} [stackA=[]] Tracks traversed source objects.\n * @param {Array} [stackB=[]] Associates values with source counterparts.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) {\n var length = stackA.length,\n srcValue = source[key];\n\n while (length--) {\n if (stackA[length] == srcValue) {\n object[key] = stackB[length];\n return;\n }\n }\n var value = object[key],\n result = customizer ? customizer(value, srcValue, key, object, source) : undefined,\n isCommon = typeof result == 'undefined';\n\n if (isCommon) {\n result = srcValue;\n if (isLength(srcValue.length) && (isArray(srcValue) || isTypedArray(srcValue))) {\n result = isArray(value)\n ? value\n : (value ? arrayCopy(value) : []);\n }\n else if (isPlainObject(srcValue) || isArguments(srcValue)) {\n result = isArguments(value)\n ? toPlainObject(value)\n : (isPlainObject(value) ? value : {});\n }\n else {\n isCommon = false;\n }\n }\n // Add the source value to the stack of traversed objects and associate\n // it with its merged value.\n stackA.push(srcValue);\n stackB.push(result);\n\n if (isCommon) {\n // Recursively merge objects and arrays (susceptible to call stack limits).\n object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB);\n } else if (result === result ? result !== value : value === value) {\n object[key] = result;\n }\n }\n\n /**\n * The base implementation of `_.property` which does not coerce `key` to a string.\n *\n * @private\n * @param {string} key The key of the property to get.\n * @returns {Function} Returns the new function.\n */\n function baseProperty(key) {\n return function (object) {\n return object == null ? undefined : object[key];\n };\n }\n\n /**\n * The base implementation of `_.pullAt` without support for individual\n * index arguments.\n *\n * @private\n * @param {Array} array The array to modify.\n * @param {number[]} indexes The indexes of elements to remove.\n * @returns {Array} Returns the new array of removed elements.\n */\n function basePullAt(array, indexes) {\n var length = indexes.length,\n result = baseAt(array, indexes);\n\n indexes.sort(baseCompareAscending);\n while (length--) {\n var index = parseFloat(indexes[length]);\n if (index != previous && isIndex(index)) {\n var previous = index;\n splice.call(array, index, 1);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.random` without support for argument juggling\n * and returning floating-point numbers.\n *\n * @private\n * @param {number} min The minimum possible value.\n * @param {number} max The maximum possible value.\n * @returns {number} Returns the random number.\n */\n function baseRandom(min, max) {\n return min + floor(nativeRandom() * (max - min + 1));\n }\n\n /**\n * The base implementation of `_.reduce` and `_.reduceRight` without support\n * for callback shorthands or `this` binding, which iterates over `collection`\n * using the provided `eachFunc`.\n *\n * @private\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {*} accumulator The initial value.\n * @param {boolean} initFromCollection Specify using the first or last element\n * of `collection` as the initial value.\n * @param {Function} eachFunc The function to iterate over `collection`.\n * @returns {*} Returns the accumulated value.\n */\n function baseReduce(collection, iteratee, accumulator, initFromCollection, eachFunc) {\n eachFunc(collection, function (value, index, collection) {\n accumulator = initFromCollection\n ? (initFromCollection = false, value)\n : iteratee(accumulator, value, index, collection);\n });\n return accumulator;\n }\n\n /**\n * The base implementation of `setData` without support for hot loop detection.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var baseSetData = !metaMap ? identity : function (func, data) {\n metaMap.set(func, data);\n return func;\n };\n\n /**\n * The base implementation of `_.slice` without an iteratee call guard.\n *\n * @private\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function baseSlice(array, start, end) {\n var index = -1,\n length = array.length;\n\n start = start == null ? 0 : (+start || 0);\n if (start < 0) {\n start = -start > length ? 0 : (length + start);\n }\n end = (typeof end == 'undefined' || end > length) ? length : (+end || 0);\n if (end < 0) {\n end += length;\n }\n length = start > end ? 0 : (end - start) >>> 0;\n start >>>= 0;\n\n var result = Array(length);\n while (++index < length) {\n result[index] = array[index + start];\n }\n return result;\n }\n\n /**\n * The base implementation of `_.some` without support for callback shorthands\n * or `this` binding.\n *\n * @private\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n */\n function baseSome(collection, predicate) {\n var result;\n\n baseEach(collection, function (value, index, collection) {\n result = predicate(value, index, collection);\n return !result;\n });\n return !!result;\n }\n\n /**\n * The base implementation of `_.uniq` without support for callback shorthands\n * and `this` binding.\n *\n * @private\n * @param {Array} array The array to inspect.\n * @param {Function} [iteratee] The function invoked per iteration.\n * @returns {Array} Returns the new duplicate-value-free array.\n */\n function baseUniq(array, iteratee) {\n var index = -1,\n indexOf = getIndexOf(),\n length = array.length,\n isCommon = indexOf == baseIndexOf,\n isLarge = isCommon && length >= 200,\n seen = isLarge ? createCache() : null,\n result = [];\n\n if (seen) {\n indexOf = cacheIndexOf;\n isCommon = false;\n } else {\n isLarge = false;\n seen = iteratee ? [] : result;\n }\n outer:\n while (++index < length) {\n var value = array[index],\n computed = iteratee ? iteratee(value, index, array) : value;\n\n if (isCommon && value === value) {\n var seenIndex = seen.length;\n while (seenIndex--) {\n if (seen[seenIndex] === computed) {\n continue outer;\n }\n }\n if (iteratee) {\n seen.push(computed);\n }\n result.push(value);\n }\n else if (indexOf(seen, computed) < 0) {\n if (iteratee || isLarge) {\n seen.push(computed);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * The base implementation of `_.values` and `_.valuesIn` which creates an\n * array of `object` property values corresponding to the property names\n * returned by `keysFunc`.\n *\n * @private\n * @param {Object} object The object to query.\n * @param {Array} props The property names to get values for.\n * @returns {Object} Returns the array of property values.\n */\n function baseValues(object, props) {\n var index = -1,\n length = props.length,\n result = Array(length);\n\n while (++index < length) {\n result[index] = object[props[index]];\n }\n return result;\n }\n\n /**\n * The base implementation of `wrapperValue` which returns the result of\n * performing a sequence of actions on the unwrapped `value`, where each\n * successive action is supplied the return value of the previous.\n *\n * @private\n * @param {*} value The unwrapped value.\n * @param {Array} actions Actions to peform to resolve the unwrapped value.\n * @returns {*} Returns the resolved unwrapped value.\n */\n function baseWrapperValue(value, actions) {\n var result = value;\n if (result instanceof LazyWrapper) {\n result = result.value();\n }\n var index = -1,\n length = actions.length;\n\n while (++index < length) {\n var args = [result],\n action = actions[index];\n\n push.apply(args, action.args);\n result = action.func.apply(action.thisArg, args);\n }\n return result;\n }\n\n /**\n * Performs a binary search of `array` to determine the index at which `value`\n * should be inserted into `array` in order to maintain its sort order.\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {boolean} [retHighest] Specify returning the highest, instead\n * of the lowest, index at which a value should be inserted into `array`.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function binaryIndex(array, value, retHighest) {\n var low = 0,\n high = array ? array.length : low;\n\n if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {\n while (low < high) {\n var mid = (low + high) >>> 1,\n computed = array[mid];\n\n if (retHighest ? (computed <= value) : (computed < value)) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return high;\n }\n return binaryIndexBy(array, value, identity, retHighest);\n }\n\n /**\n * This function is like `binaryIndex` except that it invokes `iteratee` for\n * `value` and each element of `array` to compute their sort ranking. The\n * iteratee is invoked with one argument; (value).\n *\n * @private\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {boolean} [retHighest] Specify returning the highest, instead\n * of the lowest, index at which a value should be inserted into `array`.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n */\n function binaryIndexBy(array, value, iteratee, retHighest) {\n value = iteratee(value);\n\n var low = 0,\n high = array ? array.length : 0,\n valIsNaN = value !== value,\n valIsUndef = typeof value == 'undefined';\n\n while (low < high) {\n var mid = floor((low + high) / 2),\n computed = iteratee(array[mid]),\n isReflexive = computed === computed;\n\n if (valIsNaN) {\n var setLow = isReflexive || retHighest;\n } else if (valIsUndef) {\n setLow = isReflexive && (retHighest || typeof computed != 'undefined');\n } else {\n setLow = retHighest ? (computed <= value) : (computed < value);\n }\n if (setLow) {\n low = mid + 1;\n } else {\n high = mid;\n }\n }\n return nativeMin(high, MAX_ARRAY_INDEX);\n }\n\n /**\n * A specialized version of `baseCallback` which only supports `this` binding\n * and specifying the number of arguments to provide to `func`.\n *\n * @private\n * @param {Function} func The function to bind.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {number} [argCount] The number of arguments to provide to `func`.\n * @returns {Function} Returns the callback.\n */\n function bindCallback(func, thisArg, argCount) {\n if (typeof func != 'function') {\n return identity;\n }\n if (typeof thisArg == 'undefined') {\n return func;\n }\n switch (argCount) {\n case 1: return function (value) {\n return func.call(thisArg, value);\n };\n case 3: return function (value, index, collection) {\n return func.call(thisArg, value, index, collection);\n };\n case 4: return function (accumulator, value, index, collection) {\n return func.call(thisArg, accumulator, value, index, collection);\n };\n case 5: return function (value, other, key, object, source) {\n return func.call(thisArg, value, other, key, object, source);\n };\n }\n return function () {\n return func.apply(thisArg, arguments);\n };\n }\n\n /**\n * Creates a clone of the given array buffer.\n *\n * @private\n * @param {ArrayBuffer} buffer The array buffer to clone.\n * @returns {ArrayBuffer} Returns the cloned array buffer.\n */\n function bufferClone(buffer) {\n return bufferSlice.call(buffer, 0);\n }\n if (!bufferSlice) {\n // PhantomJS has `ArrayBuffer` and `Uint8Array` but not `Float64Array`.\n bufferClone = !(ArrayBuffer && Uint8Array) ? constant(null) : function (buffer) {\n var byteLength = buffer.byteLength,\n floatLength = Float64Array ? floor(byteLength / FLOAT64_BYTES_PER_ELEMENT) : 0,\n offset = floatLength * FLOAT64_BYTES_PER_ELEMENT,\n result = new ArrayBuffer(byteLength);\n\n if (floatLength) {\n var view = new Float64Array(result, 0, floatLength);\n view.set(new Float64Array(buffer, 0, floatLength));\n }\n if (byteLength != offset) {\n view = new Uint8Array(result, offset);\n view.set(new Uint8Array(buffer, offset));\n }\n return result;\n };\n }\n\n /**\n * Creates an array that is the composition of partially applied arguments,\n * placeholders, and provided arguments into a single array of arguments.\n *\n * @private\n * @param {Array|Object} args The provided arguments.\n * @param {Array} partials The arguments to prepend to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgs(args, partials, holders) {\n var holdersLength = holders.length,\n argsIndex = -1,\n argsLength = nativeMax(args.length - holdersLength, 0),\n leftIndex = -1,\n leftLength = partials.length,\n result = Array(argsLength + leftLength);\n\n while (++leftIndex < leftLength) {\n result[leftIndex] = partials[leftIndex];\n }\n while (++argsIndex < holdersLength) {\n result[holders[argsIndex]] = args[argsIndex];\n }\n while (argsLength--) {\n result[leftIndex++] = args[argsIndex++];\n }\n return result;\n }\n\n /**\n * This function is like `composeArgs` except that the arguments composition\n * is tailored for `_.partialRight`.\n *\n * @private\n * @param {Array|Object} args The provided arguments.\n * @param {Array} partials The arguments to append to those provided.\n * @param {Array} holders The `partials` placeholder indexes.\n * @returns {Array} Returns the new array of composed arguments.\n */\n function composeArgsRight(args, partials, holders) {\n var holdersIndex = -1,\n holdersLength = holders.length,\n argsIndex = -1,\n argsLength = nativeMax(args.length - holdersLength, 0),\n rightIndex = -1,\n rightLength = partials.length,\n result = Array(argsLength + rightLength);\n\n while (++argsIndex < argsLength) {\n result[argsIndex] = args[argsIndex];\n }\n var pad = argsIndex;\n while (++rightIndex < rightLength) {\n result[pad + rightIndex] = partials[rightIndex];\n }\n while (++holdersIndex < holdersLength) {\n result[pad + holders[holdersIndex]] = args[argsIndex++];\n }\n return result;\n }\n\n /**\n * Creates a function that aggregates a collection, creating an accumulator\n * object composed from the results of running each element in the collection\n * through an iteratee.\n *\n * @private\n * @param {Function} setter The function to set keys and values of the accumulator object.\n * @param {Function} [initializer] The function to initialize the accumulator object.\n * @returns {Function} Returns the new aggregator function.\n */\n function createAggregator(setter, initializer) {\n return function (collection, iteratee, thisArg) {\n var result = initializer ? initializer() : {};\n iteratee = getCallback(iteratee, thisArg, 3);\n\n if (isArray(collection)) {\n var index = -1,\n length = collection.length;\n\n while (++index < length) {\n var value = collection[index];\n setter(result, value, iteratee(value, index, collection), collection);\n }\n } else {\n baseEach(collection, function (value, key, collection) {\n setter(result, value, iteratee(value, key, collection), collection);\n });\n }\n return result;\n };\n }\n\n /**\n * Creates a function that assigns properties of source object(s) to a given\n * destination object.\n *\n * @private\n * @param {Function} assigner The function to assign values.\n * @returns {Function} Returns the new assigner function.\n */\n function createAssigner(assigner) {\n return function () {\n var length = arguments.length,\n object = arguments[0];\n\n if (length < 2 || object == null) {\n return object;\n }\n if (length > 3 && isIterateeCall(arguments[1], arguments[2], arguments[3])) {\n length = 2;\n }\n // Juggle arguments.\n if (length > 3 && typeof arguments[length - 2] == 'function') {\n var customizer = bindCallback(arguments[--length - 1], arguments[length--], 5);\n } else if (length > 2 && typeof arguments[length - 1] == 'function') {\n customizer = arguments[--length];\n }\n var index = 0;\n while (++index < length) {\n var source = arguments[index];\n if (source) {\n assigner(object, source, customizer);\n }\n }\n return object;\n };\n }\n\n /**\n * Creates a function that wraps `func` and invokes it with the `this`\n * binding of `thisArg`.\n *\n * @private\n * @param {Function} func The function to bind.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @returns {Function} Returns the new bound function.\n */\n function createBindWrapper(func, thisArg) {\n var Ctor = createCtorWrapper(func);\n\n function wrapper() {\n return (this instanceof wrapper ? Ctor : func).apply(thisArg, arguments);\n }\n return wrapper;\n }\n\n /**\n * Creates a `Set` cache object to optimize linear searches of large arrays.\n *\n * @private\n * @param {Array} [values] The values to cache.\n * @returns {null|Object} Returns the new cache object if `Set` is supported, else `null`.\n */\n var createCache = !(nativeCreate && Set) ? constant(null) : function (values) {\n return new SetCache(values);\n };\n\n /**\n * Creates a function that produces compound words out of the words in a\n * given string.\n *\n * @private\n * @param {Function} callback The function to combine each word.\n * @returns {Function} Returns the new compounder function.\n */\n function createCompounder(callback) {\n return function (string) {\n var index = -1,\n array = words(deburr(string)),\n length = array.length,\n result = '';\n\n while (++index < length) {\n result = callback(result, array[index], index);\n }\n return result;\n };\n }\n\n /**\n * Creates a function that produces an instance of `Ctor` regardless of\n * whether it was invoked as part of a `new` expression or by `call` or `apply`.\n *\n * @private\n * @param {Function} Ctor The constructor to wrap.\n * @returns {Function} Returns the new wrapped function.\n */\n function createCtorWrapper(Ctor) {\n return function () {\n var thisBinding = baseCreate(Ctor.prototype),\n result = Ctor.apply(thisBinding, arguments);\n\n // Mimic the constructor's `return` behavior.\n // See https://es5.github.io/#x13.2.2 for more details.\n return isObject(result) ? result : thisBinding;\n };\n }\n\n /**\n * Creates a function that gets the extremum value of a collection.\n *\n * @private\n * @param {Function} arrayFunc The function to get the extremum value from an array.\n * @param {boolean} [isMin] Specify returning the minimum, instead of the maximum,\n * extremum value.\n * @returns {Function} Returns the new extremum function.\n */\n function createExtremum(arrayFunc, isMin) {\n return function (collection, iteratee, thisArg) {\n if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {\n iteratee = null;\n }\n var func = getCallback(),\n noIteratee = iteratee == null;\n\n if (!(func === baseCallback && noIteratee)) {\n noIteratee = false;\n iteratee = func(iteratee, thisArg, 3);\n }\n if (noIteratee) {\n var isArr = isArray(collection);\n if (!isArr && isString(collection)) {\n iteratee = charAtCallback;\n } else {\n return arrayFunc(isArr ? collection : toIterable(collection));\n }\n }\n return extremumBy(collection, iteratee, isMin);\n };\n }\n\n /**\n * Creates a function that wraps `func` and invokes it with optional `this`\n * binding of, partial application, and currying.\n *\n * @private\n * @param {Function|string} func The function or method name to reference.\n * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to prepend to those provided to the new function.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [partialsRight] The arguments to append to those provided to the new function.\n * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createHybridWrapper(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {\n var isAry = bitmask & ARY_FLAG,\n isBind = bitmask & BIND_FLAG,\n isBindKey = bitmask & BIND_KEY_FLAG,\n isCurry = bitmask & CURRY_FLAG,\n isCurryBound = bitmask & CURRY_BOUND_FLAG,\n isCurryRight = bitmask & CURRY_RIGHT_FLAG;\n\n var Ctor = !isBindKey && createCtorWrapper(func),\n key = func;\n\n function wrapper() {\n // Avoid `arguments` object use disqualifying optimizations by\n // converting it to an array before providing it to other functions.\n var length = arguments.length,\n index = length,\n args = Array(length);\n\n while (index--) {\n args[index] = arguments[index];\n }\n if (partials) {\n args = composeArgs(args, partials, holders);\n }\n if (partialsRight) {\n args = composeArgsRight(args, partialsRight, holdersRight);\n }\n if (isCurry || isCurryRight) {\n var placeholder = wrapper.placeholder,\n argsHolders = replaceHolders(args, placeholder);\n\n length -= argsHolders.length;\n if (length < arity) {\n var newArgPos = argPos ? arrayCopy(argPos) : null,\n newArity = nativeMax(arity - length, 0),\n newsHolders = isCurry ? argsHolders : null,\n newHoldersRight = isCurry ? null : argsHolders,\n newPartials = isCurry ? args : null,\n newPartialsRight = isCurry ? null : args;\n\n bitmask |= (isCurry ? PARTIAL_FLAG : PARTIAL_RIGHT_FLAG);\n bitmask &= ~(isCurry ? PARTIAL_RIGHT_FLAG : PARTIAL_FLAG);\n\n if (!isCurryBound) {\n bitmask &= ~(BIND_FLAG | BIND_KEY_FLAG);\n }\n var result = createHybridWrapper(func, bitmask, thisArg, newPartials, newsHolders, newPartialsRight, newHoldersRight, newArgPos, ary, newArity);\n result.placeholder = placeholder;\n return result;\n }\n }\n var thisBinding = isBind ? thisArg : this;\n if (isBindKey) {\n func = thisBinding[key];\n }\n if (argPos) {\n args = reorder(args, argPos);\n }\n if (isAry && ary < args.length) {\n args.length = ary;\n }\n return (this instanceof wrapper ? (Ctor || createCtorWrapper(func)) : func).apply(thisBinding, args);\n }\n return wrapper;\n }\n\n /**\n * Creates the pad required for `string` based on the given padding length.\n * The `chars` string may be truncated if the number of padding characters\n * exceeds the padding length.\n *\n * @private\n * @param {string} string The string to create padding for.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the pad for `string`.\n */\n function createPad(string, length, chars) {\n var strLength = string.length;\n length = +length;\n\n if (strLength >= length || !nativeIsFinite(length)) {\n return '';\n }\n var padLength = length - strLength;\n chars = chars == null ? ' ' : (chars + '');\n return repeat(chars, ceil(padLength / chars.length)).slice(0, padLength);\n }\n\n /**\n * Creates a function that wraps `func` and invokes it with the optional `this`\n * binding of `thisArg` and the `partials` prepended to those provided to\n * the wrapper.\n *\n * @private\n * @param {Function} func The function to partially apply arguments to.\n * @param {number} bitmask The bitmask of flags. See `createWrapper` for more details.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {Array} partials The arguments to prepend to those provided to the new function.\n * @returns {Function} Returns the new bound function.\n */\n function createPartialWrapper(func, bitmask, thisArg, partials) {\n var isBind = bitmask & BIND_FLAG,\n Ctor = createCtorWrapper(func);\n\n function wrapper() {\n // Avoid `arguments` object use disqualifying optimizations by\n // converting it to an array before providing it `func`.\n var argsIndex = -1,\n argsLength = arguments.length,\n leftIndex = -1,\n leftLength = partials.length,\n args = Array(argsLength + leftLength);\n\n while (++leftIndex < leftLength) {\n args[leftIndex] = partials[leftIndex];\n }\n while (argsLength--) {\n args[leftIndex++] = arguments[++argsIndex];\n }\n return (this instanceof wrapper ? Ctor : func).apply(isBind ? thisArg : this, args);\n }\n return wrapper;\n }\n\n /**\n * Creates a function that either curries or invokes `func` with optional\n * `this` binding and partially applied arguments.\n *\n * @private\n * @param {Function|string} func The function or method name to reference.\n * @param {number} bitmask The bitmask of flags.\n * The bitmask may be composed of the following flags:\n * 1 - `_.bind`\n * 2 - `_.bindKey`\n * 4 - `_.curry` or `_.curryRight` of a bound function\n * 8 - `_.curry`\n * 16 - `_.curryRight`\n * 32 - `_.partial`\n * 64 - `_.partialRight`\n * 128 - `_.rearg`\n * 256 - `_.ary`\n * @param {*} [thisArg] The `this` binding of `func`.\n * @param {Array} [partials] The arguments to be partially applied.\n * @param {Array} [holders] The `partials` placeholder indexes.\n * @param {Array} [argPos] The argument positions of the new function.\n * @param {number} [ary] The arity cap of `func`.\n * @param {number} [arity] The arity of `func`.\n * @returns {Function} Returns the new wrapped function.\n */\n function createWrapper(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {\n var isBindKey = bitmask & BIND_KEY_FLAG;\n if (!isBindKey && typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var length = partials ? partials.length : 0;\n if (!length) {\n bitmask &= ~(PARTIAL_FLAG | PARTIAL_RIGHT_FLAG);\n partials = holders = null;\n }\n length -= (holders ? holders.length : 0);\n if (bitmask & PARTIAL_RIGHT_FLAG) {\n var partialsRight = partials,\n holdersRight = holders;\n\n partials = holders = null;\n }\n var data = !isBindKey && getData(func),\n newData = [func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity];\n\n if (data && data !== true) {\n mergeData(newData, data);\n bitmask = newData[1];\n arity = newData[9];\n }\n newData[9] = arity == null\n ? (isBindKey ? 0 : func.length)\n : (nativeMax(arity - length, 0) || 0);\n\n if (bitmask == BIND_FLAG) {\n var result = createBindWrapper(newData[0], newData[2]);\n } else if ((bitmask == PARTIAL_FLAG || bitmask == (BIND_FLAG | PARTIAL_FLAG)) && !newData[4].length) {\n result = createPartialWrapper.apply(undefined, newData);\n } else {\n result = createHybridWrapper.apply(undefined, newData);\n }\n var setter = data ? baseSetData : setData;\n return setter(result, newData);\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for arrays with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Array} array The array to compare.\n * @param {Array} other The other array to compare.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Function} [customizer] The function to customize comparing arrays.\n * @param {boolean} [isWhere] Specify performing partial comparisons.\n * @param {Array} [stackA] Tracks traversed `value` objects.\n * @param {Array} [stackB] Tracks traversed `other` objects.\n * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.\n */\n function equalArrays(array, other, equalFunc, customizer, isWhere, stackA, stackB) {\n var index = -1,\n arrLength = array.length,\n othLength = other.length,\n result = true;\n\n if (arrLength != othLength && !(isWhere && othLength > arrLength)) {\n return false;\n }\n // Deep compare the contents, ignoring non-numeric properties.\n while (result && ++index < arrLength) {\n var arrValue = array[index],\n othValue = other[index];\n\n result = undefined;\n if (customizer) {\n result = isWhere\n ? customizer(othValue, arrValue, index)\n : customizer(arrValue, othValue, index);\n }\n if (typeof result == 'undefined') {\n // Recursively compare arrays (susceptible to call stack limits).\n if (isWhere) {\n var othIndex = othLength;\n while (othIndex--) {\n othValue = other[othIndex];\n result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isWhere, stackA, stackB);\n if (result) {\n break;\n }\n }\n } else {\n result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isWhere, stackA, stackB);\n }\n }\n }\n return !!result;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for comparing objects of\n * the same `toStringTag`.\n *\n * **Note:** This function only supports comparing values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n * @private\n * @param {Object} value The object to compare.\n * @param {Object} other The other object to compare.\n * @param {string} tag The `toStringTag` of the objects to compare.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalByTag(object, other, tag) {\n switch (tag) {\n case boolTag:\n case dateTag:\n // Coerce dates and booleans to numbers, dates to milliseconds and booleans\n // to `1` or `0` treating invalid dates coerced to `NaN` as not equal.\n return +object == +other;\n\n case errorTag:\n return object.name == other.name && object.message == other.message;\n\n case numberTag:\n // Treat `NaN` vs. `NaN` as equal.\n return (object != +object)\n ? other != +other\n // But, treat `-0` vs. `+0` as not equal.\n : (object == 0 ? ((1 / object) == (1 / other)) : object == +other);\n\n case regexpTag:\n case stringTag:\n // Coerce regexes to strings and treat strings primitives and string\n // objects as equal. See https://es5.github.io/#x15.10.6.4 for more details.\n return object == (other + '');\n }\n return false;\n }\n\n /**\n * A specialized version of `baseIsEqualDeep` for objects with support for\n * partial deep comparisons.\n *\n * @private\n * @param {Object} object The object to compare.\n * @param {Object} other The other object to compare.\n * @param {Function} equalFunc The function to determine equivalents of values.\n * @param {Function} [customizer] The function to customize comparing values.\n * @param {boolean} [isWhere] Specify performing partial comparisons.\n * @param {Array} [stackA] Tracks traversed `value` objects.\n * @param {Array} [stackB] Tracks traversed `other` objects.\n * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.\n */\n function equalObjects(object, other, equalFunc, customizer, isWhere, stackA, stackB) {\n var objProps = keys(object),\n objLength = objProps.length,\n othProps = keys(other),\n othLength = othProps.length;\n\n if (objLength != othLength && !isWhere) {\n return false;\n }\n var hasCtor,\n index = -1;\n\n while (++index < objLength) {\n var key = objProps[index],\n result = hasOwnProperty.call(other, key);\n\n if (result) {\n var objValue = object[key],\n othValue = other[key];\n\n result = undefined;\n if (customizer) {\n result = isWhere\n ? customizer(othValue, objValue, key)\n : customizer(objValue, othValue, key);\n }\n if (typeof result == 'undefined') {\n // Recursively compare objects (susceptible to call stack limits).\n result = (objValue && objValue === othValue) || equalFunc(objValue, othValue, customizer, isWhere, stackA, stackB);\n }\n }\n if (!result) {\n return false;\n }\n hasCtor || (hasCtor = key == 'constructor');\n }\n if (!hasCtor) {\n var objCtor = object.constructor,\n othCtor = other.constructor;\n\n // Non `Object` object instances with different constructors are not equal.\n if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) &&\n !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) {\n return false;\n }\n }\n return true;\n }\n\n /**\n * Gets the extremum value of `collection` invoking `iteratee` for each value\n * in `collection` to generate the criterion by which the value is ranked.\n * The `iteratee` is invoked with three arguments; (value, index, collection).\n *\n * @private\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function} iteratee The function invoked per iteration.\n * @param {boolean} [isMin] Specify returning the minimum, instead of the\n * maximum, extremum value.\n * @returns {*} Returns the extremum value.\n */\n function extremumBy(collection, iteratee, isMin) {\n var exValue = isMin ? POSITIVE_INFINITY : NEGATIVE_INFINITY,\n computed = exValue,\n result = computed;\n\n baseEach(collection, function (value, index, collection) {\n var current = iteratee(value, index, collection);\n if ((isMin ? current < computed : current > computed) || (current === exValue && current === result)) {\n computed = current;\n result = value;\n }\n });\n return result;\n }\n\n /**\n * Gets the appropriate \"callback\" function. If the `_.callback` method is\n * customized this function returns the custom method, otherwise it returns\n * the `baseCallback` function. If arguments are provided the chosen function\n * is invoked with them and its result is returned.\n *\n * @private\n * @returns {Function} Returns the chosen function or its result.\n */\n function getCallback(func, thisArg, argCount) {\n var result = lodash.callback || callback;\n result = result === callback ? baseCallback : result;\n return argCount ? result(func, thisArg, argCount) : result;\n }\n\n /**\n * Gets metadata for `func`.\n *\n * @private\n * @param {Function} func The function to query.\n * @returns {*} Returns the metadata for `func`.\n */\n var getData = !metaMap ? noop : function (func) {\n return metaMap.get(func);\n };\n\n /**\n * Gets the appropriate \"indexOf\" function. If the `_.indexOf` method is\n * customized this function returns the custom method, otherwise it returns\n * the `baseIndexOf` function. If arguments are provided the chosen function\n * is invoked with them and its result is returned.\n *\n * @private\n * @returns {Function|number} Returns the chosen function or its result.\n */\n function getIndexOf(collection, target, fromIndex) {\n var result = lodash.indexOf || indexOf;\n result = result === indexOf ? baseIndexOf : result;\n return collection ? result(collection, target, fromIndex) : result;\n }\n\n /**\n * Gets the view, applying any `transforms` to the `start` and `end` positions.\n *\n * @private\n * @param {number} start The start of the view.\n * @param {number} end The end of the view.\n * @param {Array} [transforms] The transformations to apply to the view.\n * @returns {Object} Returns an object containing the `start` and `end`\n * positions of the view.\n */\n function getView(start, end, transforms) {\n var index = -1,\n length = transforms ? transforms.length : 0;\n\n while (++index < length) {\n var data = transforms[index],\n size = data.size;\n\n switch (data.type) {\n case 'drop': start += size; break;\n case 'dropRight': end -= size; break;\n case 'take': end = nativeMin(end, start + size); break;\n case 'takeRight': start = nativeMax(start, end - size); break;\n }\n }\n return { 'start': start, 'end': end };\n }\n\n /**\n * Initializes an array clone.\n *\n * @private\n * @param {Array} array The array to clone.\n * @returns {Array} Returns the initialized clone.\n */\n function initCloneArray(array) {\n var length = array.length,\n result = new array.constructor(length);\n\n // Add array properties assigned by `RegExp#exec`.\n if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {\n result.index = array.index;\n result.input = array.input;\n }\n return result;\n }\n\n /**\n * Initializes an object clone.\n *\n * @private\n * @param {Object} object The object to clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneObject(object) {\n var Ctor = object.constructor;\n if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) {\n Ctor = Object;\n }\n return new Ctor;\n }\n\n /**\n * Initializes an object clone based on its `toStringTag`.\n *\n * **Note:** This function only supports cloning values with tags of\n * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.\n *\n *\n * @private\n * @param {Object} object The object to clone.\n * @param {string} tag The `toStringTag` of the object to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @returns {Object} Returns the initialized clone.\n */\n function initCloneByTag(object, tag, isDeep) {\n var Ctor = object.constructor;\n switch (tag) {\n case arrayBufferTag:\n return bufferClone(object);\n\n case boolTag:\n case dateTag:\n return new Ctor(+object);\n\n case float32Tag: case float64Tag:\n case int8Tag: case int16Tag: case int32Tag:\n case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:\n var buffer = object.buffer;\n return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length);\n\n case numberTag:\n case stringTag:\n return new Ctor(object);\n\n case regexpTag:\n var result = new Ctor(object.source, reFlags.exec(object));\n result.lastIndex = object.lastIndex;\n }\n return result;\n }\n\n /**\n * Checks if `func` is eligible for `this` binding.\n *\n * @private\n * @param {Function} func The function to check.\n * @returns {boolean} Returns `true` if `func` is eligible, else `false`.\n */\n function isBindable(func) {\n var support = lodash.support,\n result = !(support.funcNames ? func.name : support.funcDecomp);\n\n if (!result) {\n var source = fnToString.call(func);\n if (!support.funcNames) {\n result = !reFuncName.test(source);\n }\n if (!result) {\n // Check if `func` references the `this` keyword and store the result.\n result = reThis.test(source) || isNative(func);\n baseSetData(func, result);\n }\n }\n return result;\n }\n\n /**\n * Checks if `value` is a valid array-like index.\n *\n * @private\n * @param {*} value The value to check.\n * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.\n * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.\n */\n function isIndex(value, length) {\n value = +value;\n length = length == null ? MAX_SAFE_INTEGER : length;\n return value > -1 && value % 1 == 0 && value < length;\n }\n\n /**\n * Checks if the provided arguments are from an iteratee call.\n *\n * @private\n * @param {*} value The potential iteratee value argument.\n * @param {*} index The potential iteratee index or key argument.\n * @param {*} object The potential iteratee object argument.\n * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`.\n */\n function isIterateeCall(value, index, object) {\n if (!isObject(object)) {\n return false;\n }\n var type = typeof index;\n if (type == 'number') {\n var length = object.length,\n prereq = isLength(length) && isIndex(index, length);\n } else {\n prereq = type == 'string' && index in object;\n }\n if (prereq) {\n var other = object[index];\n return value === value ? value === other : other !== other;\n }\n return false;\n }\n\n /**\n * Checks if `value` is a valid array-like length.\n *\n * **Note:** This function is based on ES `ToLength`. See the\n * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength)\n * for more details.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.\n */\n function isLength(value) {\n return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;\n }\n\n /**\n * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` if suitable for strict\n * equality comparisons, else `false`.\n */\n function isStrictComparable(value) {\n return value === value && (value === 0 ? ((1 / value) > 0) : !isObject(value));\n }\n\n /**\n * Merges the function metadata of `source` into `data`.\n *\n * Merging metadata reduces the number of wrappers required to invoke a function.\n * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`\n * may be applied regardless of execution order. Methods like `_.ary` and `_.rearg`\n * augment function arguments, making the order in which they are executed important,\n * preventing the merging of metadata. However, we make an exception for a safe\n * common case where curried functions have `_.ary` and or `_.rearg` applied.\n *\n * @private\n * @param {Array} data The destination metadata.\n * @param {Array} source The source metadata.\n * @returns {Array} Returns `data`.\n */\n function mergeData(data, source) {\n var bitmask = data[1],\n srcBitmask = source[1],\n newBitmask = bitmask | srcBitmask;\n\n var arityFlags = ARY_FLAG | REARG_FLAG,\n bindFlags = BIND_FLAG | BIND_KEY_FLAG,\n comboFlags = arityFlags | bindFlags | CURRY_BOUND_FLAG | CURRY_RIGHT_FLAG;\n\n var isAry = bitmask & ARY_FLAG && !(srcBitmask & ARY_FLAG),\n isRearg = bitmask & REARG_FLAG && !(srcBitmask & REARG_FLAG),\n argPos = (isRearg ? data : source)[7],\n ary = (isAry ? data : source)[8];\n\n var isCommon = !(bitmask >= REARG_FLAG && srcBitmask > bindFlags) &&\n !(bitmask > bindFlags && srcBitmask >= REARG_FLAG);\n\n var isCombo = (newBitmask >= arityFlags && newBitmask <= comboFlags) &&\n (bitmask < REARG_FLAG || ((isRearg || isAry) && argPos.length <= ary));\n\n // Exit early if metadata can't be merged.\n if (!(isCommon || isCombo)) {\n return data;\n }\n // Use source `thisArg` if available.\n if (srcBitmask & BIND_FLAG) {\n data[2] = source[2];\n // Set when currying a bound function.\n newBitmask |= (bitmask & BIND_FLAG) ? 0 : CURRY_BOUND_FLAG;\n }\n // Compose partial arguments.\n var value = source[3];\n if (value) {\n var partials = data[3];\n data[3] = partials ? composeArgs(partials, value, source[4]) : arrayCopy(value);\n data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : arrayCopy(source[4]);\n }\n // Compose partial right arguments.\n value = source[5];\n if (value) {\n partials = data[5];\n data[5] = partials ? composeArgsRight(partials, value, source[6]) : arrayCopy(value);\n data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : arrayCopy(source[6]);\n }\n // Use source `argPos` if available.\n value = source[7];\n if (value) {\n data[7] = arrayCopy(value);\n }\n // Use source `ary` if it's smaller.\n if (srcBitmask & ARY_FLAG) {\n data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);\n }\n // Use source `arity` if one is not provided.\n if (data[9] == null) {\n data[9] = source[9];\n }\n // Use source `func` and merge bitmasks.\n data[0] = source[0];\n data[1] = newBitmask;\n\n return data;\n }\n\n /**\n * A specialized version of `_.pick` that picks `object` properties specified\n * by the `props` array.\n *\n * @private\n * @param {Object} object The source object.\n * @param {string[]} props The property names to pick.\n * @returns {Object} Returns the new object.\n */\n function pickByArray(object, props) {\n object = toObject(object);\n\n var index = -1,\n length = props.length,\n result = {};\n\n while (++index < length) {\n var key = props[index];\n if (key in object) {\n result[key] = object[key];\n }\n }\n return result;\n }\n\n /**\n * A specialized version of `_.pick` that picks `object` properties `predicate`\n * returns truthy for.\n *\n * @private\n * @param {Object} object The source object.\n * @param {Function} predicate The function invoked per iteration.\n * @returns {Object} Returns the new object.\n */\n function pickByCallback(object, predicate) {\n var result = {};\n baseForIn(object, function (value, key, object) {\n if (predicate(value, key, object)) {\n result[key] = value;\n }\n });\n return result;\n }\n\n /**\n * Reorder `array` according to the specified indexes where the element at\n * the first index is assigned as the first element, the element at\n * the second index is assigned as the second element, and so on.\n *\n * @private\n * @param {Array} array The array to reorder.\n * @param {Array} indexes The arranged array indexes.\n * @returns {Array} Returns `array`.\n */\n function reorder(array, indexes) {\n var arrLength = array.length,\n length = nativeMin(indexes.length, arrLength),\n oldArray = arrayCopy(array);\n\n while (length--) {\n var index = indexes[length];\n array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;\n }\n return array;\n }\n\n /**\n * Sets metadata for `func`.\n *\n * **Note:** If this function becomes hot, i.e. is invoked a lot in a short\n * period of time, it will trip its breaker and transition to an identity function\n * to avoid garbage collection pauses in V8. See [V8 issue 2070](https://code.google.com/p/v8/issues/detail?id=2070)\n * for more details.\n *\n * @private\n * @param {Function} func The function to associate metadata with.\n * @param {*} data The metadata.\n * @returns {Function} Returns `func`.\n */\n var setData = (function () {\n var count = 0,\n lastCalled = 0;\n\n return function (key, value) {\n var stamp = now(),\n remaining = HOT_SPAN - (stamp - lastCalled);\n\n lastCalled = stamp;\n if (remaining > 0) {\n if (++count >= HOT_COUNT) {\n return key;\n }\n } else {\n count = 0;\n }\n return baseSetData(key, value);\n };\n }());\n\n /**\n * A fallback implementation of `_.isPlainObject` which checks if `value`\n * is an object created by the `Object` constructor or has a `[[Prototype]]`\n * of `null`.\n *\n * @private\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n */\n function shimIsPlainObject(value) {\n var Ctor,\n support = lodash.support;\n\n // Exit early for non `Object` objects.\n if (!(isObjectLike(value) && objToString.call(value) == objectTag) ||\n (!hasOwnProperty.call(value, 'constructor') &&\n (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) {\n return false;\n }\n // IE < 9 iterates inherited properties before own properties. If the first\n // iterated property is an object's own property then there are no inherited\n // enumerable properties.\n var result;\n // In most environments an object's own properties are iterated before\n // its inherited properties. If the last iterated property is an object's\n // own property then there are no inherited enumerable properties.\n baseForIn(value, function (subValue, key) {\n result = key;\n });\n return typeof result == 'undefined' || hasOwnProperty.call(value, result);\n }\n\n /**\n * A fallback implementation of `Object.keys` which creates an array of the\n * own enumerable property names of `object`.\n *\n * @private\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the array of property names.\n */\n function shimKeys(object) {\n var props = keysIn(object),\n propsLength = props.length,\n length = propsLength && object.length,\n support = lodash.support;\n\n var allowIndexes = length && isLength(length) &&\n (isArray(object) || (support.nonEnumArgs && isArguments(object)));\n\n var index = -1,\n result = [];\n\n while (++index < propsLength) {\n var key = props[index];\n if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * Converts `value` to an array-like object if it is not one.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {Array|Object} Returns the array-like object.\n */\n function toIterable(value) {\n if (value == null) {\n return [];\n }\n if (!isLength(value.length)) {\n return values(value);\n }\n return isObject(value) ? value : Object(value);\n }\n\n /**\n * Converts `value` to an object if it is not one.\n *\n * @private\n * @param {*} value The value to process.\n * @returns {Object} Returns the object.\n */\n function toObject(value) {\n return isObject(value) ? value : Object(value);\n }\n\n /**\n * Creates a clone of `wrapper`.\n *\n * @private\n * @param {Object} wrapper The wrapper to clone.\n * @returns {Object} Returns the cloned wrapper.\n */\n function wrapperClone(wrapper) {\n return wrapper instanceof LazyWrapper\n ? wrapper.clone()\n : new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__, arrayCopy(wrapper.__actions__));\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of elements split into groups the length of `size`.\n * If `collection` can't be split evenly, the final chunk will be the remaining\n * elements.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to process.\n * @param {number} [size=1] The length of each chunk.\n * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.\n * @returns {Array} Returns the new array containing chunks.\n * @example\n *\n * _.chunk(['a', 'b', 'c', 'd'], 2);\n * // => [['a', 'b'], ['c', 'd']]\n *\n * _.chunk(['a', 'b', 'c', 'd'], 3);\n * // => [['a', 'b', 'c'], ['d']]\n */\n function chunk(array, size, guard) {\n if (guard ? isIterateeCall(array, size, guard) : size == null) {\n size = 1;\n } else {\n size = nativeMax(+size || 1, 1);\n }\n var index = 0,\n length = array ? array.length : 0,\n resIndex = -1,\n result = Array(ceil(length / size));\n\n while (index < length) {\n result[++resIndex] = baseSlice(array, index, (index += size));\n }\n return result;\n }\n\n /**\n * Creates an array with all falsey values removed. The values `false`, `null`,\n * `0`, `\"\"`, `undefined`, and `NaN` are falsey.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to compact.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.compact([0, 1, false, 2, '', 3]);\n * // => [1, 2, 3]\n */\n function compact(array) {\n var index = -1,\n length = array ? array.length : 0,\n resIndex = -1,\n result = [];\n\n while (++index < length) {\n var value = array[index];\n if (value) {\n result[++resIndex] = value;\n }\n }\n return result;\n }\n\n /**\n * Creates an array excluding all values of the provided arrays using\n * `SameValueZero` for equality comparisons.\n *\n * **Note:** `SameValueZero` comparisons are like strict equality comparisons,\n * e.g. `===`, except that `NaN` matches `NaN`. See the\n * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {...Array} [values] The arrays of values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.difference([1, 2, 3], [4, 2]);\n * // => [1, 3]\n */\n function difference() {\n var index = -1,\n length = arguments.length;\n\n while (++index < length) {\n var value = arguments[index];\n if (isArray(value) || isArguments(value)) {\n break;\n }\n }\n return baseDifference(value, baseFlatten(arguments, false, true, ++index));\n }\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the beginning.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.drop([1, 2, 3]);\n * // => [2, 3]\n *\n * _.drop([1, 2, 3], 2);\n * // => [3]\n *\n * _.drop([1, 2, 3], 5);\n * // => []\n *\n * _.drop([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function drop(array, n, guard) {\n var length = array ? array.length : 0;\n if (!length) {\n return [];\n }\n if (guard ? isIterateeCall(array, n, guard) : n == null) {\n n = 1;\n }\n return baseSlice(array, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` with `n` elements dropped from the end.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to drop.\n * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.dropRight([1, 2, 3]);\n * // => [1, 2]\n *\n * _.dropRight([1, 2, 3], 2);\n * // => [1]\n *\n * _.dropRight([1, 2, 3], 5);\n * // => []\n *\n * _.dropRight([1, 2, 3], 0);\n * // => [1, 2, 3]\n */\n function dropRight(array, n, guard) {\n var length = array ? array.length : 0;\n if (!length) {\n return [];\n }\n if (guard ? isIterateeCall(array, n, guard) : n == null) {\n n = 1;\n }\n n = length - (+n || 0);\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the end.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * bound to `thisArg` and invoked with three arguments; (value, index, array).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that match the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.dropRightWhile([1, 2, 3], function(n) {\n * return n > 1;\n * });\n * // => [1]\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * // using the `_.matches` callback shorthand\n * _.pluck(_.dropRightWhile(users, { 'user': pebbles, 'active': false }), 'user');\n * // => ['barney', 'fred']\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.pluck(_.dropRightWhile(users, 'active', false), 'user');\n * // => ['barney']\n *\n * // using the `_.property` callback shorthand\n * _.pluck(_.dropRightWhile(users, 'active'), 'user');\n * // => ['barney', 'fred', 'pebbles']\n */\n function dropRightWhile(array, predicate, thisArg) {\n var length = array ? array.length : 0;\n if (!length) {\n return [];\n }\n predicate = getCallback(predicate, thisArg, 3);\n while (length-- && predicate(array[length], length, array)) { }\n return baseSlice(array, 0, length + 1);\n }\n\n /**\n * Creates a slice of `array` excluding elements dropped from the beginning.\n * Elements are dropped until `predicate` returns falsey. The predicate is\n * bound to `thisArg` and invoked with three arguments; (value, index, array).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.dropWhile([1, 2, 3], function(n) {\n * return n < 3;\n * });\n * // => [3]\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * // using the `_.matches` callback shorthand\n * _.pluck(_.dropWhile(users, { 'user': 'barney', 'active': false }), 'user');\n * // => ['fred', 'pebbles']\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.pluck(_.dropWhile(users, 'active', false), 'user');\n * // => ['pebbles']\n *\n * // using the `_.property` callback shorthand\n * _.pluck(_.dropWhile(users, 'active'), 'user');\n * // => ['barney', 'fred', 'pebbles']\n */\n function dropWhile(array, predicate, thisArg) {\n var length = array ? array.length : 0;\n if (!length) {\n return [];\n }\n var index = -1;\n predicate = getCallback(predicate, thisArg, 3);\n while (++index < length && predicate(array[index], index, array)) { }\n return baseSlice(array, index);\n }\n\n /**\n * Fills elements of `array` with `value` from `start` up to, but not\n * including, `end`.\n *\n * **Note:** This method mutates `array`.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to fill.\n * @param {*} value The value to fill `array` with.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns `array`.\n */\n function fill(array, value, start, end) {\n var length = array ? array.length : 0;\n if (!length) {\n return [];\n }\n if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {\n start = 0;\n end = length;\n }\n return baseFill(array, value, start, end);\n }\n\n /**\n * This method is like `_.find` except that it returns the index of the first\n * element `predicate` returns truthy for, instead of the element itself.\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to search.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * _.findIndex(users, function(chr) {\n * return chr.user == 'barney';\n * });\n * // => 0\n *\n * // using the `_.matches` callback shorthand\n * _.findIndex(users, { 'user': 'fred', 'active': false });\n * // => 1\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.findIndex(users, 'active', false);\n * // => 0\n *\n * // using the `_.property` callback shorthand\n * _.findIndex(users, 'active');\n * // => 2\n */\n function findIndex(array, predicate, thisArg) {\n var index = -1,\n length = array ? array.length : 0;\n\n predicate = getCallback(predicate, thisArg, 3);\n while (++index < length) {\n if (predicate(array[index], index, array)) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * This method is like `_.findIndex` except that it iterates over elements\n * of `collection` from right to left.\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to search.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {number} Returns the index of the found element, else `-1`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * _.findLastIndex(users, function(chr) {\n * return chr.user == 'pebbles';\n * });\n * // => 2\n *\n * // using the `_.matches` callback shorthand\n * _.findLastIndex(users, { 'user': 'barney', 'active': true });\n * // => 0\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.findLastIndex(users, 'active', false);\n * // => 1\n *\n * // using the `_.property` callback shorthand\n * _.findLastIndex(users, 'active');\n * // => 0\n */\n function findLastIndex(array, predicate, thisArg) {\n var length = array ? array.length : 0;\n predicate = getCallback(predicate, thisArg, 3);\n while (length--) {\n if (predicate(array[length], length, array)) {\n return length;\n }\n }\n return -1;\n }\n\n /**\n * Gets the first element of `array`.\n *\n * @static\n * @memberOf _\n * @alias head\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the first element of `array`.\n * @example\n *\n * _.first([1, 2, 3]);\n * // => 1\n *\n * _.first([]);\n * // => undefined\n */\n function first(array) {\n return array ? array[0] : undefined;\n }\n\n /**\n * Flattens a nested array. If `isDeep` is `true` the array is recursively\n * flattened, otherwise it is only flattened a single level.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to flatten.\n * @param {boolean} [isDeep] Specify a deep flatten.\n * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flatten([1, [2, 3, [4]]]);\n * // => [1, 2, 3, [4]];\n *\n * // using `isDeep`\n * _.flatten([1, [2, 3, [4]]], true);\n * // => [1, 2, 3, 4];\n */\n function flatten(array, isDeep, guard) {\n var length = array ? array.length : 0;\n if (guard && isIterateeCall(array, isDeep, guard)) {\n isDeep = false;\n }\n return length ? baseFlatten(array, isDeep) : [];\n }\n\n /**\n * Recursively flattens a nested array.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to recursively flatten.\n * @returns {Array} Returns the new flattened array.\n * @example\n *\n * _.flattenDeep([1, [2, 3, [4]]]);\n * // => [1, 2, 3, 4];\n */\n function flattenDeep(array) {\n var length = array ? array.length : 0;\n return length ? baseFlatten(array, true) : [];\n }\n\n /**\n * Gets the index at which the first occurrence of `value` is found in `array`\n * using `SameValueZero` for equality comparisons. If `fromIndex` is negative,\n * it is used as the offset from the end of `array`. If `array` is sorted\n * providing `true` for `fromIndex` performs a faster binary search.\n *\n * **Note:** `SameValueZero` comparisons are like strict equality comparisons,\n * e.g. `===`, except that `NaN` matches `NaN`. See the\n * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to search.\n * @param {*} value The value to search for.\n * @param {boolean|number} [fromIndex=0] The index to search from or `true`\n * to perform a binary search on a sorted array.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.indexOf([1, 2, 1, 2], 2);\n * // => 1\n *\n * // using `fromIndex`\n * _.indexOf([1, 2, 1, 2], 2, 2);\n * // => 3\n *\n * // performing a binary search\n * _.indexOf([1, 1, 2, 2], 2, true);\n * // => 2\n */\n function indexOf(array, value, fromIndex) {\n var length = array ? array.length : 0;\n if (!length) {\n return -1;\n }\n if (typeof fromIndex == 'number') {\n fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);\n } else if (fromIndex) {\n var index = binaryIndex(array, value),\n other = array[index];\n\n return (value === value ? value === other : other !== other) ? index : -1;\n }\n return baseIndexOf(array, value, fromIndex);\n }\n\n /**\n * Gets all but the last element of `array`.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.initial([1, 2, 3]);\n * // => [1, 2]\n */\n function initial(array) {\n return dropRight(array, 1);\n }\n\n /**\n * Creates an array of unique values in all provided arrays using `SameValueZero`\n * for equality comparisons.\n *\n * **Note:** `SameValueZero` comparisons are like strict equality comparisons,\n * e.g. `===`, except that `NaN` matches `NaN`. See the\n * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of shared values.\n * @example\n * _.intersection([1, 2], [4, 2], [2, 1]);\n * // => [2]\n */\n function intersection() {\n var args = [],\n argsIndex = -1,\n argsLength = arguments.length,\n caches = [],\n indexOf = getIndexOf(),\n isCommon = indexOf == baseIndexOf;\n\n while (++argsIndex < argsLength) {\n var value = arguments[argsIndex];\n if (isArray(value) || isArguments(value)) {\n args.push(value);\n caches.push((isCommon && value.length >= 120) ? createCache(argsIndex && value) : null);\n }\n }\n argsLength = args.length;\n var array = args[0],\n index = -1,\n length = array ? array.length : 0,\n result = [],\n seen = caches[0];\n\n outer:\n while (++index < length) {\n value = array[index];\n if ((seen ? cacheIndexOf(seen, value) : indexOf(result, value)) < 0) {\n argsIndex = argsLength;\n while (--argsIndex) {\n var cache = caches[argsIndex];\n if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) {\n continue outer;\n }\n }\n if (seen) {\n seen.push(value);\n }\n result.push(value);\n }\n }\n return result;\n }\n\n /**\n * Gets the last element of `array`.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to query.\n * @returns {*} Returns the last element of `array`.\n * @example\n *\n * _.last([1, 2, 3]);\n * // => 3\n */\n function last(array) {\n var length = array ? array.length : 0;\n return length ? array[length - 1] : undefined;\n }\n\n /**\n * This method is like `_.indexOf` except that it iterates over elements of\n * `array` from right to left.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to search.\n * @param {*} value The value to search for.\n * @param {boolean|number} [fromIndex=array.length-1] The index to search from\n * or `true` to perform a binary search on a sorted array.\n * @returns {number} Returns the index of the matched value, else `-1`.\n * @example\n *\n * _.lastIndexOf([1, 2, 1, 2], 2);\n * // => 3\n *\n * // using `fromIndex`\n * _.lastIndexOf([1, 2, 1, 2], 2, 2);\n * // => 1\n *\n * // performing a binary search\n * _.lastIndexOf([1, 1, 2, 2], 2, true);\n * // => 3\n */\n function lastIndexOf(array, value, fromIndex) {\n var length = array ? array.length : 0;\n if (!length) {\n return -1;\n }\n var index = length;\n if (typeof fromIndex == 'number') {\n index = (fromIndex < 0 ? nativeMax(length + fromIndex, 0) : nativeMin(fromIndex || 0, length - 1)) + 1;\n } else if (fromIndex) {\n index = binaryIndex(array, value, true) - 1;\n var other = array[index];\n return (value === value ? value === other : other !== other) ? index : -1;\n }\n if (value !== value) {\n return indexOfNaN(array, index, true);\n }\n while (index--) {\n if (array[index] === value) {\n return index;\n }\n }\n return -1;\n }\n\n /**\n * Removes all provided values from `array` using `SameValueZero` for equality\n * comparisons.\n *\n * **Notes:**\n * - Unlike `_.without`, this method mutates `array`.\n * - `SameValueZero` comparisons are like strict equality comparisons, e.g. `===`,\n * except that `NaN` matches `NaN`. See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...*} [values] The values to remove.\n * @returns {Array} Returns `array`.\n * @example\n *\n * var array = [1, 2, 3, 1, 2, 3];\n *\n * _.pull(array, 2, 3);\n * console.log(array);\n * // => [1, 1]\n */\n function pull() {\n var array = arguments[0];\n if (!(array && array.length)) {\n return array;\n }\n var index = 0,\n indexOf = getIndexOf(),\n length = arguments.length;\n\n while (++index < length) {\n var fromIndex = 0,\n value = arguments[index];\n\n while ((fromIndex = indexOf(array, value, fromIndex)) > -1) {\n splice.call(array, fromIndex, 1);\n }\n }\n return array;\n }\n\n /**\n * Removes elements from `array` corresponding to the given indexes and returns\n * an array of the removed elements. Indexes may be specified as an array of\n * indexes or as individual arguments.\n *\n * **Note:** Unlike `_.at`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to modify.\n * @param {...(number|number[])} [indexes] The indexes of elements to remove,\n * specified as individual indexes or arrays of indexes.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = [5, 10, 15, 20];\n * var evens = _.pullAt(array, 1, 3);\n *\n * console.log(array);\n * // => [5, 15]\n *\n * console.log(evens);\n * // => [10, 20]\n */\n function pullAt(array) {\n return basePullAt(array || [], baseFlatten(arguments, false, false, 1));\n }\n\n /**\n * Removes all elements from `array` that `predicate` returns truthy for\n * and returns an array of the removed elements. The predicate is bound to\n * `thisArg` and invoked with three arguments; (value, index, array).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * **Note:** Unlike `_.filter`, this method mutates `array`.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to modify.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {Array} Returns the new array of removed elements.\n * @example\n *\n * var array = [1, 2, 3, 4];\n * var evens = _.remove(array, function(n) {\n * return n % 2 == 0;\n * });\n *\n * console.log(array);\n * // => [1, 3]\n *\n * console.log(evens);\n * // => [2, 4]\n */\n function remove(array, predicate, thisArg) {\n var index = -1,\n length = array ? array.length : 0,\n result = [];\n\n predicate = getCallback(predicate, thisArg, 3);\n while (++index < length) {\n var value = array[index];\n if (predicate(value, index, array)) {\n result.push(value);\n splice.call(array, index--, 1);\n length--;\n }\n }\n return result;\n }\n\n /**\n * Gets all but the first element of `array`.\n *\n * @static\n * @memberOf _\n * @alias tail\n * @category Array\n * @param {Array} array The array to query.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.rest([1, 2, 3]);\n * // => [2, 3]\n */\n function rest(array) {\n return drop(array, 1);\n }\n\n /**\n * Creates a slice of `array` from `start` up to, but not including, `end`.\n *\n * **Note:** This function is used instead of `Array#slice` to support node\n * lists in IE < 9 and to ensure dense arrays are returned.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to slice.\n * @param {number} [start=0] The start position.\n * @param {number} [end=array.length] The end position.\n * @returns {Array} Returns the slice of `array`.\n */\n function slice(array, start, end) {\n var length = array ? array.length : 0;\n if (!length) {\n return [];\n }\n if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {\n start = 0;\n end = length;\n }\n return baseSlice(array, start, end);\n }\n\n /**\n * Uses a binary search to determine the lowest index at which `value` should\n * be inserted into `array` in order to maintain its sort order. If an iteratee\n * function is provided it is invoked for `value` and each element of `array`\n * to compute their sort ranking. The iteratee is bound to `thisArg` and\n * invoked with one argument; (value).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function|Object|string} [iteratee=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedIndex([30, 50], 40);\n * // => 1\n *\n * _.sortedIndex([4, 4, 5, 5], 5);\n * // => 2\n *\n * var dict = { 'data': { 'thirty': 30, 'forty': 40, 'fifty': 50 } };\n *\n * // using an iteratee function\n * _.sortedIndex(['thirty', 'fifty'], 'forty', function(word) {\n * return this.data[word];\n * }, dict);\n * // => 1\n *\n * // using the `_.property` callback shorthand\n * _.sortedIndex([{ 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x');\n * // => 1\n */\n function sortedIndex(array, value, iteratee, thisArg) {\n var func = getCallback(iteratee);\n return (func === baseCallback && iteratee == null)\n ? binaryIndex(array, value)\n : binaryIndexBy(array, value, func(iteratee, thisArg, 1));\n }\n\n /**\n * This method is like `_.sortedIndex` except that it returns the highest\n * index at which `value` should be inserted into `array` in order to\n * maintain its sort order.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The sorted array to inspect.\n * @param {*} value The value to evaluate.\n * @param {Function|Object|string} [iteratee=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {number} Returns the index at which `value` should be inserted\n * into `array`.\n * @example\n *\n * _.sortedLastIndex([4, 4, 5, 5], 5);\n * // => 4\n */\n function sortedLastIndex(array, value, iteratee, thisArg) {\n var func = getCallback(iteratee);\n return (func === baseCallback && iteratee == null)\n ? binaryIndex(array, value, true)\n : binaryIndexBy(array, value, func(iteratee, thisArg, 1), true);\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the beginning.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.take([1, 2, 3]);\n * // => [1]\n *\n * _.take([1, 2, 3], 2);\n * // => [1, 2]\n *\n * _.take([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.take([1, 2, 3], 0);\n * // => []\n */\n function take(array, n, guard) {\n var length = array ? array.length : 0;\n if (!length) {\n return [];\n }\n if (guard ? isIterateeCall(array, n, guard) : n == null) {\n n = 1;\n }\n return baseSlice(array, 0, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` with `n` elements taken from the end.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to query.\n * @param {number} [n=1] The number of elements to take.\n * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.takeRight([1, 2, 3]);\n * // => [3]\n *\n * _.takeRight([1, 2, 3], 2);\n * // => [2, 3]\n *\n * _.takeRight([1, 2, 3], 5);\n * // => [1, 2, 3]\n *\n * _.takeRight([1, 2, 3], 0);\n * // => []\n */\n function takeRight(array, n, guard) {\n var length = array ? array.length : 0;\n if (!length) {\n return [];\n }\n if (guard ? isIterateeCall(array, n, guard) : n == null) {\n n = 1;\n }\n n = length - (+n || 0);\n return baseSlice(array, n < 0 ? 0 : n);\n }\n\n /**\n * Creates a slice of `array` with elements taken from the end. Elements are\n * taken until `predicate` returns falsey. The predicate is bound to `thisArg`\n * and invoked with three arguments; (value, index, array).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.takeRightWhile([1, 2, 3], function(n) {\n * return n > 1;\n * });\n * // => [2, 3]\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false },\n * { 'user': 'pebbles', 'active': false }\n * ];\n *\n * // using the `_.matches` callback shorthand\n * _.pluck(_.takeRightWhile(users, { 'user': 'pebbles', 'active': false }), 'user');\n * // => ['pebbles']\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.pluck(_.takeRightWhile(users, 'active', false), 'user');\n * // => ['fred', 'pebbles']\n *\n * // using the `_.property` callback shorthand\n * _.pluck(_.takeRightWhile(users, 'active'), 'user');\n * // => []\n */\n function takeRightWhile(array, predicate, thisArg) {\n var length = array ? array.length : 0;\n if (!length) {\n return [];\n }\n predicate = getCallback(predicate, thisArg, 3);\n while (length-- && predicate(array[length], length, array)) { }\n return baseSlice(array, length + 1);\n }\n\n /**\n * Creates a slice of `array` with elements taken from the beginning. Elements\n * are taken until `predicate` returns falsey. The predicate is bound to\n * `thisArg` and invoked with three arguments; (value, index, array).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to query.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {Array} Returns the slice of `array`.\n * @example\n *\n * _.takeWhile([1, 2, 3], function(n) {\n * return n < 3;\n * });\n * // => [1, 2]\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false},\n * { 'user': 'pebbles', 'active': true }\n * ];\n *\n * // using the `_.matches` callback shorthand\n * _.pluck(_.takeWhile(users, { 'user': 'barney', 'active': false }), 'user');\n * // => ['barney']\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.pluck(_.takeWhile(users, 'active', false), 'user');\n * // => ['barney', 'fred']\n *\n * // using the `_.property` callback shorthand\n * _.pluck(_.takeWhile(users, 'active'), 'user');\n * // => []\n */\n function takeWhile(array, predicate, thisArg) {\n var length = array ? array.length : 0;\n if (!length) {\n return [];\n }\n var index = -1;\n predicate = getCallback(predicate, thisArg, 3);\n while (++index < length && predicate(array[index], index, array)) { }\n return baseSlice(array, 0, index);\n }\n\n /**\n * Creates an array of unique values, in order, of the provided arrays using\n * `SameValueZero` for equality comparisons.\n *\n * **Note:** `SameValueZero` comparisons are like strict equality comparisons,\n * e.g. `===`, except that `NaN` matches `NaN`. See the\n * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of combined values.\n * @example\n *\n * _.union([1, 2], [4, 2], [2, 1]);\n * // => [1, 2, 4]\n */\n function union() {\n return baseUniq(baseFlatten(arguments, false, true));\n }\n\n /**\n * Creates a duplicate-value-free version of an array using `SameValueZero`\n * for equality comparisons. Providing `true` for `isSorted` performs a faster\n * search algorithm for sorted arrays. If an iteratee function is provided it\n * is invoked for each value in the array to generate the criterion by which\n * uniqueness is computed. The `iteratee` is bound to `thisArg` and invoked\n * with three arguments; (value, index, array).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * **Note:** `SameValueZero` comparisons are like strict equality comparisons,\n * e.g. `===`, except that `NaN` matches `NaN`. See the\n * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)\n * for more details.\n *\n * @static\n * @memberOf _\n * @alias unique\n * @category Array\n * @param {Array} array The array to inspect.\n * @param {boolean} [isSorted] Specify the array is sorted.\n * @param {Function|Object|string} [iteratee] The function invoked per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {Array} Returns the new duplicate-value-free array.\n * @example\n *\n * _.uniq([1, 2, 1]);\n * // => [1, 2]\n *\n * // using `isSorted`\n * _.uniq([1, 1, 2], true);\n * // => [1, 2]\n *\n * // using an iteratee function\n * _.uniq([1, 2.5, 1.5, 2], function(n) {\n * return this.floor(n);\n * }, Math);\n * // => [1, 2.5]\n *\n * // using the `_.property` callback shorthand\n * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');\n * // => [{ 'x': 1 }, { 'x': 2 }]\n */\n function uniq(array, isSorted, iteratee, thisArg) {\n var length = array ? array.length : 0;\n if (!length) {\n return [];\n }\n if (isSorted != null && typeof isSorted != 'boolean') {\n thisArg = iteratee;\n iteratee = isIterateeCall(array, isSorted, thisArg) ? null : isSorted;\n isSorted = false;\n }\n var func = getCallback();\n if (!(func === baseCallback && iteratee == null)) {\n iteratee = func(iteratee, thisArg, 3);\n }\n return (isSorted && getIndexOf() == baseIndexOf)\n ? sortedUniq(array, iteratee)\n : baseUniq(array, iteratee);\n }\n\n /**\n * This method is like `_.zip` except that it accepts an array of grouped\n * elements and creates an array regrouping the elements to their pre-`_.zip`\n * configuration.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array of grouped elements to process.\n * @returns {Array} Returns the new array of regrouped elements.\n * @example\n *\n * var zipped = _.zip(['fred', 'barney'], [30, 40], [true, false]);\n * // => [['fred', 30, true], ['barney', 40, false]]\n *\n * _.unzip(zipped);\n * // => [['fred', 'barney'], [30, 40], [true, false]]\n */\n function unzip(array) {\n var index = -1,\n length = (array && array.length && arrayMax(arrayMap(array, getLength))) >>> 0,\n result = Array(length);\n\n while (++index < length) {\n result[index] = arrayMap(array, baseProperty(index));\n }\n return result;\n }\n\n /**\n * Creates an array excluding all provided values using `SameValueZero` for\n * equality comparisons.\n *\n * **Note:** `SameValueZero` comparisons are like strict equality comparisons,\n * e.g. `===`, except that `NaN` matches `NaN`. See the\n * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {Array} array The array to filter.\n * @param {...*} [values] The values to exclude.\n * @returns {Array} Returns the new array of filtered values.\n * @example\n *\n * _.without([1, 2, 1, 3], 1, 2);\n * // => [3]\n */\n function without(array) {\n return baseDifference(array, baseSlice(arguments, 1));\n }\n\n /**\n * Creates an array that is the symmetric difference of the provided arrays.\n * See [Wikipedia](https://en.wikipedia.org/wiki/Symmetric_difference) for\n * more details.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {...Array} [arrays] The arrays to inspect.\n * @returns {Array} Returns the new array of values.\n * @example\n *\n * _.xor([1, 2], [4, 2]);\n * // => [1, 4]\n */\n function xor() {\n var index = -1,\n length = arguments.length;\n\n while (++index < length) {\n var array = arguments[index];\n if (isArray(array) || isArguments(array)) {\n var result = result\n ? baseDifference(result, array).concat(baseDifference(array, result))\n : array;\n }\n }\n return result ? baseUniq(result) : [];\n }\n\n /**\n * Creates an array of grouped elements, the first of which contains the first\n * elements of the given arrays, the second of which contains the second elements\n * of the given arrays, and so on.\n *\n * @static\n * @memberOf _\n * @category Array\n * @param {...Array} [arrays] The arrays to process.\n * @returns {Array} Returns the new array of grouped elements.\n * @example\n *\n * _.zip(['fred', 'barney'], [30, 40], [true, false]);\n * // => [['fred', 30, true], ['barney', 40, false]]\n */\n function zip() {\n var length = arguments.length,\n array = Array(length);\n\n while (length--) {\n array[length] = arguments[length];\n }\n return unzip(array);\n }\n\n /**\n * Creates an object composed from arrays of property names and values. Provide\n * either a single two dimensional array, e.g. `[[key1, value1], [key2, value2]]`\n * or two arrays, one of property names and one of corresponding values.\n *\n * @static\n * @memberOf _\n * @alias object\n * @category Array\n * @param {Array} props The property names.\n * @param {Array} [values=[]] The property values.\n * @returns {Object} Returns the new object.\n * @example\n *\n * _.zipObject(['fred', 'barney'], [30, 40]);\n * // => { 'fred': 30, 'barney': 40 }\n */\n function zipObject(props, values) {\n var index = -1,\n length = props ? props.length : 0,\n result = {};\n\n if (length && !values && !isArray(props[0])) {\n values = [];\n }\n while (++index < length) {\n var key = props[index];\n if (values) {\n result[key] = values[index];\n } else if (key) {\n result[key[0]] = key[1];\n }\n }\n return result;\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a `lodash` object that wraps `value` with explicit method\n * chaining enabled.\n *\n * @static\n * @memberOf _\n * @category Chain\n * @param {*} value The value to wrap.\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'pebbles', 'age': 1 }\n * ];\n *\n * var youngest = _.chain(users)\n * .sortBy('age')\n * .map(function(chr) {\n * return chr.user + ' is ' + chr.age;\n * })\n * .first()\n * .value();\n * // => 'pebbles is 1'\n */\n function chain(value) {\n var result = lodash(value);\n result.__chain__ = true;\n return result;\n }\n\n /**\n * This method invokes `interceptor` and returns `value`. The interceptor is\n * bound to `thisArg` and invoked with one argument; (value). The purpose of\n * this method is to \"tap into\" a method chain in order to perform operations\n * on intermediate results within the chain.\n *\n * @static\n * @memberOf _\n * @category Chain\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @param {*} [thisArg] The `this` binding of `interceptor`.\n * @returns {*} Returns `value`.\n * @example\n *\n * _([1, 2, 3])\n * .tap(function(array) {\n * array.pop();\n * })\n * .reverse()\n * .value();\n * // => [2, 1]\n */\n function tap(value, interceptor, thisArg) {\n interceptor.call(thisArg, value);\n return value;\n }\n\n /**\n * This method is like `_.tap` except that it returns the result of `interceptor`.\n *\n * @static\n * @memberOf _\n * @category Chain\n * @param {*} value The value to provide to `interceptor`.\n * @param {Function} interceptor The function to invoke.\n * @param {*} [thisArg] The `this` binding of `interceptor`.\n * @returns {*} Returns the result of `interceptor`.\n * @example\n *\n * _([1, 2, 3])\n * .last()\n * .thru(function(value) {\n * return [value];\n * })\n * .value();\n * // => [3]\n */\n function thru(value, interceptor, thisArg) {\n return interceptor.call(thisArg, value);\n }\n\n /**\n * Enables explicit method chaining on the wrapper object.\n *\n * @name chain\n * @memberOf _\n * @category Chain\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 }\n * ];\n *\n * // without explicit chaining\n * _(users).first();\n * // => { 'user': 'barney', 'age': 36 }\n *\n * // with explicit chaining\n * _(users).chain()\n * .first()\n * .pick('user')\n * .value();\n * // => { 'user': 'barney' }\n */\n function wrapperChain() {\n return chain(this);\n }\n\n /**\n * Executes the chained sequence and returns the wrapped result.\n *\n * @name commit\n * @memberOf _\n * @category Chain\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2];\n * var wrapper = _(array).push(3);\n *\n * console.log(array);\n * // => [1, 2]\n *\n * wrapper = wrapper.commit();\n * console.log(array);\n * // => [1, 2, 3]\n *\n * wrapper.last();\n * // => 3\n *\n * console.log(array);\n * // => [1, 2, 3]\n */\n function wrapperCommit() {\n return new LodashWrapper(this.value(), this.__chain__);\n }\n\n /**\n * Creates a clone of the chained sequence planting `value` as the wrapped value.\n *\n * @name plant\n * @memberOf _\n * @category Chain\n * @returns {Object} Returns the new `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2];\n * var wrapper = _(array).map(function(value) {\n * return Math.pow(value, 2);\n * });\n *\n * var other = [3, 4];\n * var otherWrapper = wrapper.plant(other);\n *\n * otherWrapper.value();\n * // => [9, 16]\n *\n * wrapper.value();\n * // => [1, 4]\n */\n function wrapperPlant(value) {\n var result,\n parent = this;\n\n while (parent instanceof baseLodash) {\n var clone = wrapperClone(parent);\n if (result) {\n previous.__wrapped__ = clone;\n } else {\n result = clone;\n }\n var previous = clone;\n parent = parent.__wrapped__;\n }\n previous.__wrapped__ = value;\n return result;\n }\n\n /**\n * Reverses the wrapped array so the first element becomes the last, the\n * second element becomes the second to last, and so on.\n *\n * **Note:** This method mutates the wrapped array.\n *\n * @name reverse\n * @memberOf _\n * @category Chain\n * @returns {Object} Returns the new reversed `lodash` wrapper instance.\n * @example\n *\n * var array = [1, 2, 3];\n *\n * _(array).reverse().value()\n * // => [3, 2, 1]\n *\n * console.log(array);\n * // => [3, 2, 1]\n */\n function wrapperReverse() {\n var value = this.__wrapped__;\n if (value instanceof LazyWrapper) {\n if (this.__actions__.length) {\n value = new LazyWrapper(this);\n }\n return new LodashWrapper(value.reverse(), this.__chain__);\n }\n return this.thru(function (value) {\n return value.reverse();\n });\n }\n\n /**\n * Produces the result of coercing the unwrapped value to a string.\n *\n * @name toString\n * @memberOf _\n * @category Chain\n * @returns {string} Returns the coerced string value.\n * @example\n *\n * _([1, 2, 3]).toString();\n * // => '1,2,3'\n */\n function wrapperToString() {\n return (this.value() + '');\n }\n\n /**\n * Executes the chained sequence to extract the unwrapped value.\n *\n * @name value\n * @memberOf _\n * @alias run, toJSON, valueOf\n * @category Chain\n * @returns {*} Returns the resolved unwrapped value.\n * @example\n *\n * _([1, 2, 3]).value();\n * // => [1, 2, 3]\n */\n function wrapperValue() {\n return baseWrapperValue(this.__wrapped__, this.__actions__);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates an array of elements corresponding to the given keys, or indexes,\n * of `collection`. Keys may be specified as individual arguments or as arrays\n * of keys.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {...(number|number[]|string|string[])} [props] The property names\n * or indexes of elements to pick, specified individually or in arrays.\n * @returns {Array} Returns the new array of picked elements.\n * @example\n *\n * _.at(['a', 'b', 'c'], [0, 2]);\n * // => ['a', 'c']\n *\n * _.at(['fred', 'barney', 'pebbles'], 0, 2);\n * // => ['fred', 'pebbles']\n */\n function at(collection) {\n var length = collection ? collection.length : 0;\n if (isLength(length)) {\n collection = toIterable(collection);\n }\n return baseAt(collection, baseFlatten(arguments, false, false, 1));\n }\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` through `iteratee`. The corresponding value\n * of each key is the number of times the key was returned by `iteratee`.\n * The `iteratee` is bound to `thisArg` and invoked with three arguments;\n * (value, index|key, collection).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function|Object|string} [iteratee=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.countBy([4.3, 6.1, 6.4], function(n) {\n * return Math.floor(n);\n * });\n * // => { '4': 1, '6': 2 }\n *\n * _.countBy([4.3, 6.1, 6.4], function(n) {\n * return this.floor(n);\n * }, Math);\n * // => { '4': 1, '6': 2 }\n *\n * _.countBy(['one', 'two', 'three'], 'length');\n * // => { '3': 2, '5': 1 }\n */\n var countBy = createAggregator(function (result, value, key) {\n hasOwnProperty.call(result, key) ? ++result[key] : (result[key] = 1);\n });\n\n /**\n * Checks if `predicate` returns truthy for **all** elements of `collection`.\n * The predicate is bound to `thisArg` and invoked with three arguments;\n * (value, index|key, collection).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @alias all\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {boolean} Returns `true` if all elements pass the predicate check,\n * else `false`.\n * @example\n *\n * _.every([true, 1, null, 'yes'], Boolean);\n * // => false\n *\n * var users = [\n * { 'user': 'barney', 'active': false },\n * { 'user': 'fred', 'active': false }\n * ];\n *\n * // using the `_.matches` callback shorthand\n * _.every(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.every(users, 'active', false);\n * // => true\n *\n * // using the `_.property` callback shorthand\n * _.every(users, 'active');\n * // => false\n */\n function every(collection, predicate, thisArg) {\n var func = isArray(collection) ? arrayEvery : baseEvery;\n if (typeof predicate != 'function' || typeof thisArg != 'undefined') {\n predicate = getCallback(predicate, thisArg, 3);\n }\n return func(collection, predicate);\n }\n\n /**\n * Iterates over elements of `collection`, returning an array of all elements\n * `predicate` returns truthy for. The predicate is bound to `thisArg` and\n * invoked with three arguments; (value, index|key, collection).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @alias select\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {Array} Returns the new filtered array.\n * @example\n *\n * _.filter([4, 5, 6], function(n) {\n * return n % 2 == 0;\n * });\n * // => [4, 6]\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * // using the `_.matches` callback shorthand\n * _.pluck(_.filter(users, { 'age': 36, 'active': true }), 'user');\n * // => ['barney']\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.pluck(_.filter(users, 'active', false), 'user');\n * // => ['fred']\n *\n * // using the `_.property` callback shorthand\n * _.pluck(_.filter(users, 'active'), 'user');\n * // => ['barney']\n */\n function filter(collection, predicate, thisArg) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n predicate = getCallback(predicate, thisArg, 3);\n return func(collection, predicate);\n }\n\n /**\n * Iterates over elements of `collection`, returning the first element\n * `predicate` returns truthy for. The predicate is bound to `thisArg` and\n * invoked with three arguments; (value, index|key, collection).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @alias detect\n * @category Collection\n * @param {Array|Object|string} collection The collection to search.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false },\n * { 'user': 'pebbles', 'age': 1, 'active': true }\n * ];\n *\n * _.result(_.find(users, function(chr) {\n * return chr.age < 40;\n * }), 'user');\n * // => 'barney'\n *\n * // using the `_.matches` callback shorthand\n * _.result(_.find(users, { 'age': 1, 'active': true }), 'user');\n * // => 'pebbles'\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.result(_.find(users, 'active', false), 'user');\n * // => 'fred'\n *\n * // using the `_.property` callback shorthand\n * _.result(_.find(users, 'active'), 'user');\n * // => 'barney'\n */\n function find(collection, predicate, thisArg) {\n if (isArray(collection)) {\n var index = findIndex(collection, predicate, thisArg);\n return index > -1 ? collection[index] : undefined;\n }\n predicate = getCallback(predicate, thisArg, 3);\n return baseFind(collection, predicate, baseEach);\n }\n\n /**\n * This method is like `_.find` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to search.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * _.findLast([1, 2, 3, 4], function(n) {\n * return n % 2 == 1;\n * });\n * // => 3\n */\n function findLast(collection, predicate, thisArg) {\n predicate = getCallback(predicate, thisArg, 3);\n return baseFind(collection, predicate, baseEachRight);\n }\n\n /**\n * Performs a deep comparison between each element in `collection` and the\n * source object, returning the first element that has equivalent property\n * values.\n *\n * **Note:** This method supports comparing arrays, booleans, `Date` objects,\n * numbers, `Object` objects, regexes, and strings. Objects are compared by\n * their own, not inherited, enumerable properties. For comparing a single\n * own or inherited property value see `_.matchesProperty`.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to search.\n * @param {Object} source The object of property values to match.\n * @returns {*} Returns the matched element, else `undefined`.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': true },\n * { 'user': 'fred', 'age': 40, 'active': false }\n * ];\n *\n * _.result(_.findWhere(users, { 'age': 36, 'active': true }), 'user');\n * // => 'barney'\n *\n * _.result(_.findWhere(users, { 'age': 40, 'active': false }), 'user');\n * // => 'fred'\n */\n function findWhere(collection, source) {\n return find(collection, baseMatches(source));\n }\n\n /**\n * Iterates over elements of `collection` invoking `iteratee` for each element.\n * The `iteratee` is bound to `thisArg` and invoked with three arguments;\n * (value, index|key, collection). Iterator functions may exit iteration early\n * by explicitly returning `false`.\n *\n * **Note:** As with other \"Collections\" methods, objects with a `length` property\n * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn`\n * may be used for object iteration.\n *\n * @static\n * @memberOf _\n * @alias each\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {Array|Object|string} Returns `collection`.\n * @example\n *\n * _([1, 2]).forEach(function(n) {\n * console.log(n);\n * }).value();\n * // => logs each value from left to right and returns the array\n *\n * _.forEach({ 'a': 1, 'b': 2 }, function(n, key) {\n * console.log(n, key);\n * });\n * // => logs each value-key pair and returns the object (iteration order is not guaranteed)\n */\n function forEach(collection, iteratee, thisArg) {\n return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection))\n ? arrayEach(collection, iteratee)\n : baseEach(collection, bindCallback(iteratee, thisArg, 3));\n }\n\n /**\n * This method is like `_.forEach` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @alias eachRight\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {Array|Object|string} Returns `collection`.\n * @example\n *\n * _([1, 2]).forEachRight(function(n) {\n * console.log(n);\n * }).join(',');\n * // => logs each value from right to left and returns the array\n */\n function forEachRight(collection, iteratee, thisArg) {\n return (typeof iteratee == 'function' && typeof thisArg == 'undefined' && isArray(collection))\n ? arrayEachRight(collection, iteratee)\n : baseEachRight(collection, bindCallback(iteratee, thisArg, 3));\n }\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` through `iteratee`. The corresponding value\n * of each key is an array of the elements responsible for generating the key.\n * The `iteratee` is bound to `thisArg` and invoked with three arguments;\n * (value, index|key, collection).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function|Object|string} [iteratee=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * _.groupBy([4.2, 6.1, 6.4], function(n) {\n * return Math.floor(n);\n * });\n * // => { '4': [4.2], '6': [6.1, 6.4] }\n *\n * _.groupBy([4.2, 6.1, 6.4], function(n) {\n * return this.floor(n);\n * }, Math);\n * // => { '4': [4.2], '6': [6.1, 6.4] }\n *\n * // using the `_.property` callback shorthand\n * _.groupBy(['one', 'two', 'three'], 'length');\n * // => { '3': ['one', 'two'], '5': ['three'] }\n */\n var groupBy = createAggregator(function (result, value, key) {\n if (hasOwnProperty.call(result, key)) {\n result[key].push(value);\n } else {\n result[key] = [value];\n }\n });\n\n /**\n * Checks if `value` is in `collection` using `SameValueZero` for equality\n * comparisons. If `fromIndex` is negative, it is used as the offset from\n * the end of `collection`.\n *\n * **Note:** `SameValueZero` comparisons are like strict equality comparisons,\n * e.g. `===`, except that `NaN` matches `NaN`. See the\n * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-samevaluezero)\n * for more details.\n *\n * @static\n * @memberOf _\n * @alias contains, include\n * @category Collection\n * @param {Array|Object|string} collection The collection to search.\n * @param {*} target The value to search for.\n * @param {number} [fromIndex=0] The index to search from.\n * @returns {boolean} Returns `true` if a matching element is found, else `false`.\n * @example\n *\n * _.includes([1, 2, 3], 1);\n * // => true\n *\n * _.includes([1, 2, 3], 1, 2);\n * // => false\n *\n * _.includes({ 'user': 'fred', 'age': 40 }, 'fred');\n * // => true\n *\n * _.includes('pebbles', 'eb');\n * // => true\n */\n function includes(collection, target, fromIndex) {\n var length = collection ? collection.length : 0;\n if (!isLength(length)) {\n collection = values(collection);\n length = collection.length;\n }\n if (!length) {\n return false;\n }\n if (typeof fromIndex == 'number') {\n fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0);\n } else {\n fromIndex = 0;\n }\n return (typeof collection == 'string' || !isArray(collection) && isString(collection))\n ? (fromIndex < length && collection.indexOf(target, fromIndex) > -1)\n : (getIndexOf(collection, target, fromIndex) > -1);\n }\n\n /**\n * Creates an object composed of keys generated from the results of running\n * each element of `collection` through `iteratee`. The corresponding value\n * of each key is the last element responsible for generating the key. The\n * iteratee function is bound to `thisArg` and invoked with three arguments;\n * (value, index|key, collection).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function|Object|string} [iteratee=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {Object} Returns the composed aggregate object.\n * @example\n *\n * var keyData = [\n * { 'dir': 'left', 'code': 97 },\n * { 'dir': 'right', 'code': 100 }\n * ];\n *\n * _.indexBy(keyData, 'dir');\n * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }\n *\n * _.indexBy(keyData, function(object) {\n * return String.fromCharCode(object.code);\n * });\n * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }\n *\n * _.indexBy(keyData, function(object) {\n * return this.fromCharCode(object.code);\n * }, String);\n * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }\n */\n var indexBy = createAggregator(function (result, value, key) {\n result[key] = value;\n });\n\n /**\n * Invokes the method named by `methodName` on each element in `collection`,\n * returning an array of the results of each invoked method. Any additional\n * arguments are provided to each invoked method. If `methodName` is a function\n * it is invoked for, and `this` bound to, each element in `collection`.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function|string} methodName The name of the method to invoke or\n * the function invoked per iteration.\n * @param {...*} [args] The arguments to invoke the method with.\n * @returns {Array} Returns the array of results.\n * @example\n *\n * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort');\n * // => [[1, 5, 7], [1, 2, 3]]\n *\n * _.invoke([123, 456], String.prototype.split, '');\n * // => [['1', '2', '3'], ['4', '5', '6']]\n */\n function invoke(collection, methodName) {\n return baseInvoke(collection, methodName, baseSlice(arguments, 2));\n }\n\n /**\n * Creates an array of values by running each element in `collection` through\n * `iteratee`. The `iteratee` is bound to `thisArg` and invoked with three\n * arguments; (value, index|key, collection).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * Many lodash methods are guarded to work as interatees for methods like\n * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.\n *\n * The guarded methods are:\n * `ary`, `callback`, `chunk`, `clone`, `create`, `curry`, `curryRight`, `drop`,\n * `dropRight`, `fill`, `flatten`, `invert`, `max`, `min`, `parseInt`, `slice`,\n * `sortBy`, `take`, `takeRight`, `template`, `trim`, `trimLeft`, `trimRight`,\n * `trunc`, `random`, `range`, `sample`, `uniq`, and `words`\n *\n * @static\n * @memberOf _\n * @alias collect\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function|Object|string} [iteratee=_.identity] The function invoked\n * per iteration.\n * create a `_.property` or `_.matches` style callback respectively.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {Array} Returns the new mapped array.\n * @example\n *\n * function timesThree(n) {\n * return n * 3;\n * }\n *\n * _.map([1, 2], timesThree);\n * // => [3, 6]\n *\n * _.map({ 'a': 1, 'b': 2 }, timesThree);\n * // => [3, 6] (iteration order is not guaranteed)\n *\n * var users = [\n * { 'user': 'barney' },\n * { 'user': 'fred' }\n * ];\n *\n * // using the `_.property` callback shorthand\n * _.map(users, 'user');\n * // => ['barney', 'fred']\n */\n function map(collection, iteratee, thisArg) {\n var func = isArray(collection) ? arrayMap : baseMap;\n iteratee = getCallback(iteratee, thisArg, 3);\n return func(collection, iteratee);\n }\n\n /**\n * Gets the maximum value of `collection`. If `collection` is empty or falsey\n * `-Infinity` is returned. If an iteratee function is provided it is invoked\n * for each value in `collection` to generate the criterion by which the value\n * is ranked. The `iteratee` is bound to `thisArg` and invoked with three\n * arguments; (value, index, collection).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function|Object|string} [iteratee] The function invoked per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {*} Returns the maximum value.\n * @example\n *\n * _.max([4, 2, 8, 6]);\n * // => 8\n *\n * _.max([]);\n * // => -Infinity\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 }\n * ];\n *\n * _.max(users, function(chr) {\n * return chr.age;\n * });\n * // => { 'user': 'fred', 'age': 40 };\n *\n * // using the `_.property` callback shorthand\n * _.max(users, 'age');\n * // => { 'user': 'fred', 'age': 40 };\n */\n var max = createExtremum(arrayMax);\n\n /**\n * Gets the minimum value of `collection`. If `collection` is empty or falsey\n * `Infinity` is returned. If an iteratee function is provided it is invoked\n * for each value in `collection` to generate the criterion by which the value\n * is ranked. The `iteratee` is bound to `thisArg` and invoked with three\n * arguments; (value, index, collection).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function|Object|string} [iteratee] The function invoked per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {*} Returns the minimum value.\n * @example\n *\n * _.min([4, 2, 8, 6]);\n * // => 2\n *\n * _.min([]);\n * // => Infinity\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 }\n * ];\n *\n * _.min(users, function(chr) {\n * return chr.age;\n * });\n * // => { 'user': 'barney', 'age': 36 };\n *\n * // using the `_.property` callback shorthand\n * _.min(users, 'age');\n * // => { 'user': 'barney', 'age': 36 };\n */\n var min = createExtremum(arrayMin, true);\n\n /**\n * Creates an array of elements split into two groups, the first of which\n * contains elements `predicate` returns truthy for, while the second of which\n * contains elements `predicate` returns falsey for. The predicate is bound\n * to `thisArg` and invoked with three arguments; (value, index|key, collection).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {Array} Returns the array of grouped elements.\n * @example\n *\n * _.partition([1, 2, 3], function(n) {\n * return n % 2;\n * });\n * // => [[1, 3], [2]]\n *\n * _.partition([1.2, 2.3, 3.4], function(n) {\n * return this.floor(n) % 2;\n * }, Math);\n * // => [[1, 3], [2]]\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true },\n * { 'user': 'pebbles', 'age': 1, 'active': false }\n * ];\n *\n * var mapper = function(array) {\n * return _.pluck(array, 'user');\n * };\n *\n * // using the `_.matches` callback shorthand\n * _.map(_.partition(users, { 'age': 1, 'active': false }), mapper);\n * // => [['pebbles'], ['barney', 'fred']]\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.map(_.partition(users, 'active', false), mapper);\n * // => [['barney', 'pebbles'], ['fred']]\n *\n * // using the `_.property` callback shorthand\n * _.map(_.partition(users, 'active'), mapper);\n * // => [['fred'], ['barney', 'pebbles']]\n */\n var partition = createAggregator(function (result, value, key) {\n result[key ? 0 : 1].push(value);\n }, function () { return [[], []]; });\n\n /**\n * Gets the value of `key` from all elements in `collection`.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {string} key The key of the property to pluck.\n * @returns {Array} Returns the property values.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 }\n * ];\n *\n * _.pluck(users, 'user');\n * // => ['barney', 'fred']\n *\n * var userIndex = _.indexBy(users, 'user');\n * _.pluck(userIndex, 'age');\n * // => [36, 40] (iteration order is not guaranteed)\n */\n function pluck(collection, key) {\n return map(collection, baseProperty(key));\n }\n\n /**\n * Reduces `collection` to a value which is the accumulated result of running\n * each element in `collection` through `iteratee`, where each successive\n * invocation is supplied the return value of the previous. If `accumulator`\n * is not provided the first element of `collection` is used as the initial\n * value. The `iteratee` is bound to `thisArg`and invoked with four arguments;\n * (accumulator, value, index|key, collection).\n *\n * Many lodash methods are guarded to work as interatees for methods like\n * `_.reduce`, `_.reduceRight`, and `_.transform`.\n *\n * The guarded methods are:\n * `assign`, `defaults`, `merge`, and `sortAllBy`\n *\n * @static\n * @memberOf _\n * @alias foldl, inject\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {*} Returns the accumulated value.\n * @example\n *\n * _.reduce([1, 2], function(sum, n) {\n * return sum + n;\n * });\n * // => 3\n *\n * _.reduce({ 'a': 1, 'b': 2 }, function(result, n, key) {\n * result[key] = n * 3;\n * return result;\n * }, {});\n * // => { 'a': 3, 'b': 6 } (iteration order is not guaranteed)\n */\n function reduce(collection, iteratee, accumulator, thisArg) {\n var func = isArray(collection) ? arrayReduce : baseReduce;\n return func(collection, getCallback(iteratee, thisArg, 4), accumulator, arguments.length < 3, baseEach);\n }\n\n /**\n * This method is like `_.reduce` except that it iterates over elements of\n * `collection` from right to left.\n *\n * @static\n * @memberOf _\n * @alias foldr\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The initial value.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {*} Returns the accumulated value.\n * @example\n *\n * var array = [[0, 1], [2, 3], [4, 5]];\n *\n * _.reduceRight(array, function(flattened, other) {\n * return flattened.concat(other);\n * }, []);\n * // => [4, 5, 2, 3, 0, 1]\n */\n function reduceRight(collection, iteratee, accumulator, thisArg) {\n var func = isArray(collection) ? arrayReduceRight : baseReduce;\n return func(collection, getCallback(iteratee, thisArg, 4), accumulator, arguments.length < 3, baseEachRight);\n }\n\n /**\n * The opposite of `_.filter`; this method returns the elements of `collection`\n * that `predicate` does **not** return truthy for.\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {Array} Returns the new filtered array.\n * @example\n *\n * _.reject([1, 2, 3, 4], function(n) {\n * return n % 2 == 0;\n * });\n * // => [1, 3]\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false },\n * { 'user': 'fred', 'age': 40, 'active': true }\n * ];\n *\n * // using the `_.matches` callback shorthand\n * _.pluck(_.reject(users, { 'age': 40, 'active': true }), 'user');\n * // => ['barney']\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.pluck(_.reject(users, 'active', false), 'user');\n * // => ['fred']\n *\n * // using the `_.property` callback shorthand\n * _.pluck(_.reject(users, 'active'), 'user');\n * // => ['barney']\n */\n function reject(collection, predicate, thisArg) {\n var func = isArray(collection) ? arrayFilter : baseFilter;\n predicate = getCallback(predicate, thisArg, 3);\n return func(collection, function (value, index, collection) {\n return !predicate(value, index, collection);\n });\n }\n\n /**\n * Gets a random element or `n` random elements from a collection.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to sample.\n * @param {number} [n] The number of elements to sample.\n * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.\n * @returns {*} Returns the random sample(s).\n * @example\n *\n * _.sample([1, 2, 3, 4]);\n * // => 2\n *\n * _.sample([1, 2, 3, 4], 2);\n * // => [3, 1]\n */\n function sample(collection, n, guard) {\n if (guard ? isIterateeCall(collection, n, guard) : n == null) {\n collection = toIterable(collection);\n var length = collection.length;\n return length > 0 ? collection[baseRandom(0, length - 1)] : undefined;\n }\n var result = shuffle(collection);\n result.length = nativeMin(n < 0 ? 0 : (+n || 0), result.length);\n return result;\n }\n\n /**\n * Creates an array of shuffled values, using a version of the Fisher-Yates\n * shuffle. See [Wikipedia](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to shuffle.\n * @returns {Array} Returns the new shuffled array.\n * @example\n *\n * _.shuffle([1, 2, 3, 4]);\n * // => [4, 1, 3, 2]\n */\n function shuffle(collection) {\n collection = toIterable(collection);\n\n var index = -1,\n length = collection.length,\n result = Array(length);\n\n while (++index < length) {\n var rand = baseRandom(0, index);\n if (index != rand) {\n result[index] = result[rand];\n }\n result[rand] = collection[index];\n }\n return result;\n }\n\n /**\n * Gets the size of `collection` by returning `collection.length` for\n * array-like values or the number of own enumerable properties for objects.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to inspect.\n * @returns {number} Returns the size of `collection`.\n * @example\n *\n * _.size([1, 2, 3]);\n * // => 3\n *\n * _.size({ 'a': 1, 'b': 2 });\n * // => 2\n *\n * _.size('pebbles');\n * // => 7\n */\n function size(collection) {\n var length = collection ? collection.length : 0;\n return isLength(length) ? length : keys(collection).length;\n }\n\n /**\n * Checks if `predicate` returns truthy for **any** element of `collection`.\n * The function returns as soon as it finds a passing value and does not iterate\n * over the entire collection. The predicate is bound to `thisArg` and invoked\n * with three arguments; (value, index|key, collection).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @alias any\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {boolean} Returns `true` if any element passes the predicate check,\n * else `false`.\n * @example\n *\n * _.some([null, 0, 'yes', false], Boolean);\n * // => true\n *\n * var users = [\n * { 'user': 'barney', 'active': true },\n * { 'user': 'fred', 'active': false }\n * ];\n *\n * // using the `_.matches` callback shorthand\n * _.some(users, { 'user': 'barney', 'active': false });\n * // => false\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.some(users, 'active', false);\n * // => true\n *\n * // using the `_.property` callback shorthand\n * _.some(users, 'active');\n * // => true\n */\n function some(collection, predicate, thisArg) {\n var func = isArray(collection) ? arraySome : baseSome;\n if (typeof predicate != 'function' || typeof thisArg != 'undefined') {\n predicate = getCallback(predicate, thisArg, 3);\n }\n return func(collection, predicate);\n }\n\n /**\n * Creates an array of elements, sorted in ascending order by the results of\n * running each element in a collection through `iteratee`. This method performs\n * a stable sort, that is, it preserves the original sort order of equal elements.\n * The `iteratee` is bound to `thisArg` and invoked with three arguments;\n * (value, index|key, collection).\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {Array|Function|Object|string} [iteratee=_.identity] The function\n * invoked per iteration. If a property name or an object is provided it is\n * used to create a `_.property` or `_.matches` style callback respectively.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * _.sortBy([1, 2, 3], function(n) {\n * return Math.sin(n);\n * });\n * // => [3, 1, 2]\n *\n * _.sortBy([1, 2, 3], function(n) {\n * return this.sin(n);\n * }, Math);\n * // => [3, 1, 2]\n *\n * var users = [\n * { 'user': 'fred' },\n * { 'user': 'pebbles' },\n * { 'user': 'barney' }\n * ];\n *\n * // using the `_.property` callback shorthand\n * _.pluck(_.sortBy(users, 'user'), 'user');\n * // => ['barney', 'fred', 'pebbles']\n */\n function sortBy(collection, iteratee, thisArg) {\n var index = -1,\n length = collection ? collection.length : 0,\n result = isLength(length) ? Array(length) : [];\n\n if (thisArg && isIterateeCall(collection, iteratee, thisArg)) {\n iteratee = null;\n }\n iteratee = getCallback(iteratee, thisArg, 3);\n baseEach(collection, function (value, key, collection) {\n result[++index] = { 'criteria': iteratee(value, key, collection), 'index': index, 'value': value };\n });\n return baseSortBy(result, compareAscending);\n }\n\n /**\n * This method is like `_.sortBy` except that it sorts by property names\n * instead of an iteratee function.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to iterate over.\n * @param {...(string|string[])} props The property names to sort by,\n * specified as individual property names or arrays of property names.\n * @returns {Array} Returns the new sorted array.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36 },\n * { 'user': 'fred', 'age': 40 },\n * { 'user': 'barney', 'age': 26 },\n * { 'user': 'fred', 'age': 30 }\n * ];\n *\n * _.map(_.sortByAll(users, ['user', 'age']), _.values);\n * // => [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]]\n */\n function sortByAll(collection) {\n var args = arguments;\n if (args.length > 3 && isIterateeCall(args[1], args[2], args[3])) {\n args = [collection, args[1]];\n }\n var index = -1,\n length = collection ? collection.length : 0,\n props = baseFlatten(args, false, false, 1),\n result = isLength(length) ? Array(length) : [];\n\n baseEach(collection, function (value) {\n var length = props.length,\n criteria = Array(length);\n\n while (length--) {\n criteria[length] = value == null ? undefined : value[props[length]];\n }\n result[++index] = { 'criteria': criteria, 'index': index, 'value': value };\n });\n return baseSortBy(result, compareMultipleAscending);\n }\n\n /**\n * Performs a deep comparison between each element in `collection` and the\n * source object, returning an array of all elements that have equivalent\n * property values.\n *\n * **Note:** This method supports comparing arrays, booleans, `Date` objects,\n * numbers, `Object` objects, regexes, and strings. Objects are compared by\n * their own, not inherited, enumerable properties. For comparing a single\n * own or inherited property value see `_.matchesProperty`.\n *\n * @static\n * @memberOf _\n * @category Collection\n * @param {Array|Object|string} collection The collection to search.\n * @param {Object} source The object of property values to match.\n * @returns {Array} Returns the new filtered array.\n * @example\n *\n * var users = [\n * { 'user': 'barney', 'age': 36, 'active': false, 'pets': ['hoppy'] },\n * { 'user': 'fred', 'age': 40, 'active': true, 'pets': ['baby puss', 'dino'] }\n * ];\n *\n * _.pluck(_.where(users, { 'age': 36, 'active': false }), 'user');\n * // => ['barney']\n *\n * _.pluck(_.where(users, { 'pets': ['dino'] }), 'user');\n * // => ['fred']\n */\n function where(collection, source) {\n return filter(collection, baseMatches(source));\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Gets the number of milliseconds that have elapsed since the Unix epoch\n * (1 January 1970 00:00:00 UTC).\n *\n * @static\n * @memberOf _\n * @category Date\n * @example\n *\n * _.defer(function(stamp) {\n * console.log(_.now() - stamp);\n * }, _.now());\n * // => logs the number of milliseconds it took for the deferred function to be invoked\n */\n var now = nativeNow || function () {\n return new Date().getTime();\n };\n\n /*------------------------------------------------------------------------*/\n\n /**\n * The opposite of `_.before`; this method creates a function that invokes\n * `func` once it is called `n` or more times.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {number} n The number of calls before `func` is invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var saves = ['profile', 'settings'];\n *\n * var done = _.after(saves.length, function() {\n * console.log('done saving!');\n * });\n *\n * _.forEach(saves, function(type) {\n * asyncSave({ 'type': type, 'complete': done });\n * });\n * // => logs 'done saving!' after the two async saves have completed\n */\n function after(n, func) {\n if (typeof func != 'function') {\n if (typeof n == 'function') {\n var temp = n;\n n = func;\n func = temp;\n } else {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n }\n n = nativeIsFinite(n = +n) ? n : 0;\n return function () {\n if (--n < 1) {\n return func.apply(this, arguments);\n }\n };\n }\n\n /**\n * Creates a function that accepts up to `n` arguments ignoring any\n * additional arguments.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to cap arguments for.\n * @param {number} [n=func.length] The arity cap.\n * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.\n * @returns {Function} Returns the new function.\n * @example\n *\n * _.map(['6', '8', '10'], _.ary(parseInt, 1));\n * // => [6, 8, 10]\n */\n function ary(func, n, guard) {\n if (guard && isIterateeCall(func, n, guard)) {\n n = null;\n }\n n = (func && n == null) ? func.length : nativeMax(+n || 0, 0);\n return createWrapper(func, ARY_FLAG, null, null, null, null, n);\n }\n\n /**\n * Creates a function that invokes `func`, with the `this` binding and arguments\n * of the created function, while it is called less than `n` times. Subsequent\n * calls to the created function return the result of the last `func` invocation.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {number} n The number of calls at which `func` is no longer invoked.\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * jQuery('#add').on('click', _.before(5, addContactToList));\n * // => allows adding up to 4 contacts to the list\n */\n function before(n, func) {\n var result;\n if (typeof func != 'function') {\n if (typeof n == 'function') {\n var temp = n;\n n = func;\n func = temp;\n } else {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n }\n return function () {\n if (--n > 0) {\n result = func.apply(this, arguments);\n } else {\n func = null;\n }\n return result;\n };\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of `thisArg`\n * and prepends any additional `_.bind` arguments to those provided to the\n * bound function.\n *\n * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for partially applied arguments.\n *\n * **Note:** Unlike native `Function#bind` this method does not set the `length`\n * property of bound functions.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to bind.\n * @param {*} thisArg The `this` binding of `func`.\n * @param {...*} [args] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * var greet = function(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * };\n *\n * var object = { 'user': 'fred' };\n *\n * var bound = _.bind(greet, object, 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * // using placeholders\n * var bound = _.bind(greet, object, _, '!');\n * bound('hi');\n * // => 'hi fred!'\n */\n function bind(func, thisArg) {\n var bitmask = BIND_FLAG;\n if (arguments.length > 2) {\n var partials = baseSlice(arguments, 2),\n holders = replaceHolders(partials, bind.placeholder);\n\n bitmask |= PARTIAL_FLAG;\n }\n return createWrapper(func, bitmask, thisArg, partials, holders);\n }\n\n /**\n * Binds methods of an object to the object itself, overwriting the existing\n * method. Method names may be specified as individual arguments or as arrays\n * of method names. If no method names are provided all enumerable function\n * properties, own and inherited, of `object` are bound.\n *\n * **Note:** This method does not set the `length` property of bound functions.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Object} object The object to bind and assign the bound methods to.\n * @param {...(string|string[])} [methodNames] The object method names to bind,\n * specified as individual method names or arrays of method names.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var view = {\n * 'label': 'docs',\n * 'onClick': function() {\n * console.log('clicked ' + this.label);\n * }\n * };\n *\n * _.bindAll(view);\n * jQuery('#docs').on('click', view.onClick);\n * // => logs 'clicked docs' when the element is clicked\n */\n function bindAll(object) {\n return baseBindAll(object,\n arguments.length > 1\n ? baseFlatten(arguments, false, false, 1)\n : functions(object)\n );\n }\n\n /**\n * Creates a function that invokes the method at `object[key]` and prepends\n * any additional `_.bindKey` arguments to those provided to the bound function.\n *\n * This method differs from `_.bind` by allowing bound functions to reference\n * methods that may be redefined or don't yet exist.\n * See [Peter Michaux's article](http://michaux.ca/articles/lazy-function-definition-pattern)\n * for more details.\n *\n * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Object} object The object the method belongs to.\n * @param {string} key The key of the method.\n * @param {...*} [args] The arguments to be partially applied.\n * @returns {Function} Returns the new bound function.\n * @example\n *\n * var object = {\n * 'user': 'fred',\n * 'greet': function(greeting, punctuation) {\n * return greeting + ' ' + this.user + punctuation;\n * }\n * };\n *\n * var bound = _.bindKey(object, 'greet', 'hi');\n * bound('!');\n * // => 'hi fred!'\n *\n * object.greet = function(greeting, punctuation) {\n * return greeting + 'ya ' + this.user + punctuation;\n * };\n *\n * bound('!');\n * // => 'hiya fred!'\n *\n * // using placeholders\n * var bound = _.bindKey(object, 'greet', _, '!');\n * bound('hi');\n * // => 'hiya fred!'\n */\n function bindKey(object, key) {\n var bitmask = BIND_FLAG | BIND_KEY_FLAG;\n if (arguments.length > 2) {\n var partials = baseSlice(arguments, 2),\n holders = replaceHolders(partials, bindKey.placeholder);\n\n bitmask |= PARTIAL_FLAG;\n }\n return createWrapper(key, bitmask, object, partials, holders);\n }\n\n /**\n * Creates a function that accepts one or more arguments of `func` that when\n * called either invokes `func` returning its result, if all `func` arguments\n * have been provided, or returns a function that accepts one or more of the\n * remaining `func` arguments, and so on. The arity of `func` may be specified\n * if `func.length` is not sufficient.\n *\n * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,\n * may be used as a placeholder for provided arguments.\n *\n * **Note:** This method does not set the `length` property of curried functions.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curry(abc);\n *\n * curried(1)(2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2)(3);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // using placeholders\n * curried(1)(_, 3)(2);\n * // => [1, 2, 3]\n */\n function curry(func, arity, guard) {\n if (guard && isIterateeCall(func, arity, guard)) {\n arity = null;\n }\n var result = createWrapper(func, CURRY_FLAG, null, null, null, null, null, arity);\n result.placeholder = curry.placeholder;\n return result;\n }\n\n /**\n * This method is like `_.curry` except that arguments are applied to `func`\n * in the manner of `_.partialRight` instead of `_.partial`.\n *\n * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for provided arguments.\n *\n * **Note:** This method does not set the `length` property of curried functions.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to curry.\n * @param {number} [arity=func.length] The arity of `func`.\n * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.\n * @returns {Function} Returns the new curried function.\n * @example\n *\n * var abc = function(a, b, c) {\n * return [a, b, c];\n * };\n *\n * var curried = _.curryRight(abc);\n *\n * curried(3)(2)(1);\n * // => [1, 2, 3]\n *\n * curried(2, 3)(1);\n * // => [1, 2, 3]\n *\n * curried(1, 2, 3);\n * // => [1, 2, 3]\n *\n * // using placeholders\n * curried(3)(1, _)(2);\n * // => [1, 2, 3]\n */\n function curryRight(func, arity, guard) {\n if (guard && isIterateeCall(func, arity, guard)) {\n arity = null;\n }\n var result = createWrapper(func, CURRY_RIGHT_FLAG, null, null, null, null, null, arity);\n result.placeholder = curryRight.placeholder;\n return result;\n }\n\n /**\n * Creates a function that delays invoking `func` until after `wait` milliseconds\n * have elapsed since the last time it was invoked. The created function comes\n * with a `cancel` method to cancel delayed invocations. Provide an options\n * object to indicate that `func` should be invoked on the leading and/or\n * trailing edge of the `wait` timeout. Subsequent calls to the debounced\n * function return the result of the last `func` invocation.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked\n * on the trailing edge of the timeout only if the the debounced function is\n * invoked more than once during the `wait` timeout.\n *\n * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)\n * for details over the differences between `_.debounce` and `_.throttle`.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to debounce.\n * @param {number} [wait=0] The number of milliseconds to delay.\n * @param {Object} [options] The options object.\n * @param {boolean} [options.leading=false] Specify invoking on the leading\n * edge of the timeout.\n * @param {number} [options.maxWait] The maximum time `func` is allowed to be\n * delayed before it is invoked.\n * @param {boolean} [options.trailing=true] Specify invoking on the trailing\n * edge of the timeout.\n * @returns {Function} Returns the new debounced function.\n * @example\n *\n * // avoid costly calculations while the window size is in flux\n * jQuery(window).on('resize', _.debounce(calculateLayout, 150));\n *\n * // invoke `sendMail` when the click event is fired, debouncing subsequent calls\n * jQuery('#postbox').on('click', _.debounce(sendMail, 300, {\n * 'leading': true,\n * 'trailing': false\n * }));\n *\n * // ensure `batchLog` is invoked once after 1 second of debounced calls\n * var source = new EventSource('/stream');\n * jQuery(source).on('message', _.debounce(batchLog, 250, {\n * 'maxWait': 1000\n * }));\n *\n * // cancel a debounced call\n * var todoChanges = _.debounce(batchLog, 1000);\n * Object.observe(models.todo, todoChanges);\n *\n * Object.observe(models, function(changes) {\n * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) {\n * todoChanges.cancel();\n * }\n * }, ['delete']);\n *\n * // ...at some point `models.todo` is changed\n * models.todo.completed = true;\n *\n * // ...before 1 second has passed `models.todo` is deleted\n * // which cancels the debounced `todoChanges` call\n * delete models.todo;\n */\n function debounce(func, wait, options) {\n var args,\n maxTimeoutId,\n result,\n stamp,\n thisArg,\n timeoutId,\n trailingCall,\n lastCalled = 0,\n maxWait = false,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n wait = wait < 0 ? 0 : (+wait || 0);\n if (options === true) {\n var leading = true;\n trailing = false;\n } else if (isObject(options)) {\n leading = options.leading;\n maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait);\n trailing = 'trailing' in options ? options.trailing : trailing;\n }\n\n function cancel() {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n if (maxTimeoutId) {\n clearTimeout(maxTimeoutId);\n }\n maxTimeoutId = timeoutId = trailingCall = undefined;\n }\n\n function delayed() {\n var remaining = wait - (now() - stamp);\n if (remaining <= 0 || remaining > wait) {\n if (maxTimeoutId) {\n clearTimeout(maxTimeoutId);\n }\n var isCalled = trailingCall;\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (isCalled) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n if (!timeoutId && !maxTimeoutId) {\n args = thisArg = null;\n }\n }\n } else {\n timeoutId = setTimeout(delayed, remaining);\n }\n }\n\n function maxDelayed() {\n if (timeoutId) {\n clearTimeout(timeoutId);\n }\n maxTimeoutId = timeoutId = trailingCall = undefined;\n if (trailing || (maxWait !== wait)) {\n lastCalled = now();\n result = func.apply(thisArg, args);\n if (!timeoutId && !maxTimeoutId) {\n args = thisArg = null;\n }\n }\n }\n\n function debounced() {\n args = arguments;\n stamp = now();\n thisArg = this;\n trailingCall = trailing && (timeoutId || !leading);\n\n if (maxWait === false) {\n var leadingCall = leading && !timeoutId;\n } else {\n if (!maxTimeoutId && !leading) {\n lastCalled = stamp;\n }\n var remaining = maxWait - (stamp - lastCalled),\n isCalled = remaining <= 0 || remaining > maxWait;\n\n if (isCalled) {\n if (maxTimeoutId) {\n maxTimeoutId = clearTimeout(maxTimeoutId);\n }\n lastCalled = stamp;\n result = func.apply(thisArg, args);\n }\n else if (!maxTimeoutId) {\n maxTimeoutId = setTimeout(maxDelayed, remaining);\n }\n }\n if (isCalled && timeoutId) {\n timeoutId = clearTimeout(timeoutId);\n }\n else if (!timeoutId && wait !== maxWait) {\n timeoutId = setTimeout(delayed, wait);\n }\n if (leadingCall) {\n isCalled = true;\n result = func.apply(thisArg, args);\n }\n if (isCalled && !timeoutId && !maxTimeoutId) {\n args = thisArg = null;\n }\n return result;\n }\n debounced.cancel = cancel;\n return debounced;\n }\n\n /**\n * Defers invoking the `func` until the current call stack has cleared. Any\n * additional arguments are provided to `func` when it is invoked.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to defer.\n * @param {...*} [args] The arguments to invoke the function with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.defer(function(text) {\n * console.log(text);\n * }, 'deferred');\n * // logs 'deferred' after one or more milliseconds\n */\n function defer(func) {\n return baseDelay(func, 1, arguments, 1);\n }\n\n /**\n * Invokes `func` after `wait` milliseconds. Any additional arguments are\n * provided to `func` when it is invoked.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to delay.\n * @param {number} wait The number of milliseconds to delay invocation.\n * @param {...*} [args] The arguments to invoke the function with.\n * @returns {number} Returns the timer id.\n * @example\n *\n * _.delay(function(text) {\n * console.log(text);\n * }, 1000, 'later');\n * // => logs 'later' after one second\n */\n function delay(func, wait) {\n return baseDelay(func, wait, arguments, 2);\n }\n\n /**\n * Creates a function that returns the result of invoking the provided\n * functions with the `this` binding of the created function, where each\n * successive invocation is supplied the return value of the previous.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {...Function} [funcs] Functions to invoke.\n * @returns {Function} Returns the new function.\n * @example\n *\n * function add(x, y) {\n * return x + y;\n * }\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var addSquare = _.flow(add, square);\n * addSquare(1, 2);\n * // => 9\n */\n function flow() {\n var funcs = arguments,\n length = funcs.length;\n\n if (!length) {\n return function () { return arguments[0]; };\n }\n if (!arrayEvery(funcs, baseIsFunction)) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function () {\n var index = 0,\n result = funcs[index].apply(this, arguments);\n\n while (++index < length) {\n result = funcs[index].call(this, result);\n }\n return result;\n };\n }\n\n /**\n * This method is like `_.flow` except that it creates a function that\n * invokes the provided functions from right to left.\n *\n * @static\n * @memberOf _\n * @alias backflow, compose\n * @category Function\n * @param {...Function} [funcs] Functions to invoke.\n * @returns {Function} Returns the new function.\n * @example\n *\n * function add(x, y) {\n * return x + y;\n * }\n *\n * function square(n) {\n * return n * n;\n * }\n *\n * var addSquare = _.flowRight(square, add);\n * addSquare(1, 2);\n * // => 9\n */\n function flowRight() {\n var funcs = arguments,\n fromIndex = funcs.length - 1;\n\n if (fromIndex < 0) {\n return function () { return arguments[0]; };\n }\n if (!arrayEvery(funcs, baseIsFunction)) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function () {\n var index = fromIndex,\n result = funcs[index].apply(this, arguments);\n\n while (index--) {\n result = funcs[index].call(this, result);\n }\n return result;\n };\n }\n\n /**\n * Creates a function that memoizes the result of `func`. If `resolver` is\n * provided it determines the cache key for storing the result based on the\n * arguments provided to the memoized function. By default, the first argument\n * provided to the memoized function is coerced to a string and used as the\n * cache key. The `func` is invoked with the `this` binding of the memoized\n * function.\n *\n * **Note:** The cache is exposed as the `cache` property on the memoized\n * function. Its creation may be customized by replacing the `_.memoize.Cache`\n * constructor with one whose instances implement the ES `Map` method interface\n * of `get`, `has`, and `set`. See the\n * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-properties-of-the-map-prototype-object)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to have its output memoized.\n * @param {Function} [resolver] The function to resolve the cache key.\n * @returns {Function} Returns the new memoizing function.\n * @example\n *\n * var upperCase = _.memoize(function(string) {\n * return string.toUpperCase();\n * });\n *\n * upperCase('fred');\n * // => 'FRED'\n *\n * // modifying the result cache\n * upperCase.cache.set('fred', 'BARNEY');\n * upperCase('fred');\n * // => 'BARNEY'\n *\n * // replacing `_.memoize.Cache`\n * var object = { 'user': 'fred' };\n * var other = { 'user': 'barney' };\n * var identity = _.memoize(_.identity);\n *\n * identity(object);\n * // => { 'user': 'fred' }\n * identity(other);\n * // => { 'user': 'fred' }\n *\n * _.memoize.Cache = WeakMap;\n * var identity = _.memoize(_.identity);\n *\n * identity(object);\n * // => { 'user': 'fred' }\n * identity(other);\n * // => { 'user': 'barney' }\n */\n function memoize(func, resolver) {\n if (typeof func != 'function' || (resolver && typeof resolver != 'function')) {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n var memoized = function () {\n var cache = memoized.cache,\n key = resolver ? resolver.apply(this, arguments) : arguments[0];\n\n if (cache.has(key)) {\n return cache.get(key);\n }\n var result = func.apply(this, arguments);\n cache.set(key, result);\n return result;\n };\n memoized.cache = new memoize.Cache;\n return memoized;\n }\n\n /**\n * Creates a function that negates the result of the predicate `func`. The\n * `func` predicate is invoked with the `this` binding and arguments of the\n * created function.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} predicate The predicate to negate.\n * @returns {Function} Returns the new function.\n * @example\n *\n * function isEven(n) {\n * return n % 2 == 0;\n * }\n *\n * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));\n * // => [1, 3, 5]\n */\n function negate(predicate) {\n if (typeof predicate != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function () {\n return !predicate.apply(this, arguments);\n };\n }\n\n /**\n * Creates a function that is restricted to invoking `func` once. Repeat calls\n * to the function return the value of the first call. The `func` is invoked\n * with the `this` binding of the created function.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to restrict.\n * @returns {Function} Returns the new restricted function.\n * @example\n *\n * var initialize = _.once(createApplication);\n * initialize();\n * initialize();\n * // `initialize` invokes `createApplication` once\n */\n function once(func) {\n return before(func, 2);\n }\n\n /**\n * Creates a function that invokes `func` with `partial` arguments prepended\n * to those provided to the new function. This method is like `_.bind` except\n * it does **not** alter the `this` binding.\n *\n * The `_.partial.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method does not set the `length` property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [args] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * var greet = function(greeting, name) {\n * return greeting + ' ' + name;\n * };\n *\n * var sayHelloTo = _.partial(greet, 'hello');\n * sayHelloTo('fred');\n * // => 'hello fred'\n *\n * // using placeholders\n * var greetFred = _.partial(greet, _, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n */\n function partial(func) {\n var partials = baseSlice(arguments, 1),\n holders = replaceHolders(partials, partial.placeholder);\n\n return createWrapper(func, PARTIAL_FLAG, null, partials, holders);\n }\n\n /**\n * This method is like `_.partial` except that partially applied arguments\n * are appended to those provided to the new function.\n *\n * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic\n * builds, may be used as a placeholder for partially applied arguments.\n *\n * **Note:** This method does not set the `length` property of partially\n * applied functions.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to partially apply arguments to.\n * @param {...*} [args] The arguments to be partially applied.\n * @returns {Function} Returns the new partially applied function.\n * @example\n *\n * var greet = function(greeting, name) {\n * return greeting + ' ' + name;\n * };\n *\n * var greetFred = _.partialRight(greet, 'fred');\n * greetFred('hi');\n * // => 'hi fred'\n *\n * // using placeholders\n * var sayHelloTo = _.partialRight(greet, 'hello', _);\n * sayHelloTo('fred');\n * // => 'hello fred'\n */\n function partialRight(func) {\n var partials = baseSlice(arguments, 1),\n holders = replaceHolders(partials, partialRight.placeholder);\n\n return createWrapper(func, PARTIAL_RIGHT_FLAG, null, partials, holders);\n }\n\n /**\n * Creates a function that invokes `func` with arguments arranged according\n * to the specified indexes where the argument value at the first index is\n * provided as the first argument, the argument value at the second index is\n * provided as the second argument, and so on.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to rearrange arguments for.\n * @param {...(number|number[])} indexes The arranged argument indexes,\n * specified as individual indexes or arrays of indexes.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var rearged = _.rearg(function(a, b, c) {\n * return [a, b, c];\n * }, 2, 0, 1);\n *\n * rearged('b', 'c', 'a')\n * // => ['a', 'b', 'c']\n *\n * var map = _.rearg(_.map, [1, 0]);\n * map(function(n) {\n * return n * 3;\n * }, [1, 2, 3]);\n * // => [3, 6, 9]\n */\n function rearg(func) {\n var indexes = baseFlatten(arguments, false, false, 1);\n return createWrapper(func, REARG_FLAG, null, null, null, indexes);\n }\n\n /**\n * Creates a function that invokes `func` with the `this` binding of the\n * created function and the array of arguments provided to the created\n * function much like [Function#apply](http://es5.github.io/#x15.3.4.3).\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to spread arguments over.\n * @returns {*} Returns the new function.\n * @example\n *\n * var spread = _.spread(function(who, what) {\n * return who + ' says ' + what;\n * });\n *\n * spread(['Fred', 'hello']);\n * // => 'Fred says hello'\n *\n * // with a Promise\n * var numbers = Promise.all([\n * Promise.resolve(40),\n * Promise.resolve(36)\n * ]);\n *\n * numbers.then(_.spread(function(x, y) {\n * return x + y;\n * }));\n * // => a Promise of 76\n */\n function spread(func) {\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n return function (array) {\n return func.apply(this, array);\n };\n }\n\n /**\n * Creates a function that only invokes `func` at most once per every `wait`\n * milliseconds. The created function comes with a `cancel` method to cancel\n * delayed invocations. Provide an options object to indicate that `func`\n * should be invoked on the leading and/or trailing edge of the `wait` timeout.\n * Subsequent calls to the throttled function return the result of the last\n * `func` call.\n *\n * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked\n * on the trailing edge of the timeout only if the the throttled function is\n * invoked more than once during the `wait` timeout.\n *\n * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation)\n * for details over the differences between `_.throttle` and `_.debounce`.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {Function} func The function to throttle.\n * @param {number} [wait=0] The number of milliseconds to throttle invocations to.\n * @param {Object} [options] The options object.\n * @param {boolean} [options.leading=true] Specify invoking on the leading\n * edge of the timeout.\n * @param {boolean} [options.trailing=true] Specify invoking on the trailing\n * edge of the timeout.\n * @returns {Function} Returns the new throttled function.\n * @example\n *\n * // avoid excessively updating the position while scrolling\n * jQuery(window).on('scroll', _.throttle(updatePosition, 100));\n *\n * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes\n * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, {\n * 'trailing': false\n * }));\n *\n * // cancel a trailing throttled call\n * jQuery(window).on('popstate', throttled.cancel);\n */\n function throttle(func, wait, options) {\n var leading = true,\n trailing = true;\n\n if (typeof func != 'function') {\n throw new TypeError(FUNC_ERROR_TEXT);\n }\n if (options === false) {\n leading = false;\n } else if (isObject(options)) {\n leading = 'leading' in options ? !!options.leading : leading;\n trailing = 'trailing' in options ? !!options.trailing : trailing;\n }\n debounceOptions.leading = leading;\n debounceOptions.maxWait = +wait;\n debounceOptions.trailing = trailing;\n return debounce(func, wait, debounceOptions);\n }\n\n /**\n * Creates a function that provides `value` to the wrapper function as its\n * first argument. Any additional arguments provided to the function are\n * appended to those provided to the wrapper function. The wrapper is invoked\n * with the `this` binding of the created function.\n *\n * @static\n * @memberOf _\n * @category Function\n * @param {*} value The value to wrap.\n * @param {Function} wrapper The wrapper function.\n * @returns {Function} Returns the new function.\n * @example\n *\n * var p = _.wrap(_.escape, function(func, text) {\n * return '

      ' + func(text) + '

      ';\n * });\n *\n * p('fred, barney, & pebbles');\n * // => '

      fred, barney, & pebbles

      '\n */\n function wrap(value, wrapper) {\n wrapper = wrapper == null ? identity : wrapper;\n return createWrapper(wrapper, PARTIAL_FLAG, null, [value], []);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Creates a clone of `value`. If `isDeep` is `true` nested objects are cloned,\n * otherwise they are assigned by reference. If `customizer` is provided it is\n * invoked to produce the cloned values. If `customizer` returns `undefined`\n * cloning is handled by the method instead. The `customizer` is bound to\n * `thisArg` and invoked with two argument; (value [, index|key, object]).\n *\n * **Note:** This method is loosely based on the structured clone algorithm.\n * The enumerable properties of `arguments` objects and objects created by\n * constructors other than `Object` are cloned to plain `Object` objects. An\n * empty object is returned for uncloneable values such as functions, DOM nodes,\n * Maps, Sets, and WeakMaps. See the [HTML5 specification](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to clone.\n * @param {boolean} [isDeep] Specify a deep clone.\n * @param {Function} [customizer] The function to customize cloning values.\n * @param {*} [thisArg] The `this` binding of `customizer`.\n * @returns {*} Returns the cloned value.\n * @example\n *\n * var users = [\n * { 'user': 'barney' },\n * { 'user': 'fred' }\n * ];\n *\n * var shallow = _.clone(users);\n * shallow[0] === users[0];\n * // => true\n *\n * var deep = _.clone(users, true);\n * deep[0] === users[0];\n * // => false\n *\n * // using a customizer callback\n * var el = _.clone(document.body, function(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(false);\n * }\n * });\n *\n * el === document.body\n * // => false\n * el.nodeName\n * // => BODY\n * el.childNodes.length;\n * // => 0\n */\n function clone(value, isDeep, customizer, thisArg) {\n if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) {\n isDeep = false;\n }\n else if (typeof isDeep == 'function') {\n thisArg = customizer;\n customizer = isDeep;\n isDeep = false;\n }\n customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 1);\n return baseClone(value, isDeep, customizer);\n }\n\n /**\n * Creates a deep clone of `value`. If `customizer` is provided it is invoked\n * to produce the cloned values. If `customizer` returns `undefined` cloning\n * is handled by the method instead. The `customizer` is bound to `thisArg`\n * and invoked with two argument; (value [, index|key, object]).\n *\n * **Note:** This method is loosely based on the structured clone algorithm.\n * The enumerable properties of `arguments` objects and objects created by\n * constructors other than `Object` are cloned to plain `Object` objects. An\n * empty object is returned for uncloneable values such as functions, DOM nodes,\n * Maps, Sets, and WeakMaps. See the [HTML5 specification](http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to deep clone.\n * @param {Function} [customizer] The function to customize cloning values.\n * @param {*} [thisArg] The `this` binding of `customizer`.\n * @returns {*} Returns the deep cloned value.\n * @example\n *\n * var users = [\n * { 'user': 'barney' },\n * { 'user': 'fred' }\n * ];\n *\n * var deep = _.cloneDeep(users);\n * deep[0] === users[0];\n * // => false\n *\n * // using a customizer callback\n * var el = _.cloneDeep(document.body, function(value) {\n * if (_.isElement(value)) {\n * return value.cloneNode(true);\n * }\n * });\n *\n * el === document.body\n * // => false\n * el.nodeName\n * // => BODY\n * el.childNodes.length;\n * // => 20\n */\n function cloneDeep(value, customizer, thisArg) {\n customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 1);\n return baseClone(value, true, customizer);\n }\n\n /**\n * Checks if `value` is classified as an `arguments` object.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isArguments(function() { return arguments; }());\n * // => true\n *\n * _.isArguments([1, 2, 3]);\n * // => false\n */\n function isArguments(value) {\n var length = isObjectLike(value) ? value.length : undefined;\n return (isLength(length) && objToString.call(value) == argsTag) || false;\n }\n\n /**\n * Checks if `value` is classified as an `Array` object.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isArray([1, 2, 3]);\n * // => true\n *\n * _.isArray(function() { return arguments; }());\n * // => false\n */\n var isArray = nativeIsArray || function (value) {\n return (isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag) || false;\n };\n\n /**\n * Checks if `value` is classified as a boolean primitive or object.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isBoolean(false);\n * // => true\n *\n * _.isBoolean(null);\n * // => false\n */\n function isBoolean(value) {\n return (value === true || value === false || isObjectLike(value) && objToString.call(value) == boolTag) || false;\n }\n\n /**\n * Checks if `value` is classified as a `Date` object.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isDate(new Date);\n * // => true\n *\n * _.isDate('Mon April 23 2012');\n * // => false\n */\n function isDate(value) {\n return (isObjectLike(value) && objToString.call(value) == dateTag) || false;\n }\n\n /**\n * Checks if `value` is a DOM element.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.\n * @example\n *\n * _.isElement(document.body);\n * // => true\n *\n * _.isElement('');\n * // => false\n */\n function isElement(value) {\n return (value && value.nodeType === 1 && isObjectLike(value) &&\n objToString.call(value).indexOf('Element') > -1) || false;\n }\n // Fallback for environments without DOM support.\n if (!support.dom) {\n isElement = function (value) {\n return (value && value.nodeType === 1 && isObjectLike(value) && !isPlainObject(value)) || false;\n };\n }\n\n /**\n * Checks if a value is empty. A value is considered empty unless it is an\n * `arguments` object, array, string, or jQuery-like collection with a length\n * greater than `0` or an object with own enumerable properties.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {Array|Object|string} value The value to inspect.\n * @returns {boolean} Returns `true` if `value` is empty, else `false`.\n * @example\n *\n * _.isEmpty(null);\n * // => true\n *\n * _.isEmpty(true);\n * // => true\n *\n * _.isEmpty(1);\n * // => true\n *\n * _.isEmpty([1, 2, 3]);\n * // => false\n *\n * _.isEmpty({ 'a': 1 });\n * // => false\n */\n function isEmpty(value) {\n if (value == null) {\n return true;\n }\n var length = value.length;\n if (isLength(length) && (isArray(value) || isString(value) || isArguments(value) ||\n (isObjectLike(value) && isFunction(value.splice)))) {\n return !length;\n }\n return !keys(value).length;\n }\n\n /**\n * Performs a deep comparison between two values to determine if they are\n * equivalent. If `customizer` is provided it is invoked to compare values.\n * If `customizer` returns `undefined` comparisons are handled by the method\n * instead. The `customizer` is bound to `thisArg` and invoked with three\n * arguments; (value, other [, index|key]).\n *\n * **Note:** This method supports comparing arrays, booleans, `Date` objects,\n * numbers, `Object` objects, regexes, and strings. Objects are compared by\n * their own, not inherited, enumerable properties. Functions and DOM nodes\n * are **not** supported. Provide a customizer function to extend support\n * for comparing other values.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to compare.\n * @param {*} other The other value to compare.\n * @param {Function} [customizer] The function to customize comparing values.\n * @param {*} [thisArg] The `this` binding of `customizer`.\n * @returns {boolean} Returns `true` if the values are equivalent, else `false`.\n * @example\n *\n * var object = { 'user': 'fred' };\n * var other = { 'user': 'fred' };\n *\n * object == other;\n * // => false\n *\n * _.isEqual(object, other);\n * // => true\n *\n * // using a customizer callback\n * var array = ['hello', 'goodbye'];\n * var other = ['hi', 'goodbye'];\n *\n * _.isEqual(array, other, function(value, other) {\n * if (_.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/)) {\n * return true;\n * }\n * });\n * // => true\n */\n function isEqual(value, other, customizer, thisArg) {\n customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3);\n if (!customizer && isStrictComparable(value) && isStrictComparable(other)) {\n return value === other;\n }\n var result = customizer ? customizer(value, other) : undefined;\n return typeof result == 'undefined' ? baseIsEqual(value, other, customizer) : !!result;\n }\n\n /**\n * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,\n * `SyntaxError`, `TypeError`, or `URIError` object.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an error object, else `false`.\n * @example\n *\n * _.isError(new Error);\n * // => true\n *\n * _.isError(Error);\n * // => false\n */\n function isError(value) {\n return (isObjectLike(value) && typeof value.message == 'string' && objToString.call(value) == errorTag) || false;\n }\n\n /**\n * Checks if `value` is a finite primitive number.\n *\n * **Note:** This method is based on ES `Number.isFinite`. See the\n * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-number.isfinite)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.\n * @example\n *\n * _.isFinite(10);\n * // => true\n *\n * _.isFinite('10');\n * // => false\n *\n * _.isFinite(true);\n * // => false\n *\n * _.isFinite(Object(10));\n * // => false\n *\n * _.isFinite(Infinity);\n * // => false\n */\n var isFinite = nativeNumIsFinite || function (value) {\n return typeof value == 'number' && nativeIsFinite(value);\n };\n\n /**\n * Checks if `value` is classified as a `Function` object.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isFunction(_);\n * // => true\n *\n * _.isFunction(/abc/);\n * // => false\n */\n var isFunction = !(baseIsFunction(/x/) || (Uint8Array && !baseIsFunction(Uint8Array))) ? baseIsFunction : function (value) {\n // The use of `Object#toString` avoids issues with the `typeof` operator\n // in older versions of Chrome and Safari which return 'function' for regexes\n // and Safari 8 equivalents which return 'object' for typed array constructors.\n return objToString.call(value) == funcTag;\n };\n\n /**\n * Checks if `value` is the language type of `Object`.\n * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)\n *\n * **Note:** See the [ES5 spec](https://es5.github.io/#x8) for more details.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is an object, else `false`.\n * @example\n *\n * _.isObject({});\n * // => true\n *\n * _.isObject([1, 2, 3]);\n * // => true\n *\n * _.isObject(1);\n * // => false\n */\n function isObject(value) {\n // Avoid a V8 JIT bug in Chrome 19-20.\n // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.\n var type = typeof value;\n return type == 'function' || (value && type == 'object') || false;\n }\n\n /**\n * Performs a deep comparison between `object` and `source` to determine if\n * `object` contains equivalent property values. If `customizer` is provided\n * it is invoked to compare values. If `customizer` returns `undefined`\n * comparisons are handled by the method instead. The `customizer` is bound\n * to `thisArg` and invoked with three arguments; (value, other, index|key).\n *\n * **Note:** This method supports comparing properties of arrays, booleans,\n * `Date` objects, numbers, `Object` objects, regexes, and strings. Functions\n * and DOM nodes are **not** supported. Provide a customizer function to extend\n * support for comparing other values.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {Object} object The object to inspect.\n * @param {Object} source The object of property values to match.\n * @param {Function} [customizer] The function to customize comparing values.\n * @param {*} [thisArg] The `this` binding of `customizer`.\n * @returns {boolean} Returns `true` if `object` is a match, else `false`.\n * @example\n *\n * var object = { 'user': 'fred', 'age': 40 };\n *\n * _.isMatch(object, { 'age': 40 });\n * // => true\n *\n * _.isMatch(object, { 'age': 36 });\n * // => false\n *\n * // using a customizer callback\n * var object = { 'greeting': 'hello' };\n * var source = { 'greeting': 'hi' };\n *\n * _.isMatch(object, source, function(value, other) {\n * return _.every([value, other], RegExp.prototype.test, /^h(?:i|ello)$/) || undefined;\n * });\n * // => true\n */\n function isMatch(object, source, customizer, thisArg) {\n var props = keys(source),\n length = props.length;\n\n customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 3);\n if (!customizer && length == 1) {\n var key = props[0],\n value = source[key];\n\n if (isStrictComparable(value)) {\n return object != null && value === object[key] && hasOwnProperty.call(object, key);\n }\n }\n var values = Array(length),\n strictCompareFlags = Array(length);\n\n while (length--) {\n value = values[length] = source[props[length]];\n strictCompareFlags[length] = isStrictComparable(value);\n }\n return baseIsMatch(object, props, values, strictCompareFlags, customizer);\n }\n\n /**\n * Checks if `value` is `NaN`.\n *\n * **Note:** This method is not the same as native `isNaN` which returns `true`\n * for `undefined` and other non-numeric values. See the [ES5 spec](https://es5.github.io/#x15.1.2.4)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.\n * @example\n *\n * _.isNaN(NaN);\n * // => true\n *\n * _.isNaN(new Number(NaN));\n * // => true\n *\n * isNaN(undefined);\n * // => true\n *\n * _.isNaN(undefined);\n * // => false\n */\n function isNaN(value) {\n // An `NaN` primitive is the only value that is not equal to itself.\n // Perform the `toStringTag` check first to avoid errors with some host objects in IE.\n return isNumber(value) && value != +value;\n }\n\n /**\n * Checks if `value` is a native function.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a native function, else `false`.\n * @example\n *\n * _.isNative(Array.prototype.push);\n * // => true\n *\n * _.isNative(_);\n * // => false\n */\n function isNative(value) {\n if (value == null) {\n return false;\n }\n if (objToString.call(value) == funcTag) {\n return reNative.test(fnToString.call(value));\n }\n return (isObjectLike(value) && reHostCtor.test(value)) || false;\n }\n\n /**\n * Checks if `value` is `null`.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `null`, else `false`.\n * @example\n *\n * _.isNull(null);\n * // => true\n *\n * _.isNull(void 0);\n * // => false\n */\n function isNull(value) {\n return value === null;\n }\n\n /**\n * Checks if `value` is classified as a `Number` primitive or object.\n *\n * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified\n * as numbers, use the `_.isFinite` method.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isNumber(8.4);\n * // => true\n *\n * _.isNumber(NaN);\n * // => true\n *\n * _.isNumber('8.4');\n * // => false\n */\n function isNumber(value) {\n return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag) || false;\n }\n\n /**\n * Checks if `value` is a plain object, that is, an object created by the\n * `Object` constructor or one with a `[[Prototype]]` of `null`.\n *\n * **Note:** This method assumes objects created by the `Object` constructor\n * have no inherited enumerable properties.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * }\n *\n * _.isPlainObject(new Foo);\n * // => false\n *\n * _.isPlainObject([1, 2, 3]);\n * // => false\n *\n * _.isPlainObject({ 'x': 0, 'y': 0 });\n * // => true\n *\n * _.isPlainObject(Object.create(null));\n * // => true\n */\n var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function (value) {\n if (!(value && objToString.call(value) == objectTag)) {\n return false;\n }\n var valueOf = value.valueOf,\n objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto);\n\n return objProto\n ? (value == objProto || getPrototypeOf(value) == objProto)\n : shimIsPlainObject(value);\n };\n\n /**\n * Checks if `value` is classified as a `RegExp` object.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isRegExp(/abc/);\n * // => true\n *\n * _.isRegExp('/abc/');\n * // => false\n */\n function isRegExp(value) {\n return (isObjectLike(value) && objToString.call(value) == regexpTag) || false;\n }\n\n /**\n * Checks if `value` is classified as a `String` primitive or object.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isString('abc');\n * // => true\n *\n * _.isString(1);\n * // => false\n */\n function isString(value) {\n return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag) || false;\n }\n\n /**\n * Checks if `value` is classified as a typed array.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.\n * @example\n *\n * _.isTypedArray(new Uint8Array);\n * // => true\n *\n * _.isTypedArray([]);\n * // => false\n */\n function isTypedArray(value) {\n return (isObjectLike(value) && isLength(value.length) && typedArrayTags[objToString.call(value)]) || false;\n }\n\n /**\n * Checks if `value` is `undefined`.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to check.\n * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.\n * @example\n *\n * _.isUndefined(void 0);\n * // => true\n *\n * _.isUndefined(null);\n * // => false\n */\n function isUndefined(value) {\n return typeof value == 'undefined';\n }\n\n /**\n * Converts `value` to an array.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Array} Returns the converted array.\n * @example\n *\n * (function() {\n * return _.toArray(arguments).slice(1);\n * }(1, 2, 3));\n * // => [2, 3]\n */\n function toArray(value) {\n var length = value ? value.length : 0;\n if (!isLength(length)) {\n return values(value);\n }\n if (!length) {\n return [];\n }\n return arrayCopy(value);\n }\n\n /**\n * Converts `value` to a plain object flattening inherited enumerable\n * properties of `value` to own properties of the plain object.\n *\n * @static\n * @memberOf _\n * @category Lang\n * @param {*} value The value to convert.\n * @returns {Object} Returns the converted plain object.\n * @example\n *\n * function Foo() {\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.assign({ 'a': 1 }, new Foo);\n * // => { 'a': 1, 'b': 2 }\n *\n * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));\n * // => { 'a': 1, 'b': 2, 'c': 3 }\n */\n function toPlainObject(value) {\n return baseCopy(value, keysIn(value));\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Assigns own enumerable properties of source object(s) to the destination\n * object. Subsequent sources overwrite property assignments of previous sources.\n * If `customizer` is provided it is invoked to produce the assigned values.\n * The `customizer` is bound to `thisArg` and invoked with five arguments;\n * (objectValue, sourceValue, key, object, source).\n *\n * @static\n * @memberOf _\n * @alias extend\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @param {Function} [customizer] The function to customize assigning values.\n * @param {*} [thisArg] The `this` binding of `customizer`.\n * @returns {Object} Returns `object`.\n * @example\n *\n * _.assign({ 'user': 'barney' }, { 'age': 40 }, { 'user': 'fred' });\n * // => { 'user': 'fred', 'age': 40 }\n *\n * // using a customizer callback\n * var defaults = _.partialRight(_.assign, function(value, other) {\n * return typeof value == 'undefined' ? other : value;\n * });\n *\n * defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });\n * // => { 'user': 'barney', 'age': 36 }\n */\n var assign = createAssigner(baseAssign);\n\n /**\n * Creates an object that inherits from the given `prototype` object. If a\n * `properties` object is provided its own enumerable properties are assigned\n * to the created object.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} prototype The object to inherit from.\n * @param {Object} [properties] The properties to assign to the object.\n * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.\n * @returns {Object} Returns the new object.\n * @example\n *\n * function Shape() {\n * this.x = 0;\n * this.y = 0;\n * }\n *\n * function Circle() {\n * Shape.call(this);\n * }\n *\n * Circle.prototype = _.create(Shape.prototype, {\n * 'constructor': Circle\n * });\n *\n * var circle = new Circle;\n * circle instanceof Circle;\n * // => true\n *\n * circle instanceof Shape;\n * // => true\n */\n function create(prototype, properties, guard) {\n var result = baseCreate(prototype);\n if (guard && isIterateeCall(prototype, properties, guard)) {\n properties = null;\n }\n return properties ? baseCopy(properties, result, keys(properties)) : result;\n }\n\n /**\n * Assigns own enumerable properties of source object(s) to the destination\n * object for all destination properties that resolve to `undefined`. Once a\n * property is set, additional defaults of the same property are ignored.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @returns {Object} Returns `object`.\n * @example\n *\n * _.defaults({ 'user': 'barney' }, { 'age': 36 }, { 'user': 'fred' });\n * // => { 'user': 'barney', 'age': 36 }\n */\n function defaults(object) {\n if (object == null) {\n return object;\n }\n var args = arrayCopy(arguments);\n args.push(assignDefaults);\n return assign.apply(undefined, args);\n }\n\n /**\n * This method is like `_.findIndex` except that it returns the key of the\n * first element `predicate` returns truthy for, instead of the element itself.\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to search.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {string|undefined} Returns the key of the matched element, else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findKey(users, function(chr) {\n * return chr.age < 40;\n * });\n * // => 'barney' (iteration order is not guaranteed)\n *\n * // using the `_.matches` callback shorthand\n * _.findKey(users, { 'age': 1, 'active': true });\n * // => 'pebbles'\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.findKey(users, 'active', false);\n * // => 'fred'\n *\n * // using the `_.property` callback shorthand\n * _.findKey(users, 'active');\n * // => 'barney'\n */\n function findKey(object, predicate, thisArg) {\n predicate = getCallback(predicate, thisArg, 3);\n return baseFind(object, predicate, baseForOwn, true);\n }\n\n /**\n * This method is like `_.findKey` except that it iterates over elements of\n * a collection in the opposite order.\n *\n * If a property name is provided for `predicate` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `predicate` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to search.\n * @param {Function|Object|string} [predicate=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {string|undefined} Returns the key of the matched element, else `undefined`.\n * @example\n *\n * var users = {\n * 'barney': { 'age': 36, 'active': true },\n * 'fred': { 'age': 40, 'active': false },\n * 'pebbles': { 'age': 1, 'active': true }\n * };\n *\n * _.findLastKey(users, function(chr) {\n * return chr.age < 40;\n * });\n * // => returns `pebbles` assuming `_.findKey` returns `barney`\n *\n * // using the `_.matches` callback shorthand\n * _.findLastKey(users, { 'age': 36, 'active': true });\n * // => 'barney'\n *\n * // using the `_.matchesProperty` callback shorthand\n * _.findLastKey(users, 'active', false);\n * // => 'fred'\n *\n * // using the `_.property` callback shorthand\n * _.findLastKey(users, 'active');\n * // => 'pebbles'\n */\n function findLastKey(object, predicate, thisArg) {\n predicate = getCallback(predicate, thisArg, 3);\n return baseFind(object, predicate, baseForOwnRight, true);\n }\n\n /**\n * Iterates over own and inherited enumerable properties of an object invoking\n * `iteratee` for each property. The `iteratee` is bound to `thisArg` and invoked\n * with three arguments; (value, key, object). Iterator functions may exit\n * iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forIn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => logs 'a', 'b', and 'c' (iteration order is not guaranteed)\n */\n function forIn(object, iteratee, thisArg) {\n if (typeof iteratee != 'function' || typeof thisArg != 'undefined') {\n iteratee = bindCallback(iteratee, thisArg, 3);\n }\n return baseFor(object, iteratee, keysIn);\n }\n\n /**\n * This method is like `_.forIn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forInRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => logs 'c', 'b', and 'a' assuming `_.forIn ` logs 'a', 'b', and 'c'\n */\n function forInRight(object, iteratee, thisArg) {\n iteratee = bindCallback(iteratee, thisArg, 3);\n return baseForRight(object, iteratee, keysIn);\n }\n\n /**\n * Iterates over own enumerable properties of an object invoking `iteratee`\n * for each property. The `iteratee` is bound to `thisArg` and invoked with\n * three arguments; (value, key, object). Iterator functions may exit iteration\n * early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwn(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => logs 'a' and 'b' (iteration order is not guaranteed)\n */\n function forOwn(object, iteratee, thisArg) {\n if (typeof iteratee != 'function' || typeof thisArg != 'undefined') {\n iteratee = bindCallback(iteratee, thisArg, 3);\n }\n return baseForOwn(object, iteratee);\n }\n\n /**\n * This method is like `_.forOwn` except that it iterates over properties of\n * `object` in the opposite order.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {Object} Returns `object`.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.forOwnRight(new Foo, function(value, key) {\n * console.log(key);\n * });\n * // => logs 'b' and 'a' assuming `_.forOwn` logs 'a' and 'b'\n */\n function forOwnRight(object, iteratee, thisArg) {\n iteratee = bindCallback(iteratee, thisArg, 3);\n return baseForRight(object, iteratee, keys);\n }\n\n /**\n * Creates an array of function property names from all enumerable properties,\n * own and inherited, of `object`.\n *\n * @static\n * @memberOf _\n * @alias methods\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the new array of property names.\n * @example\n *\n * _.functions(_);\n * // => ['after', 'ary', 'assign', ...]\n */\n function functions(object) {\n return baseFunctions(object, keysIn(object));\n }\n\n /**\n * Checks if `key` exists as a direct property of `object` instead of an\n * inherited property.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to inspect.\n * @param {string} key The key to check.\n * @returns {boolean} Returns `true` if `key` is a direct property, else `false`.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 3 };\n *\n * _.has(object, 'b');\n * // => true\n */\n function has(object, key) {\n return object ? hasOwnProperty.call(object, key) : false;\n }\n\n /**\n * Creates an object composed of the inverted keys and values of `object`.\n * If `object` contains duplicate values, subsequent values overwrite property\n * assignments of previous values unless `multiValue` is `true`.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to invert.\n * @param {boolean} [multiValue] Allow multiple values per key.\n * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.\n * @returns {Object} Returns the new inverted object.\n * @example\n *\n * var object = { 'a': 1, 'b': 2, 'c': 1 };\n *\n * _.invert(object);\n * // => { '1': 'c', '2': 'b' }\n *\n * // with `multiValue`\n * _.invert(object, true);\n * // => { '1': ['a', 'c'], '2': ['b'] }\n */\n function invert(object, multiValue, guard) {\n if (guard && isIterateeCall(object, multiValue, guard)) {\n multiValue = null;\n }\n var index = -1,\n props = keys(object),\n length = props.length,\n result = {};\n\n while (++index < length) {\n var key = props[index],\n value = object[key];\n\n if (multiValue) {\n if (hasOwnProperty.call(result, value)) {\n result[value].push(key);\n } else {\n result[value] = [key];\n }\n }\n else {\n result[value] = key;\n }\n }\n return result;\n }\n\n /**\n * Creates an array of the own enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects. See the\n * [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.keys)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keys(new Foo);\n * // => ['a', 'b'] (iteration order is not guaranteed)\n *\n * _.keys('hi');\n * // => ['0', '1']\n */\n var keys = !nativeKeys ? shimKeys : function (object) {\n if (object) {\n var Ctor = object.constructor,\n length = object.length;\n }\n if ((typeof Ctor == 'function' && Ctor.prototype === object) ||\n (typeof object != 'function' && (length && isLength(length)))) {\n return shimKeys(object);\n }\n return isObject(object) ? nativeKeys(object) : [];\n };\n\n /**\n * Creates an array of the own and inherited enumerable property names of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the array of property names.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.keysIn(new Foo);\n * // => ['a', 'b', 'c'] (iteration order is not guaranteed)\n */\n function keysIn(object) {\n if (object == null) {\n return [];\n }\n if (!isObject(object)) {\n object = Object(object);\n }\n var length = object.length;\n length = (length && isLength(length) &&\n (isArray(object) || (support.nonEnumArgs && isArguments(object))) && length) || 0;\n\n var Ctor = object.constructor,\n index = -1,\n isProto = typeof Ctor == 'function' && Ctor.prototype === object,\n result = Array(length),\n skipIndexes = length > 0;\n\n while (++index < length) {\n result[index] = (index + '');\n }\n for (var key in object) {\n if (!(skipIndexes && isIndex(key, length)) &&\n !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {\n result.push(key);\n }\n }\n return result;\n }\n\n /**\n * Creates an object with the same keys as `object` and values generated by\n * running each own enumerable property of `object` through `iteratee`. The\n * iteratee function is bound to `thisArg` and invoked with three arguments;\n * (value, key, object).\n *\n * If a property name is provided for `iteratee` the created `_.property`\n * style callback returns the property value of the given element.\n *\n * If a value is also provided for `thisArg` the created `_.matchesProperty`\n * style callback returns `true` for elements that have a matching property\n * value, else `false`.\n *\n * If an object is provided for `iteratee` the created `_.matches` style\n * callback returns `true` for elements that have the properties of the given\n * object, else `false`.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to iterate over.\n * @param {Function|Object|string} [iteratee=_.identity] The function invoked\n * per iteration.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {Object} Returns the new mapped object.\n * @example\n *\n * _.mapValues({ 'a': 1, 'b': 2 }, function(n) {\n * return n * 3;\n * });\n * // => { 'a': 3, 'b': 6 }\n *\n * var users = {\n * 'fred': { 'user': 'fred', 'age': 40 },\n * 'pebbles': { 'user': 'pebbles', 'age': 1 }\n * };\n *\n * // using the `_.property` callback shorthand\n * _.mapValues(users, 'age');\n * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)\n */\n function mapValues(object, iteratee, thisArg) {\n var result = {};\n iteratee = getCallback(iteratee, thisArg, 3);\n\n baseForOwn(object, function (value, key, object) {\n result[key] = iteratee(value, key, object);\n });\n return result;\n }\n\n /**\n * Recursively merges own enumerable properties of the source object(s), that\n * don't resolve to `undefined` into the destination object. Subsequent sources\n * overwrite property assignments of previous sources. If `customizer` is\n * provided it is invoked to produce the merged values of the destination and\n * source properties. If `customizer` returns `undefined` merging is handled\n * by the method instead. The `customizer` is bound to `thisArg` and invoked\n * with five arguments; (objectValue, sourceValue, key, object, source).\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The destination object.\n * @param {...Object} [sources] The source objects.\n * @param {Function} [customizer] The function to customize merging properties.\n * @param {*} [thisArg] The `this` binding of `customizer`.\n * @returns {Object} Returns `object`.\n * @example\n *\n * var users = {\n * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }]\n * };\n *\n * var ages = {\n * 'data': [{ 'age': 36 }, { 'age': 40 }]\n * };\n *\n * _.merge(users, ages);\n * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] }\n *\n * // using a customizer callback\n * var object = {\n * 'fruits': ['apple'],\n * 'vegetables': ['beet']\n * };\n *\n * var other = {\n * 'fruits': ['banana'],\n * 'vegetables': ['carrot']\n * };\n *\n * _.merge(object, other, function(a, b) {\n * if (_.isArray(a)) {\n * return a.concat(b);\n * }\n * });\n * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] }\n */\n var merge = createAssigner(baseMerge);\n\n /**\n * The opposite of `_.pick`; this method creates an object composed of the\n * own and inherited enumerable properties of `object` that are not omitted.\n * Property names may be specified as individual arguments or as arrays of\n * property names. If `predicate` is provided it is invoked for each property\n * of `object` omitting the properties `predicate` returns truthy for. The\n * predicate is bound to `thisArg` and invoked with three arguments;\n * (value, key, object).\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {Function|...(string|string[])} [predicate] The function invoked per\n * iteration or property names to omit, specified as individual property\n * names or arrays of property names.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'user': 'fred', 'age': 40 };\n *\n * _.omit(object, 'age');\n * // => { 'user': 'fred' }\n *\n * _.omit(object, _.isNumber);\n * // => { 'user': 'fred' }\n */\n function omit(object, predicate, thisArg) {\n if (object == null) {\n return {};\n }\n if (typeof predicate != 'function') {\n var props = arrayMap(baseFlatten(arguments, false, false, 1), String);\n return pickByArray(object, baseDifference(keysIn(object), props));\n }\n predicate = bindCallback(predicate, thisArg, 3);\n return pickByCallback(object, function (value, key, object) {\n return !predicate(value, key, object);\n });\n }\n\n /**\n * Creates a two dimensional array of the key-value pairs for `object`,\n * e.g. `[[key1, value1], [key2, value2]]`.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to inspect.\n * @returns {Array} Returns the new array of key-value pairs.\n * @example\n *\n * _.pairs({ 'barney': 36, 'fred': 40 });\n * // => [['barney', 36], ['fred', 40]] (iteration order is not guaranteed)\n */\n function pairs(object) {\n var index = -1,\n props = keys(object),\n length = props.length,\n result = Array(length);\n\n while (++index < length) {\n var key = props[index];\n result[index] = [key, object[key]];\n }\n return result;\n }\n\n /**\n * Creates an object composed of the picked `object` properties. Property\n * names may be specified as individual arguments or as arrays of property\n * names. If `predicate` is provided it is invoked for each property of `object`\n * picking the properties `predicate` returns truthy for. The predicate is\n * bound to `thisArg` and invoked with three arguments; (value, key, object).\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The source object.\n * @param {Function|...(string|string[])} [predicate] The function invoked per\n * iteration or property names to pick, specified as individual property\n * names or arrays of property names.\n * @param {*} [thisArg] The `this` binding of `predicate`.\n * @returns {Object} Returns the new object.\n * @example\n *\n * var object = { 'user': 'fred', 'age': 40 };\n *\n * _.pick(object, 'user');\n * // => { 'user': 'fred' }\n *\n * _.pick(object, _.isString);\n * // => { 'user': 'fred' }\n */\n function pick(object, predicate, thisArg) {\n if (object == null) {\n return {};\n }\n return typeof predicate == 'function'\n ? pickByCallback(object, bindCallback(predicate, thisArg, 3))\n : pickByArray(object, baseFlatten(arguments, false, false, 1));\n }\n\n /**\n * Resolves the value of property `key` on `object`. If the value of `key` is\n * a function it is invoked with the `this` binding of `object` and its result\n * is returned, else the property value is returned. If the property value is\n * `undefined` the `defaultValue` is used in its place.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @param {string} key The key of the property to resolve.\n * @param {*} [defaultValue] The value returned if the property value\n * resolves to `undefined`.\n * @returns {*} Returns the resolved value.\n * @example\n *\n * var object = { 'user': 'fred', 'age': _.constant(40) };\n *\n * _.result(object, 'user');\n * // => 'fred'\n *\n * _.result(object, 'age');\n * // => 40\n *\n * _.result(object, 'status', 'busy');\n * // => 'busy'\n *\n * _.result(object, 'status', _.constant('busy'));\n * // => 'busy'\n */\n function result(object, key, defaultValue) {\n var value = object == null ? undefined : object[key];\n if (typeof value == 'undefined') {\n value = defaultValue;\n }\n return isFunction(value) ? value.call(object) : value;\n }\n\n /**\n * An alternative to `_.reduce`; this method transforms `object` to a new\n * `accumulator` object which is the result of running each of its own enumerable\n * properties through `iteratee`, with each invocation potentially mutating\n * the `accumulator` object. The `iteratee` is bound to `thisArg` and invoked\n * with four arguments; (accumulator, value, key, object). Iterator functions\n * may exit iteration early by explicitly returning `false`.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Array|Object} object The object to iterate over.\n * @param {Function} [iteratee=_.identity] The function invoked per iteration.\n * @param {*} [accumulator] The custom accumulator value.\n * @param {*} [thisArg] The `this` binding of `iteratee`.\n * @returns {*} Returns the accumulated value.\n * @example\n *\n * _.transform([2, 3, 4], function(result, n) {\n * result.push(n *= n);\n * return n % 2 == 0;\n * });\n * // => [4, 9]\n *\n * _.transform({ 'a': 1, 'b': 2 }, function(result, n, key) {\n * result[key] = n * 3;\n * });\n * // => { 'a': 3, 'b': 6 }\n */\n function transform(object, iteratee, accumulator, thisArg) {\n var isArr = isArray(object) || isTypedArray(object);\n iteratee = getCallback(iteratee, thisArg, 4);\n\n if (accumulator == null) {\n if (isArr || isObject(object)) {\n var Ctor = object.constructor;\n if (isArr) {\n accumulator = isArray(object) ? new Ctor : [];\n } else {\n accumulator = baseCreate(isFunction(Ctor) && Ctor.prototype);\n }\n } else {\n accumulator = {};\n }\n }\n (isArr ? arrayEach : baseForOwn)(object, function (value, index, object) {\n return iteratee(accumulator, value, index, object);\n });\n return accumulator;\n }\n\n /**\n * Creates an array of the own enumerable property values of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.values(new Foo);\n * // => [1, 2] (iteration order is not guaranteed)\n *\n * _.values('hi');\n * // => ['h', 'i']\n */\n function values(object) {\n return baseValues(object, keys(object));\n }\n\n /**\n * Creates an array of the own and inherited enumerable property values\n * of `object`.\n *\n * **Note:** Non-object values are coerced to objects.\n *\n * @static\n * @memberOf _\n * @category Object\n * @param {Object} object The object to query.\n * @returns {Array} Returns the array of property values.\n * @example\n *\n * function Foo() {\n * this.a = 1;\n * this.b = 2;\n * }\n *\n * Foo.prototype.c = 3;\n *\n * _.valuesIn(new Foo);\n * // => [1, 2, 3] (iteration order is not guaranteed)\n */\n function valuesIn(object) {\n return baseValues(object, keysIn(object));\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Checks if `n` is between `start` and up to but not including, `end`. If\n * `end` is not specified it defaults to `start` with `start` becoming `0`.\n *\n * @static\n * @memberOf _\n * @category Number\n * @param {number} n The number to check.\n * @param {number} [start=0] The start of the range.\n * @param {number} end The end of the range.\n * @returns {boolean} Returns `true` if `n` is in the range, else `false`.\n * @example\n *\n * _.inRange(3, 2, 4);\n * // => true\n *\n * _.inRange(4, 8);\n * // => true\n *\n * _.inRange(4, 2);\n * // => false\n *\n * _.inRange(2, 2);\n * // => false\n *\n * _.inRange(1.2, 2);\n * // => true\n *\n * _.inRange(5.2, 4);\n * // => false\n */\n function inRange(value, start, end) {\n start = +start || 0;\n if (typeof end === 'undefined') {\n end = start;\n start = 0;\n } else {\n end = +end || 0;\n }\n return value >= start && value < end;\n }\n\n /**\n * Produces a random number between `min` and `max` (inclusive). If only one\n * argument is provided a number between `0` and the given number is returned.\n * If `floating` is `true`, or either `min` or `max` are floats, a floating-point\n * number is returned instead of an integer.\n *\n * @static\n * @memberOf _\n * @category Number\n * @param {number} [min=0] The minimum possible value.\n * @param {number} [max=1] The maximum possible value.\n * @param {boolean} [floating] Specify returning a floating-point number.\n * @returns {number} Returns the random number.\n * @example\n *\n * _.random(0, 5);\n * // => an integer between 0 and 5\n *\n * _.random(5);\n * // => also an integer between 0 and 5\n *\n * _.random(5, true);\n * // => a floating-point number between 0 and 5\n *\n * _.random(1.2, 5.2);\n * // => a floating-point number between 1.2 and 5.2\n */\n function random(min, max, floating) {\n if (floating && isIterateeCall(min, max, floating)) {\n max = floating = null;\n }\n var noMin = min == null,\n noMax = max == null;\n\n if (floating == null) {\n if (noMax && typeof min == 'boolean') {\n floating = min;\n min = 1;\n }\n else if (typeof max == 'boolean') {\n floating = max;\n noMax = true;\n }\n }\n if (noMin && noMax) {\n max = 1;\n noMax = false;\n }\n min = +min || 0;\n if (noMax) {\n max = min;\n min = 0;\n } else {\n max = +max || 0;\n }\n if (floating || min % 1 || max % 1) {\n var rand = nativeRandom();\n return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand + '').length - 1)))), max);\n }\n return baseRandom(min, max);\n }\n\n /*------------------------------------------------------------------------*/\n\n /**\n * Converts `string` to camel case.\n * See [Wikipedia](https://en.wikipedia.org/wiki/CamelCase) for more details.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the camel cased string.\n * @example\n *\n * _.camelCase('Foo Bar');\n * // => 'fooBar'\n *\n * _.camelCase('--foo-bar');\n * // => 'fooBar'\n *\n * _.camelCase('__foo_bar__');\n * // => 'fooBar'\n */\n var camelCase = createCompounder(function (result, word, index) {\n word = word.toLowerCase();\n return result + (index ? (word.charAt(0).toUpperCase() + word.slice(1)) : word);\n });\n\n /**\n * Capitalizes the first character of `string`.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to capitalize.\n * @returns {string} Returns the capitalized string.\n * @example\n *\n * _.capitalize('fred');\n * // => 'Fred'\n */\n function capitalize(string) {\n string = baseToString(string);\n return string && (string.charAt(0).toUpperCase() + string.slice(1));\n }\n\n /**\n * Deburrs `string` by converting latin-1 supplementary letters to basic latin letters.\n * See [Wikipedia](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to deburr.\n * @returns {string} Returns the deburred string.\n * @example\n *\n * _.deburr('déjà vu');\n * // => 'deja vu'\n */\n function deburr(string) {\n string = baseToString(string);\n return string && string.replace(reLatin1, deburrLetter);\n }\n\n /**\n * Checks if `string` ends with the given target string.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to search.\n * @param {string} [target] The string to search for.\n * @param {number} [position=string.length] The position to search from.\n * @returns {boolean} Returns `true` if `string` ends with `target`, else `false`.\n * @example\n *\n * _.endsWith('abc', 'c');\n * // => true\n *\n * _.endsWith('abc', 'b');\n * // => false\n *\n * _.endsWith('abc', 'b', 2);\n * // => true\n */\n function endsWith(string, target, position) {\n string = baseToString(string);\n target = (target + '');\n\n var length = string.length;\n position = (typeof position == 'undefined' ? length : nativeMin(position < 0 ? 0 : (+position || 0), length)) - target.length;\n return position >= 0 && string.indexOf(target, position) == position;\n }\n\n /**\n * Converts the characters \"&\", \"<\", \">\", '\"', \"'\", and '`', in `string` to\n * their corresponding HTML entities.\n *\n * **Note:** No other characters are escaped. To escape additional characters\n * use a third-party library like [_he_](https://mths.be/he).\n *\n * Though the \">\" character is escaped for symmetry, characters like\n * \">\" and \"/\" don't require escaping in HTML and have no special meaning\n * unless they're part of a tag or unquoted attribute value.\n * See [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)\n * (under \"semi-related fun fact\") for more details.\n *\n * Backticks are escaped because in Internet Explorer < 9, they can break out\n * of attribute values or HTML comments. See [#102](https://html5sec.org/#102),\n * [#108](https://html5sec.org/#108), and [#133](https://html5sec.org/#133) of\n * the [HTML5 Security Cheatsheet](https://html5sec.org/) for more details.\n *\n * When working with HTML you should always quote attribute values to reduce\n * XSS vectors. See [Ryan Grove's article](http://wonko.com/post/html-escaping)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escape('fred, barney, & pebbles');\n * // => 'fred, barney, & pebbles'\n */\n function escape(string) {\n // Reset `lastIndex` because in IE < 9 `String#replace` does not.\n string = baseToString(string);\n return (string && reHasUnescapedHtml.test(string))\n ? string.replace(reUnescapedHtml, escapeHtmlChar)\n : string;\n }\n\n /**\n * Escapes the `RegExp` special characters \"\\\", \"^\", \"$\", \".\", \"|\", \"?\", \"*\",\n * \"+\", \"(\", \")\", \"[\", \"]\", \"{\" and \"}\" in `string`.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to escape.\n * @returns {string} Returns the escaped string.\n * @example\n *\n * _.escapeRegExp('[lodash](https://lodash.com/)');\n * // => '\\[lodash\\]\\(https://lodash\\.com/\\)'\n */\n function escapeRegExp(string) {\n string = baseToString(string);\n return (string && reHasRegExpChars.test(string))\n ? string.replace(reRegExpChars, '\\\\$&')\n : string;\n }\n\n /**\n * Converts `string` to kebab case.\n * See [Wikipedia](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles) for\n * more details.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the kebab cased string.\n * @example\n *\n * _.kebabCase('Foo Bar');\n * // => 'foo-bar'\n *\n * _.kebabCase('fooBar');\n * // => 'foo-bar'\n *\n * _.kebabCase('__foo_bar__');\n * // => 'foo-bar'\n */\n var kebabCase = createCompounder(function (result, word, index) {\n return result + (index ? '-' : '') + word.toLowerCase();\n });\n\n /**\n * Pads `string` on the left and right sides if it is shorter then the given\n * padding length. The `chars` string may be truncated if the number of padding\n * characters can't be evenly divided by the padding length.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.pad('abc', 8);\n * // => ' abc '\n *\n * _.pad('abc', 8, '_-');\n * // => '_-abc_-_'\n *\n * _.pad('abc', 3);\n * // => 'abc'\n */\n function pad(string, length, chars) {\n string = baseToString(string);\n length = +length;\n\n var strLength = string.length;\n if (strLength >= length || !nativeIsFinite(length)) {\n return string;\n }\n var mid = (length - strLength) / 2,\n leftLength = floor(mid),\n rightLength = ceil(mid);\n\n chars = createPad('', rightLength, chars);\n return chars.slice(0, leftLength) + string + chars;\n }\n\n /**\n * Pads `string` on the left side if it is shorter then the given padding\n * length. The `chars` string may be truncated if the number of padding\n * characters exceeds the padding length.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padLeft('abc', 6);\n * // => ' abc'\n *\n * _.padLeft('abc', 6, '_-');\n * // => '_-_abc'\n *\n * _.padLeft('abc', 3);\n * // => 'abc'\n */\n function padLeft(string, length, chars) {\n string = baseToString(string);\n return string && (createPad(string, length, chars) + string);\n }\n\n /**\n * Pads `string` on the right side if it is shorter then the given padding\n * length. The `chars` string may be truncated if the number of padding\n * characters exceeds the padding length.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to pad.\n * @param {number} [length=0] The padding length.\n * @param {string} [chars=' '] The string used as padding.\n * @returns {string} Returns the padded string.\n * @example\n *\n * _.padRight('abc', 6);\n * // => 'abc '\n *\n * _.padRight('abc', 6, '_-');\n * // => 'abc_-_'\n *\n * _.padRight('abc', 3);\n * // => 'abc'\n */\n function padRight(string, length, chars) {\n string = baseToString(string);\n return string && (string + createPad(string, length, chars));\n }\n\n /**\n * Converts `string` to an integer of the specified radix. If `radix` is\n * `undefined` or `0`, a `radix` of `10` is used unless `value` is a hexadecimal,\n * in which case a `radix` of `16` is used.\n *\n * **Note:** This method aligns with the ES5 implementation of `parseInt`.\n * See the [ES5 spec](https://es5.github.io/#E) for more details.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} string The string to convert.\n * @param {number} [radix] The radix to interpret `value` by.\n * @param- {Object} [guard] Enables use as a callback for functions like `_.map`.\n * @returns {number} Returns the converted integer.\n * @example\n *\n * _.parseInt('08');\n * // => 8\n *\n * _.map(['6', '08', '10'], _.parseInt);\n * // => [6, 8, 10]\n */\n function parseInt(string, radix, guard) {\n if (guard && isIterateeCall(string, radix, guard)) {\n radix = 0;\n }\n return nativeParseInt(string, radix);\n }\n // Fallback for environments with pre-ES5 implementations.\n if (nativeParseInt(whitespace + '08') != 8) {\n parseInt = function (string, radix, guard) {\n // Firefox < 21 and Opera < 15 follow ES3 for `parseInt`.\n // Chrome fails to trim leading whitespace characters.\n // See https://code.google.com/p/v8/issues/detail?id=3109 for more details.\n if (guard ? isIterateeCall(string, radix, guard) : radix == null) {\n radix = 0;\n } else if (radix) {\n radix = +radix;\n }\n string = trim(string);\n return nativeParseInt(string, radix || (reHexPrefix.test(string) ? 16 : 10));\n };\n }\n\n /**\n * Repeats the given string `n` times.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to repeat.\n * @param {number} [n=0] The number of times to repeat the string.\n * @returns {string} Returns the repeated string.\n * @example\n *\n * _.repeat('*', 3);\n * // => '***'\n *\n * _.repeat('abc', 2);\n * // => 'abcabc'\n *\n * _.repeat('abc', 0);\n * // => ''\n */\n function repeat(string, n) {\n var result = '';\n string = baseToString(string);\n n = +n;\n if (n < 1 || !string || !nativeIsFinite(n)) {\n return result;\n }\n // Leverage the exponentiation by squaring algorithm for a faster repeat.\n // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.\n do {\n if (n % 2) {\n result += string;\n }\n n = floor(n / 2);\n string += string;\n } while (n);\n\n return result;\n }\n\n /**\n * Converts `string` to snake case.\n * See [Wikipedia](https://en.wikipedia.org/wiki/Snake_case) for more details.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the snake cased string.\n * @example\n *\n * _.snakeCase('Foo Bar');\n * // => 'foo_bar'\n *\n * _.snakeCase('fooBar');\n * // => 'foo_bar'\n *\n * _.snakeCase('--foo-bar');\n * // => 'foo_bar'\n */\n var snakeCase = createCompounder(function (result, word, index) {\n return result + (index ? '_' : '') + word.toLowerCase();\n });\n\n /**\n * Converts `string` to start case.\n * See [Wikipedia](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage)\n * for more details.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to convert.\n * @returns {string} Returns the start cased string.\n * @example\n *\n * _.startCase('--foo-bar');\n * // => 'Foo Bar'\n *\n * _.startCase('fooBar');\n * // => 'Foo Bar'\n *\n * _.startCase('__foo_bar__');\n * // => 'Foo Bar'\n */\n var startCase = createCompounder(function (result, word, index) {\n return result + (index ? ' ' : '') + (word.charAt(0).toUpperCase() + word.slice(1));\n });\n\n /**\n * Checks if `string` starts with the given target string.\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The string to search.\n * @param {string} [target] The string to search for.\n * @param {number} [position=0] The position to search from.\n * @returns {boolean} Returns `true` if `string` starts with `target`, else `false`.\n * @example\n *\n * _.startsWith('abc', 'a');\n * // => true\n *\n * _.startsWith('abc', 'b');\n * // => false\n *\n * _.startsWith('abc', 'b', 1);\n * // => true\n */\n function startsWith(string, target, position) {\n string = baseToString(string);\n position = position == null ? 0 : nativeMin(position < 0 ? 0 : (+position || 0), string.length);\n return string.lastIndexOf(target, position) == position;\n }\n\n /**\n * Creates a compiled template function that can interpolate data properties\n * in \"interpolate\" delimiters, HTML-escape interpolated data properties in\n * \"escape\" delimiters, and execute JavaScript in \"evaluate\" delimiters. Data\n * properties may be accessed as free variables in the template. If a setting\n * object is provided it takes precedence over `_.templateSettings` values.\n *\n * **Note:** In the development build `_.template` utilizes sourceURLs for easier debugging.\n * See the [HTML5 Rocks article on sourcemaps](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)\n * for more details.\n *\n * For more information on precompiling templates see\n * [lodash's custom builds documentation](https://lodash.com/custom-builds).\n *\n * For more information on Chrome extension sandboxes see\n * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).\n *\n * @static\n * @memberOf _\n * @category String\n * @param {string} [string=''] The template string.\n * @param {Object} [options] The options object.\n * @param {RegExp} [options.escape] The HTML \"escape\" delimiter.\n * @param {RegExp} [options.evaluate] The \"evaluate\" delimiter.\n * @param {Object} [options.imports] An object to import into the template as free variables.\n * @param {RegExp} [options.interpolate] The \"interpolate\" delimiter.\n * @param {string} [options.sourceURL] The sourceURL of the template's compiled source.\n * @param {string} [options.variable] The data object variable name.\n * @param- {Object} [otherOptions] Enables the legacy `options` param signature.\n * @returns {Function} Returns the compiled template function.\n * @example\n *\n * // using the \"interpolate\" delimiter to create a compiled template\n * var compiled = _.template('hello <%= user %>!');\n * compiled({ 'user': 'fred' });\n * // => 'hello fred!'\n *\n * // using the HTML \"escape\" delimiter to escape data property values\n * var compiled = _.template('<%- value %>');\n * compiled({ 'value': '.\");\n }\n };\n\n _pageWindow.load(function () { _pageLoaded = true; });\n\n function validateTransport(requestedTransport, connection) {\n /// Validates the requested transport by cross checking it with the pre-defined signalR.transports\n /// The designated transports that the user has specified.\n /// The connection that will be using the requested transports. Used for logging purposes.\n /// \n\n if ($.isArray(requestedTransport)) {\n // Go through transport array and remove an \"invalid\" tranports\n for (var i = requestedTransport.length - 1; i >= 0; i--) {\n var transport = requestedTransport[i];\n if ($.type(transport) !== \"string\" || !signalR.transports[transport]) {\n connection.log(\"Invalid transport: \" + transport + \", removing it from the transports list.\");\n requestedTransport.splice(i, 1);\n }\n }\n\n // Verify we still have transports left, if we dont then we have invalid transports\n if (requestedTransport.length === 0) {\n connection.log(\"No transports remain within the specified transport array.\");\n requestedTransport = null;\n }\n } else if (!signalR.transports[requestedTransport] && requestedTransport !== \"auto\") {\n connection.log(\"Invalid transport: \" + requestedTransport.toString() + \".\");\n requestedTransport = null;\n } else if (requestedTransport === \"auto\" && signalR._.ieVersion <= 8) {\n // If we're doing an auto transport and we're IE8 then force longPolling, #1764\n return [\"longPolling\"];\n\n }\n\n return requestedTransport;\n }\n\n function getDefaultPort(protocol) {\n if (protocol === \"http:\") {\n return 80;\n } else if (protocol === \"https:\") {\n return 443;\n }\n }\n\n function addDefaultPort(protocol, url) {\n // Remove ports from url. We have to check if there's a / or end of line\n // following the port in order to avoid removing ports such as 8080.\n if (url.match(/:\\d+$/)) {\n return url;\n } else {\n return url + \":\" + getDefaultPort(protocol);\n }\n }\n\n function ConnectingMessageBuffer(connection, drainCallback) {\n var that = this,\n buffer = [];\n\n that.tryBuffer = function (message) {\n if (connection.state === $.signalR.connectionState.connecting) {\n buffer.push(message);\n\n return true;\n }\n\n return false;\n };\n\n that.drain = function () {\n // Ensure that the connection is connected when we drain (do not want to drain while a connection is not active)\n if (connection.state === $.signalR.connectionState.connected) {\n while (buffer.length > 0) {\n drainCallback(buffer.shift());\n }\n }\n };\n\n that.clear = function () {\n buffer = [];\n };\n }\n\n signalR.fn = signalR.prototype = {\n init: function (url, qs, logging) {\n var $connection = $(this);\n\n this.url = url;\n this.qs = qs;\n this.lastError = null;\n this._ = {\n keepAliveData: {},\n connectingMessageBuffer: new ConnectingMessageBuffer(this, function (message) {\n $connection.triggerHandler(events.onReceived, [message]);\n }),\n onFailedTimeoutHandle: null,\n lastMessageAt: new Date().getTime(),\n lastActiveAt: new Date().getTime(),\n beatInterval: 5000, // Default value, will only be overridden if keep alive is enabled,\n beatHandle: null,\n totalTransportConnectTimeout: 0 // This will be the sum of the TransportConnectTimeout sent in response to negotiate and connection.transportConnectTimeout\n };\n if (typeof (logging) === \"boolean\") {\n this.logging = logging;\n }\n },\n\n _parseResponse: function (response) {\n var that = this;\n\n if (!response) {\n return response;\n } else if (typeof response === \"string\") {\n return that.json.parse(response);\n } else {\n return response;\n }\n },\n\n _originalJson: window.JSON,\n\n json: window.JSON,\n\n isCrossDomain: function (url, against) {\n /// Checks if url is cross domain\n /// The base URL\n /// \n /// An optional argument to compare the URL against, if not specified it will be set to window.location.\n /// If specified it must contain a protocol and a host property.\n /// \n var link;\n\n url = $.trim(url);\n\n against = against || window.location;\n\n if (url.indexOf(\"http\") !== 0) {\n return false;\n }\n\n // Create an anchor tag.\n link = window.document.createElement(\"a\");\n link.href = url;\n\n // When checking for cross domain we have to special case port 80 because the window.location will remove the \n return link.protocol + addDefaultPort(link.protocol, link.host) !== against.protocol + addDefaultPort(against.protocol, against.host);\n },\n\n ajaxDataType: \"text\",\n\n contentType: \"application/json; charset=UTF-8\",\n\n logging: false,\n\n state: signalR.connectionState.disconnected,\n\n clientProtocol: \"1.4\",\n\n reconnectDelay: 2000,\n\n transportConnectTimeout: 0,\n\n disconnectTimeout: 30000, // This should be set by the server in response to the negotiate request (30s default)\n\n reconnectWindow: 30000, // This should be set by the server in response to the negotiate request \n\n keepAliveWarnAt: 2 / 3, // Warn user of slow connection if we breach the X% mark of the keep alive timeout\n\n start: function (options, callback) {\n /// Starts the connection\n /// Options map\n /// A callback function to execute when the connection has started\n var connection = this,\n config = {\n pingInterval: 300000,\n waitForPageLoad: true,\n transport: \"auto\",\n jsonp: false\n },\n initialize,\n deferred = connection._deferral || $.Deferred(), // Check to see if there is a pre-existing deferral that's being built on, if so we want to keep using it\n parser = window.document.createElement(\"a\");\n\n connection.lastError = null;\n\n // Persist the deferral so that if start is called multiple times the same deferral is used.\n connection._deferral = deferred;\n\n if (!connection.json) {\n // no JSON!\n throw new Error(\"SignalR: No JSON parser found. Please ensure json2.js is referenced before the SignalR.js file if you need to support clients without native JSON parsing support, e.g. IE<8.\");\n }\n\n if ($.type(options) === \"function\") {\n // Support calling with single callback parameter\n callback = options;\n } else if ($.type(options) === \"object\") {\n $.extend(config, options);\n if ($.type(config.callback) === \"function\") {\n callback = config.callback;\n }\n }\n\n config.transport = validateTransport(config.transport, connection);\n\n // If the transport is invalid throw an error and abort start\n if (!config.transport) {\n throw new Error(\"SignalR: Invalid transport(s) specified, aborting start.\");\n }\n\n connection._.config = config;\n\n // Check to see if start is being called prior to page load\n // If waitForPageLoad is true we then want to re-direct function call to the window load event\n if (!_pageLoaded && config.waitForPageLoad === true) {\n connection._.deferredStartHandler = function () {\n connection.start(options, callback);\n };\n _pageWindow.bind(\"load\", connection._.deferredStartHandler);\n\n return deferred.promise();\n }\n\n // If we're already connecting just return the same deferral as the original connection start\n if (connection.state === signalR.connectionState.connecting) {\n return deferred.promise();\n } else if (changeState(connection,\n signalR.connectionState.disconnected,\n signalR.connectionState.connecting) === false) {\n // We're not connecting so try and transition into connecting.\n // If we fail to transition then we're either in connected or reconnecting.\n\n deferred.resolve(connection);\n return deferred.promise();\n }\n\n configureStopReconnectingTimeout(connection);\n\n // Resolve the full url\n parser.href = connection.url;\n if (!parser.protocol || parser.protocol === \":\") {\n connection.protocol = window.document.location.protocol;\n connection.host = parser.host || window.document.location.host;\n } else {\n connection.protocol = parser.protocol;\n connection.host = parser.host;\n }\n\n connection.baseUrl = connection.protocol + \"//\" + connection.host;\n\n // Set the websocket protocol\n connection.wsProtocol = connection.protocol === \"https:\" ? \"wss://\" : \"ws://\";\n\n // If jsonp with no/auto transport is specified, then set the transport to long polling\n // since that is the only transport for which jsonp really makes sense.\n // Some developers might actually choose to specify jsonp for same origin requests\n // as demonstrated by Issue #623.\n if (config.transport === \"auto\" && config.jsonp === true) {\n config.transport = \"longPolling\";\n }\n\n // If the url is protocol relative, prepend the current windows protocol to the url. \n if (connection.url.indexOf(\"//\") === 0) {\n connection.url = window.location.protocol + connection.url;\n connection.log(\"Protocol relative URL detected, normalizing it to '\" + connection.url + \"'.\");\n }\n\n if (this.isCrossDomain(connection.url)) {\n connection.log(\"Auto detected cross domain url.\");\n\n if (config.transport === \"auto\") {\n // TODO: Support XDM with foreverFrame\n config.transport = [\"webSockets\", \"serverSentEvents\", \"longPolling\"];\n }\n\n if (typeof (config.withCredentials) === \"undefined\") {\n config.withCredentials = true;\n }\n\n // Determine if jsonp is the only choice for negotiation, ajaxSend and ajaxAbort.\n // i.e. if the browser doesn't supports CORS\n // If it is, ignore any preference to the contrary, and switch to jsonp.\n if (!config.jsonp) {\n config.jsonp = !$.support.cors;\n\n if (config.jsonp) {\n connection.log(\"Using jsonp because this browser doesn't support CORS.\");\n }\n }\n\n connection.contentType = signalR._.defaultContentType;\n }\n\n connection.withCredentials = config.withCredentials;\n\n connection.ajaxDataType = config.jsonp ? \"jsonp\" : \"text\";\n\n $(connection).bind(events.onStart, function (e, data) {\n if ($.type(callback) === \"function\") {\n callback.call(connection);\n }\n deferred.resolve(connection);\n });\n\n initialize = function (transports, index) {\n var noTransportError = signalR._.error(resources.noTransportOnInit);\n\n index = index || 0;\n if (index >= transports.length) {\n // No transport initialized successfully\n $(connection).triggerHandler(events.onError, [noTransportError]);\n deferred.reject(noTransportError);\n // Stop the connection if it has connected and move it into the disconnected state\n connection.stop();\n return;\n }\n\n // The connection was aborted\n if (connection.state === signalR.connectionState.disconnected) {\n return;\n }\n\n var transportName = transports[index],\n transport = signalR.transports[transportName],\n initializationComplete = false,\n onFailed = function () {\n // Check if we've already triggered onFailed, onStart\n if (!initializationComplete) {\n initializationComplete = true;\n window.clearTimeout(connection._.onFailedTimeoutHandle);\n transport.stop(connection);\n initialize(transports, index + 1);\n }\n };\n\n connection.transport = transport;\n\n try {\n connection._.onFailedTimeoutHandle = window.setTimeout(function () {\n connection.log(transport.name + \" timed out when trying to connect.\");\n onFailed();\n }, connection._.totalTransportConnectTimeout);\n\n transport.start(connection, function () { // success\n var onStartSuccess = function () {\n // Firefox 11+ doesn't allow sync XHR withCredentials: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#withCredentials\n var isFirefox11OrGreater = signalR._.firefoxMajorVersion(window.navigator.userAgent) >= 11,\n asyncAbort = !!connection.withCredentials && isFirefox11OrGreater;\n\n connection.log(\"The start request succeeded. Transitioning to the connected state.\");\n\n if (supportsKeepAlive(connection)) {\n signalR.transports._logic.monitorKeepAlive(connection);\n }\n\n signalR.transports._logic.startHeartbeat(connection);\n\n // Used to ensure low activity clients maintain their authentication.\n // Must be configured once a transport has been decided to perform valid ping requests.\n signalR._.configurePingInterval(connection);\n\n if (!changeState(connection,\n signalR.connectionState.connecting,\n signalR.connectionState.connected)) {\n connection.log(\"WARNING! The connection was not in the connecting state.\");\n }\n\n // Drain any incoming buffered messages (messages that came in prior to connect)\n connection._.connectingMessageBuffer.drain();\n\n $(connection).triggerHandler(events.onStart);\n\n // wire the stop handler for when the user leaves the page\n _pageWindow.bind(\"unload\", function () {\n connection.log(\"Window unloading, stopping the connection.\");\n\n connection.stop(asyncAbort);\n });\n\n if (isFirefox11OrGreater) {\n // Firefox does not fire cross-domain XHRs in the normal unload handler on tab close.\n // #2400\n _pageWindow.bind(\"beforeunload\", function () {\n // If connection.stop() runs runs in beforeunload and fails, it will also fail\n // in unload unless connection.stop() runs after a timeout.\n window.setTimeout(function () {\n connection.stop(asyncAbort);\n }, 0);\n });\n }\n };\n\n if (!initializationComplete) {\n initializationComplete = true;\n // Prevent transport fallback\n window.clearTimeout(connection._.onFailedTimeoutHandle);\n\n // The connection was aborted while initializing transports\n if (connection.state === signalR.connectionState.disconnected) {\n return;\n }\n\n connection.log(transport.name + \" transport selected. Initiating start request.\");\n signalR.transports._logic.ajaxStart(connection, onStartSuccess);\n }\n }, onFailed);\n }\n catch (error) {\n connection.log(transport.name + \" transport threw '\" + error.message + \"' when attempting to start.\");\n onFailed();\n }\n };\n\n var url = connection.url + \"/negotiate\",\n onFailed = function (error, connection) {\n var err = signalR._.error(resources.errorOnNegotiate, error, connection._.negotiateRequest);\n\n $(connection).triggerHandler(events.onError, err);\n deferred.reject(err);\n // Stop the connection if negotiate failed\n connection.stop();\n };\n\n $(connection).triggerHandler(events.onStarting);\n\n url = signalR.transports._logic.prepareQueryString(connection, url);\n\n connection.log(\"Negotiating with '\" + url + \"'.\");\n\n // Save the ajax negotiate request object so we can abort it if stop is called while the request is in flight.\n connection._.negotiateRequest = signalR.transports._logic.ajax(connection, {\n url: url,\n error: function (error, statusText) {\n // We don't want to cause any errors if we're aborting our own negotiate request.\n if (statusText !== _negotiateAbortText) {\n onFailed(error, connection);\n } else {\n // This rejection will noop if the deferred has already been resolved or rejected.\n deferred.reject(signalR._.error(resources.stoppedWhileNegotiating, null /* error */, connection._.negotiateRequest));\n }\n },\n success: function (result) {\n var res,\n keepAliveData,\n protocolError,\n transports = [],\n supportedTransports = [];\n\n try {\n res = connection._parseResponse(result);\n } catch (error) {\n onFailed(signalR._.error(resources.errorParsingNegotiateResponse, error), connection);\n return;\n }\n\n keepAliveData = connection._.keepAliveData;\n connection.appRelativeUrl = res.Url;\n connection.id = res.ConnectionId;\n connection.token = res.ConnectionToken;\n connection.webSocketServerUrl = res.WebSocketServerUrl;\n\n // The long poll timeout is the ConnectionTimeout plus 10 seconds\n connection._.pollTimeout = res.ConnectionTimeout * 1000 + 10000; // in ms\n\n // Once the server has labeled the PersistentConnection as Disconnected, we should stop attempting to reconnect\n // after res.DisconnectTimeout seconds.\n connection.disconnectTimeout = res.DisconnectTimeout * 1000; // in ms\n\n // Add the TransportConnectTimeout from the response to the transportConnectTimeout from the client to calculate the total timeout\n connection._.totalTransportConnectTimeout = connection.transportConnectTimeout + res.TransportConnectTimeout * 1000;\n\n // If we have a keep alive\n if (res.KeepAliveTimeout) {\n // Register the keep alive data as activated\n keepAliveData.activated = true;\n\n // Timeout to designate when to force the connection into reconnecting converted to milliseconds\n keepAliveData.timeout = res.KeepAliveTimeout * 1000;\n\n // Timeout to designate when to warn the developer that the connection may be dead or is not responding.\n keepAliveData.timeoutWarning = keepAliveData.timeout * connection.keepAliveWarnAt;\n\n // Instantiate the frequency in which we check the keep alive. It must be short in order to not miss/pick up any changes\n connection._.beatInterval = (keepAliveData.timeout - keepAliveData.timeoutWarning) / 3;\n } else {\n keepAliveData.activated = false;\n }\n\n connection.reconnectWindow = connection.disconnectTimeout + (keepAliveData.timeout || 0);\n\n if (!res.ProtocolVersion || res.ProtocolVersion !== connection.clientProtocol) {\n protocolError = signalR._.error(signalR._.format(resources.protocolIncompatible, connection.clientProtocol, res.ProtocolVersion));\n $(connection).triggerHandler(events.onError, [protocolError]);\n deferred.reject(protocolError);\n\n return;\n }\n\n $.each(signalR.transports, function (key) {\n if ((key.indexOf(\"_\") === 0) || (key === \"webSockets\" && !res.TryWebSockets)) {\n return true;\n }\n supportedTransports.push(key);\n });\n\n if ($.isArray(config.transport)) {\n $.each(config.transport, function (_, transport) {\n if ($.inArray(transport, supportedTransports) >= 0) {\n transports.push(transport);\n }\n });\n } else if (config.transport === \"auto\") {\n transports = supportedTransports;\n } else if ($.inArray(config.transport, supportedTransports) >= 0) {\n transports.push(config.transport);\n }\n\n initialize(transports);\n }\n });\n\n return deferred.promise();\n },\n\n starting: function (callback) {\n /// Adds a callback that will be invoked before anything is sent over the connection\n /// A callback function to execute before the connection is fully instantiated.\n /// \n var connection = this;\n $(connection).bind(events.onStarting, function (e, data) {\n callback.call(connection);\n });\n return connection;\n },\n\n send: function (data) {\n /// Sends data over the connection\n /// The data to send over the connection\n /// \n var connection = this;\n\n if (connection.state === signalR.connectionState.disconnected) {\n // Connection hasn't been started yet\n throw new Error(\"SignalR: Connection must be started before data can be sent. Call .start() before .send()\");\n }\n\n if (connection.state === signalR.connectionState.connecting) {\n // Connection hasn't been started yet\n throw new Error(\"SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.\");\n }\n\n connection.transport.send(connection, data);\n // REVIEW: Should we return deferred here?\n return connection;\n },\n\n received: function (callback) {\n /// Adds a callback that will be invoked after anything is received over the connection\n /// A callback function to execute when any data is received on the connection\n /// \n var connection = this;\n $(connection).bind(events.onReceived, function (e, data) {\n callback.call(connection, data);\n });\n return connection;\n },\n\n stateChanged: function (callback) {\n /// Adds a callback that will be invoked when the connection state changes\n /// A callback function to execute when the connection state changes\n /// \n var connection = this;\n $(connection).bind(events.onStateChanged, function (e, data) {\n callback.call(connection, data);\n });\n return connection;\n },\n\n error: function (callback) {\n /// Adds a callback that will be invoked after an error occurs with the connection\n /// A callback function to execute when an error occurs on the connection\n /// \n var connection = this;\n $(connection).bind(events.onError, function (e, errorData, sendData) {\n connection.lastError = errorData;\n // In practice 'errorData' is the SignalR built error object.\n // In practice 'sendData' is undefined for all error events except those triggered by\n // 'ajaxSend' and 'webSockets.send'.'sendData' is the original send payload.\n callback.call(connection, errorData, sendData);\n });\n return connection;\n },\n\n disconnected: function (callback) {\n /// Adds a callback that will be invoked when the client disconnects\n /// A callback function to execute when the connection is broken\n /// \n var connection = this;\n $(connection).bind(events.onDisconnect, function (e, data) {\n callback.call(connection);\n });\n return connection;\n },\n\n connectionSlow: function (callback) {\n /// Adds a callback that will be invoked when the client detects a slow connection\n /// A callback function to execute when the connection is slow\n /// \n var connection = this;\n $(connection).bind(events.onConnectionSlow, function (e, data) {\n callback.call(connection);\n });\n\n return connection;\n },\n\n reconnecting: function (callback) {\n /// Adds a callback that will be invoked when the underlying transport begins reconnecting\n /// A callback function to execute when the connection enters a reconnecting state\n /// \n var connection = this;\n $(connection).bind(events.onReconnecting, function (e, data) {\n callback.call(connection);\n });\n return connection;\n },\n\n reconnected: function (callback) {\n /// Adds a callback that will be invoked when the underlying transport reconnects\n /// A callback function to execute when the connection is restored\n /// \n var connection = this;\n $(connection).bind(events.onReconnect, function (e, data) {\n callback.call(connection);\n });\n return connection;\n },\n\n stop: function (async, notifyServer) {\n /// Stops listening\n /// Whether or not to asynchronously abort the connection\n /// Whether we want to notify the server that we are aborting the connection\n /// \n var connection = this,\n // Save deferral because this is always cleaned up\n deferral = connection._deferral;\n\n // Verify that we've bound a load event.\n if (connection._.deferredStartHandler) {\n // Unbind the event.\n _pageWindow.unbind(\"load\", connection._.deferredStartHandler);\n }\n\n // Always clean up private non-timeout based state.\n delete connection._.config;\n delete connection._.deferredStartHandler;\n\n // This needs to be checked despite the connection state because a connection start can be deferred until page load.\n // If we've deferred the start due to a page load we need to unbind the \"onLoad\" -> start event.\n if (!_pageLoaded && (!connection._.config || connection._.config.waitForPageLoad === true)) {\n connection.log(\"Stopping connection prior to negotiate.\");\n\n // If we have a deferral we should reject it\n if (deferral) {\n deferral.reject(signalR._.error(resources.stoppedWhileLoading));\n }\n\n // Short-circuit because the start has not been fully started.\n return;\n }\n\n if (connection.state === signalR.connectionState.disconnected) {\n return;\n }\n\n connection.log(\"Stopping connection.\");\n\n changeState(connection, connection.state, signalR.connectionState.disconnected);\n\n // Clear this no matter what\n window.clearTimeout(connection._.beatHandle);\n window.clearTimeout(connection._.onFailedTimeoutHandle);\n window.clearInterval(connection._.pingIntervalId);\n\n if (connection.transport) {\n connection.transport.stop(connection);\n\n if (notifyServer !== false) {\n connection.transport.abort(connection, async);\n }\n\n if (supportsKeepAlive(connection)) {\n signalR.transports._logic.stopMonitoringKeepAlive(connection);\n }\n\n connection.transport = null;\n }\n\n if (connection._.negotiateRequest) {\n // If the negotiation request has already completed this will noop.\n connection._.negotiateRequest.abort(_negotiateAbortText);\n delete connection._.negotiateRequest;\n }\n\n // Ensure that tryAbortStartRequest is called before connection._deferral is deleted\n signalR.transports._logic.tryAbortStartRequest(connection);\n\n // Trigger the disconnect event\n $(connection).triggerHandler(events.onDisconnect);\n\n delete connection._deferral;\n delete connection.messageId;\n delete connection.groupsToken;\n delete connection.id;\n delete connection._.pingIntervalId;\n delete connection._.lastMessageAt;\n delete connection._.lastActiveAt;\n\n // Clear out our message buffer\n connection._.connectingMessageBuffer.clear();\n\n return connection;\n },\n\n log: function (msg) {\n log(msg, this.logging);\n }\n };\n\n signalR.fn.init.prototype = signalR.fn;\n\n signalR.noConflict = function () {\n /// Reinstates the original value of $.connection and returns the signalR object for manual assignment\n /// \n if ($.connection === signalR) {\n $.connection = _connection;\n }\n return signalR;\n };\n\n if ($.connection) {\n _connection = $.connection;\n }\n\n $.connection = $.signalR = signalR;\n\n}(window.jQuery, window));\n/* jquery.signalR.transports.common.js */\n// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.\n\n/*global window:false */\n/// \n\n(function ($, window, undefined) {\n\n var signalR = $.signalR,\n events = $.signalR.events,\n changeState = $.signalR.changeState,\n startAbortText = \"__Start Aborted__\",\n transportLogic;\n\n signalR.transports = {};\n\n function beat(connection) {\n if (connection._.keepAliveData.monitoring) {\n checkIfAlive(connection);\n }\n\n // Ensure that we successfully marked active before continuing the heartbeat.\n if (transportLogic.markActive(connection)) {\n connection._.beatHandle = window.setTimeout(function () {\n beat(connection);\n }, connection._.beatInterval);\n }\n }\n\n function checkIfAlive(connection) {\n var keepAliveData = connection._.keepAliveData,\n timeElapsed;\n\n // Only check if we're connected\n if (connection.state === signalR.connectionState.connected) {\n timeElapsed = new Date().getTime() - connection._.lastMessageAt;\n\n // Check if the keep alive has completely timed out\n if (timeElapsed >= keepAliveData.timeout) {\n connection.log(\"Keep alive timed out. Notifying transport that connection has been lost.\");\n\n // Notify transport that the connection has been lost\n connection.transport.lostConnection(connection);\n } else if (timeElapsed >= keepAliveData.timeoutWarning) {\n // This is to assure that the user only gets a single warning\n if (!keepAliveData.userNotified) {\n connection.log(\"Keep alive has been missed, connection may be dead/slow.\");\n $(connection).triggerHandler(events.onConnectionSlow);\n keepAliveData.userNotified = true;\n }\n } else {\n keepAliveData.userNotified = false;\n }\n }\n }\n\n function getAjaxUrl(connection, path) {\n var url = connection.url + path;\n\n if (connection.transport) {\n url += \"?transport=\" + connection.transport.name;\n }\n\n return transportLogic.prepareQueryString(connection, url);\n }\n\n transportLogic = signalR.transports._logic = {\n ajax: function (connection, options) {\n return $.ajax(\n $.extend(/*deep copy*/ true, {}, $.signalR.ajaxDefaults, {\n type: \"GET\",\n data: {},\n xhrFields: { withCredentials: connection.withCredentials },\n contentType: connection.contentType,\n dataType: connection.ajaxDataType\n }, options));\n },\n\n pingServer: function (connection) {\n /// Pings the server\n /// Connection associated with the server ping\n /// \n var url,\n xhr,\n deferral = $.Deferred();\n\n if (connection.transport) {\n url = connection.url + \"/ping\";\n\n url = transportLogic.addQs(url, connection.qs);\n\n xhr = transportLogic.ajax(connection, {\n url: url,\n success: function (result) {\n var data;\n\n try {\n data = connection._parseResponse(result);\n }\n catch (error) {\n deferral.reject(\n signalR._.transportError(\n signalR.resources.pingServerFailedParse,\n connection.transport,\n error,\n xhr\n )\n );\n connection.stop();\n return;\n }\n\n if (data.Response === \"pong\") {\n deferral.resolve();\n }\n else {\n deferral.reject(\n signalR._.transportError(\n signalR._.format(signalR.resources.pingServerFailedInvalidResponse, result),\n connection.transport,\n null /* error */,\n xhr\n )\n );\n }\n },\n error: function (error) {\n if (error.status === 401 || error.status === 403) {\n deferral.reject(\n signalR._.transportError(\n signalR._.format(signalR.resources.pingServerFailedStatusCode, error.status),\n connection.transport,\n error,\n xhr\n )\n );\n connection.stop();\n }\n else {\n deferral.reject(\n signalR._.transportError(\n signalR.resources.pingServerFailed,\n connection.transport,\n error,\n xhr\n )\n );\n }\n }\n });\n }\n else {\n deferral.reject(\n signalR._.transportError(\n signalR.resources.noConnectionTransport,\n connection.transport\n )\n );\n }\n\n return deferral.promise();\n },\n\n prepareQueryString: function (connection, url) {\n var preparedUrl;\n\n // Use addQs to start since it handles the ?/& prefix for us\n preparedUrl = transportLogic.addQs(url, \"clientProtocol=\" + connection.clientProtocol);\n\n // Add the user-specified query string params if any\n preparedUrl = transportLogic.addQs(preparedUrl, connection.qs);\n\n if (connection.token) {\n preparedUrl += \"&connectionToken=\" + window.encodeURIComponent(connection.token);\n }\n\n if (connection.data) {\n preparedUrl += \"&connectionData=\" + window.encodeURIComponent(connection.data);\n }\n\n return preparedUrl;\n },\n\n addQs: function (url, qs) {\n var appender = url.indexOf(\"?\") !== -1 ? \"&\" : \"?\",\n firstChar;\n\n if (!qs) {\n return url;\n }\n\n if (typeof (qs) === \"object\") {\n return url + appender + $.param(qs);\n }\n\n if (typeof (qs) === \"string\") {\n firstChar = qs.charAt(0);\n\n if (firstChar === \"?\" || firstChar === \"&\") {\n appender = \"\";\n }\n\n return url + appender + qs;\n }\n\n throw new Error(\"Query string property must be either a string or object.\");\n },\n\n getUrl: function (connection, transport, reconnecting, poll) {\n /// Gets the url for making a GET based connect request\n var baseUrl = transport === \"webSockets\" ? \"\" : connection.baseUrl,\n url = baseUrl + connection.appRelativeUrl,\n qs = \"transport=\" + transport;\n\n if (connection.groupsToken) {\n qs += \"&groupsToken=\" + window.encodeURIComponent(connection.groupsToken);\n }\n\n if (!reconnecting) {\n url += \"/connect\";\n } else {\n if (poll) {\n // longPolling transport specific\n url += \"/poll\";\n } else {\n url += \"/reconnect\";\n }\n\n if (connection.messageId) {\n qs += \"&messageId=\" + window.encodeURIComponent(connection.messageId);\n }\n }\n url += \"?\" + qs;\n url = transportLogic.prepareQueryString(connection, url);\n url += \"&tid=\" + Math.floor(Math.random() * 11);\n return url;\n },\n\n maximizePersistentResponse: function (minPersistentResponse) {\n return {\n MessageId: minPersistentResponse.C,\n Messages: minPersistentResponse.M,\n Initialized: typeof (minPersistentResponse.S) !== \"undefined\" ? true : false,\n Disconnect: typeof (minPersistentResponse.D) !== \"undefined\" ? true : false,\n ShouldReconnect: typeof (minPersistentResponse.T) !== \"undefined\" ? true : false,\n LongPollDelay: minPersistentResponse.L,\n GroupsToken: minPersistentResponse.G\n };\n },\n\n updateGroups: function (connection, groupsToken) {\n if (groupsToken) {\n connection.groupsToken = groupsToken;\n }\n },\n\n stringifySend: function (connection, message) {\n if (typeof (message) === \"string\" || typeof (message) === \"undefined\" || message === null) {\n return message;\n }\n return connection.json.stringify(message);\n },\n\n ajaxSend: function (connection, data) {\n var payload = transportLogic.stringifySend(connection, data),\n url = getAjaxUrl(connection, \"/send\"),\n xhr,\n onFail = function (error, connection) {\n $(connection).triggerHandler(events.onError, [signalR._.transportError(signalR.resources.sendFailed, connection.transport, error, xhr), data]);\n };\n\n\n xhr = transportLogic.ajax(connection, {\n url: url,\n type: connection.ajaxDataType === \"jsonp\" ? \"GET\" : \"POST\",\n contentType: signalR._.defaultContentType,\n data: {\n data: payload\n },\n success: function (result) {\n var res;\n\n if (result) {\n try {\n res = connection._parseResponse(result);\n }\n catch (error) {\n onFail(error, connection);\n connection.stop();\n return;\n }\n\n transportLogic.triggerReceived(connection, res);\n }\n },\n error: function (error, textStatus) {\n if (textStatus === \"abort\" || textStatus === \"parsererror\") {\n // The parsererror happens for sends that don't return any data, and hence\n // don't write the jsonp callback to the response. This is harder to fix on the server\n // so just hack around it on the client for now.\n return;\n }\n\n onFail(error, connection);\n }\n });\n\n return xhr;\n },\n\n ajaxAbort: function (connection, async) {\n if (typeof (connection.transport) === \"undefined\") {\n return;\n }\n\n // Async by default unless explicitly overidden\n async = typeof async === \"undefined\" ? true : async;\n\n var url = getAjaxUrl(connection, \"/abort\");\n\n transportLogic.ajax(connection, {\n url: url,\n async: async,\n timeout: 1000,\n type: \"POST\"\n });\n\n connection.log(\"Fired ajax abort async = \" + async + \".\");\n },\n\n ajaxStart: function (connection, onSuccess) {\n var rejectDeferred = function (error) {\n var deferred = connection._deferral;\n if (deferred) {\n deferred.reject(error);\n }\n },\n triggerStartError = function (error) {\n connection.log(\"The start request failed. Stopping the connection.\");\n $(connection).triggerHandler(events.onError, [error]);\n rejectDeferred(error);\n connection.stop();\n };\n\n connection._.startRequest = transportLogic.ajax(connection, {\n url: getAjaxUrl(connection, \"/start\"),\n success: function (result, statusText, xhr) {\n var data;\n\n try {\n data = connection._parseResponse(result);\n } catch (error) {\n triggerStartError(signalR._.error(\n signalR._.format(signalR.resources.errorParsingStartResponse, result),\n error, xhr));\n return;\n }\n\n if (data.Response === \"started\") {\n onSuccess();\n } else {\n triggerStartError(signalR._.error(\n signalR._.format(signalR.resources.invalidStartResponse, result),\n null /* error */, xhr));\n }\n },\n error: function (xhr, statusText, error) {\n if (statusText !== startAbortText) {\n triggerStartError(signalR._.error(\n signalR.resources.errorDuringStartRequest,\n error, xhr));\n } else {\n // Stop has been called, no need to trigger the error handler\n // or stop the connection again with onStartError\n connection.log(\"The start request aborted because connection.stop() was called.\");\n rejectDeferred(signalR._.error(\n signalR.resources.stoppedDuringStartRequest,\n null /* error */, xhr));\n }\n }\n });\n },\n\n tryAbortStartRequest: function (connection) {\n if (connection._.startRequest) {\n // If the start request has already completed this will noop.\n connection._.startRequest.abort(startAbortText);\n delete connection._.startRequest;\n }\n },\n\n tryInitialize: function (persistentResponse, onInitialized) {\n if (persistentResponse.Initialized) {\n onInitialized();\n }\n },\n\n triggerReceived: function (connection, data) {\n if (!connection._.connectingMessageBuffer.tryBuffer(data)) {\n $(connection).triggerHandler(events.onReceived, [data]);\n }\n },\n\n processMessages: function (connection, minData, onInitialized) {\n var data;\n\n // Update the last message time stamp\n transportLogic.markLastMessage(connection);\n\n if (minData) {\n data = transportLogic.maximizePersistentResponse(minData);\n\n transportLogic.updateGroups(connection, data.GroupsToken);\n\n if (data.MessageId) {\n connection.messageId = data.MessageId;\n }\n\n if (data.Messages) {\n $.each(data.Messages, function (index, message) {\n transportLogic.triggerReceived(connection, message);\n });\n\n transportLogic.tryInitialize(data, onInitialized);\n }\n }\n },\n\n monitorKeepAlive: function (connection) {\n var keepAliveData = connection._.keepAliveData;\n\n // If we haven't initiated the keep alive timeouts then we need to\n if (!keepAliveData.monitoring) {\n keepAliveData.monitoring = true;\n\n transportLogic.markLastMessage(connection);\n\n // Save the function so we can unbind it on stop\n connection._.keepAliveData.reconnectKeepAliveUpdate = function () {\n // Mark a new message so that keep alive doesn't time out connections\n transportLogic.markLastMessage(connection);\n };\n\n // Update Keep alive on reconnect\n $(connection).bind(events.onReconnect, connection._.keepAliveData.reconnectKeepAliveUpdate);\n\n connection.log(\"Now monitoring keep alive with a warning timeout of \" + keepAliveData.timeoutWarning + \" and a connection lost timeout of \" + keepAliveData.timeout + \".\");\n } else {\n connection.log(\"Tried to monitor keep alive but it's already being monitored.\");\n }\n },\n\n stopMonitoringKeepAlive: function (connection) {\n var keepAliveData = connection._.keepAliveData;\n\n // Only attempt to stop the keep alive monitoring if its being monitored\n if (keepAliveData.monitoring) {\n // Stop monitoring\n keepAliveData.monitoring = false;\n\n // Remove the updateKeepAlive function from the reconnect event\n $(connection).unbind(events.onReconnect, connection._.keepAliveData.reconnectKeepAliveUpdate);\n\n // Clear all the keep alive data\n connection._.keepAliveData = {};\n connection.log(\"Stopping the monitoring of the keep alive.\");\n }\n },\n\n startHeartbeat: function (connection) {\n connection._.lastActiveAt = new Date().getTime();\n beat(connection);\n },\n\n markLastMessage: function (connection) {\n connection._.lastMessageAt = new Date().getTime();\n },\n\n markActive: function (connection) {\n if (transportLogic.verifyLastActive(connection)) {\n connection._.lastActiveAt = new Date().getTime();\n return true;\n }\n\n return false;\n },\n\n isConnectedOrReconnecting: function (connection) {\n return connection.state === signalR.connectionState.connected ||\n connection.state === signalR.connectionState.reconnecting;\n },\n\n ensureReconnectingState: function (connection) {\n if (changeState(connection,\n signalR.connectionState.connected,\n signalR.connectionState.reconnecting) === true) {\n $(connection).triggerHandler(events.onReconnecting);\n }\n return connection.state === signalR.connectionState.reconnecting;\n },\n\n clearReconnectTimeout: function (connection) {\n if (connection && connection._.reconnectTimeout) {\n window.clearTimeout(connection._.reconnectTimeout);\n delete connection._.reconnectTimeout;\n }\n },\n\n verifyLastActive: function (connection) {\n if (new Date().getTime() - connection._.lastActiveAt >= connection.reconnectWindow) {\n var message = signalR._.format(signalR.resources.reconnectWindowTimeout, new Date(connection._.lastActiveAt), connection.reconnectWindow);\n connection.log(message);\n $(connection).triggerHandler(events.onError, [signalR._.error(message, /* source */ \"TimeoutException\")]);\n connection.stop(/* async */ false, /* notifyServer */ false);\n return false;\n }\n\n return true;\n },\n\n reconnect: function (connection, transportName) {\n var transport = signalR.transports[transportName];\n\n // We should only set a reconnectTimeout if we are currently connected\n // and a reconnectTimeout isn't already set.\n if (transportLogic.isConnectedOrReconnecting(connection) && !connection._.reconnectTimeout) {\n // Need to verify before the setTimeout occurs because an application sleep could occur during the setTimeout duration.\n if (!transportLogic.verifyLastActive(connection)) {\n return;\n }\n\n connection._.reconnectTimeout = window.setTimeout(function () {\n if (!transportLogic.verifyLastActive(connection)) {\n return;\n }\n\n transport.stop(connection);\n\n if (transportLogic.ensureReconnectingState(connection)) {\n connection.log(transportName + \" reconnecting.\");\n transport.start(connection);\n }\n }, connection.reconnectDelay);\n }\n },\n\n handleParseFailure: function (connection, result, error, onFailed, context) {\n // If we're in the initialization phase trigger onFailed, otherwise stop the connection.\n if (connection.state === signalR.connectionState.connecting) {\n connection.log(\"Failed to parse server response while attempting to connect.\");\n onFailed();\n } else {\n $(connection).triggerHandler(events.onError, [\n signalR._.transportError(\n signalR._.format(signalR.resources.parseFailed, result),\n connection.transport,\n error,\n context)]);\n connection.stop();\n }\n },\n\n foreverFrame: {\n count: 0,\n connections: {}\n }\n };\n\n}(window.jQuery, window));\n/* jquery.signalR.transports.webSockets.js */\n// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.\n\n/*global window:false */\n/// \n\n(function ($, window, undefined) {\n\n var signalR = $.signalR,\n events = $.signalR.events,\n changeState = $.signalR.changeState,\n transportLogic = signalR.transports._logic;\n\n signalR.transports.webSockets = {\n name: \"webSockets\",\n\n supportsKeepAlive: function () {\n return true;\n },\n\n send: function (connection, data) {\n var payload = transportLogic.stringifySend(connection, data);\n\n try {\n connection.socket.send(payload);\n } catch (ex) {\n $(connection).triggerHandler(events.onError,\n [signalR._.transportError(\n signalR.resources.webSocketsInvalidState,\n connection.transport,\n ex,\n connection.socket\n ),\n data]);\n }\n },\n\n start: function (connection, onSuccess, onFailed) {\n var url,\n opened = false,\n that = this,\n reconnecting = !onSuccess,\n $connection = $(connection);\n\n if (!window.WebSocket) {\n onFailed();\n return;\n }\n\n if (!connection.socket) {\n if (connection.webSocketServerUrl) {\n url = connection.webSocketServerUrl;\n } else {\n url = connection.wsProtocol + connection.host;\n }\n\n url += transportLogic.getUrl(connection, this.name, reconnecting);\n\n connection.log(\"Connecting to websocket endpoint '\" + url + \"'.\");\n connection.socket = new window.WebSocket(url);\n\n connection.socket.onopen = function () {\n opened = true;\n connection.log(\"Websocket opened.\");\n\n transportLogic.clearReconnectTimeout(connection);\n\n if (changeState(connection,\n signalR.connectionState.reconnecting,\n signalR.connectionState.connected) === true) {\n $connection.triggerHandler(events.onReconnect);\n }\n };\n\n connection.socket.onclose = function (event) {\n // Only handle a socket close if the close is from the current socket.\n // Sometimes on disconnect the server will push down an onclose event\n // to an expired socket.\n\n if (this === connection.socket) {\n if (!opened) {\n if (onFailed) {\n onFailed();\n } else if (reconnecting) {\n that.reconnect(connection);\n }\n return;\n } else if (typeof event.wasClean !== \"undefined\" && event.wasClean === false) {\n // Ideally this would use the websocket.onerror handler (rather than checking wasClean in onclose) but\n // I found in some circumstances Chrome won't call onerror. This implementation seems to work on all browsers.\n $(connection).triggerHandler(events.onError, [signalR._.transportError(\n signalR.resources.webSocketClosed,\n connection.transport,\n event)]);\n connection.log(\"Unclean disconnect from websocket: \" + event.reason || \"[no reason given].\");\n } else {\n connection.log(\"Websocket closed.\");\n }\n\n that.reconnect(connection);\n }\n };\n\n connection.socket.onmessage = function (event) {\n var data;\n\n try {\n data = connection._parseResponse(event.data);\n }\n catch (error) {\n transportLogic.handleParseFailure(connection, event.data, error, onFailed, event);\n return;\n }\n\n if (data) {\n // data.M is PersistentResponse.Messages\n if ($.isEmptyObject(data) || data.M) {\n transportLogic.processMessages(connection, data, onSuccess);\n } else {\n // For websockets we need to trigger onReceived\n // for callbacks to outgoing hub calls.\n transportLogic.triggerReceived(connection, data);\n }\n }\n };\n }\n },\n\n reconnect: function (connection) {\n transportLogic.reconnect(connection, this.name);\n },\n\n lostConnection: function (connection) {\n this.reconnect(connection);\n },\n\n stop: function (connection) {\n // Don't trigger a reconnect after stopping\n transportLogic.clearReconnectTimeout(connection);\n\n if (connection.socket) {\n connection.log(\"Closing the Websocket.\");\n connection.socket.close();\n connection.socket = null;\n }\n },\n\n abort: function (connection, async) {\n transportLogic.ajaxAbort(connection, async);\n }\n };\n\n}(window.jQuery, window));\n/* jquery.signalR.transports.serverSentEvents.js */\n// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.\n\n/*global window:false */\n/// \n\n(function ($, window, undefined) {\n\n var signalR = $.signalR,\n events = $.signalR.events,\n changeState = $.signalR.changeState,\n transportLogic = signalR.transports._logic,\n clearReconnectAttemptTimeout = function (connection) {\n window.clearTimeout(connection._.reconnectAttemptTimeoutHandle);\n delete connection._.reconnectAttemptTimeoutHandle;\n };\n\n signalR.transports.serverSentEvents = {\n name: \"serverSentEvents\",\n\n supportsKeepAlive: function () {\n return true;\n },\n\n timeOut: 3000,\n\n start: function (connection, onSuccess, onFailed) {\n var that = this,\n opened = false,\n $connection = $(connection),\n reconnecting = !onSuccess,\n url;\n\n if (connection.eventSource) {\n connection.log(\"The connection already has an event source. Stopping it.\");\n connection.stop();\n }\n\n if (!window.EventSource) {\n if (onFailed) {\n connection.log(\"This browser doesn't support SSE.\");\n onFailed();\n }\n return;\n }\n\n url = transportLogic.getUrl(connection, this.name, reconnecting);\n\n try {\n connection.log(\"Attempting to connect to SSE endpoint '\" + url + \"'.\");\n connection.eventSource = new window.EventSource(url, { withCredentials: connection.withCredentials });\n }\n catch (e) {\n connection.log(\"EventSource failed trying to connect with error \" + e.Message + \".\");\n if (onFailed) {\n // The connection failed, call the failed callback\n onFailed();\n } else {\n $connection.triggerHandler(events.onError, [signalR._.transportError(signalR.resources.eventSourceFailedToConnect, connection.transport, e)]);\n if (reconnecting) {\n // If we were reconnecting, rather than doing initial connect, then try reconnect again\n that.reconnect(connection);\n }\n }\n return;\n }\n\n if (reconnecting) {\n connection._.reconnectAttemptTimeoutHandle = window.setTimeout(function () {\n if (opened === false) {\n // If we're reconnecting and the event source is attempting to connect,\n // don't keep retrying. This causes duplicate connections to spawn.\n if (connection.eventSource.readyState !== window.EventSource.OPEN) {\n // If we were reconnecting, rather than doing initial connect, then try reconnect again\n that.reconnect(connection);\n }\n }\n },\n that.timeOut);\n }\n\n connection.eventSource.addEventListener(\"open\", function (e) {\n connection.log(\"EventSource connected.\");\n\n clearReconnectAttemptTimeout(connection);\n transportLogic.clearReconnectTimeout(connection);\n\n if (opened === false) {\n opened = true;\n\n if (changeState(connection,\n signalR.connectionState.reconnecting,\n signalR.connectionState.connected) === true) {\n $connection.triggerHandler(events.onReconnect);\n }\n }\n }, false);\n\n connection.eventSource.addEventListener(\"message\", function (e) {\n var res;\n\n // process messages\n if (e.data === \"initialized\") {\n return;\n }\n\n try {\n res = connection._parseResponse(e.data);\n }\n catch (error) {\n transportLogic.handleParseFailure(connection, e.data, error, onFailed, e);\n return;\n }\n\n transportLogic.processMessages(connection, res, onSuccess);\n }, false);\n\n connection.eventSource.addEventListener(\"error\", function (e) {\n // Only handle an error if the error is from the current Event Source.\n // Sometimes on disconnect the server will push down an error event\n // to an expired Event Source.\n if (this !== connection.eventSource) {\n return;\n }\n\n if (!opened) {\n if (onFailed) {\n onFailed();\n }\n\n return;\n }\n\n connection.log(\"EventSource readyState: \" + connection.eventSource.readyState + \".\");\n\n if (e.eventPhase === window.EventSource.CLOSED) {\n // We don't use the EventSource's native reconnect function as it\n // doesn't allow us to change the URL when reconnecting. We need\n // to change the URL to not include the /connect suffix, and pass\n // the last message id we received.\n connection.log(\"EventSource reconnecting due to the server connection ending.\");\n that.reconnect(connection);\n } else {\n // connection error\n connection.log(\"EventSource error.\");\n $connection.triggerHandler(events.onError, [signalR._.transportError(signalR.resources.eventSourceError, connection.transport, e)]);\n }\n }, false);\n },\n\n reconnect: function (connection) {\n transportLogic.reconnect(connection, this.name);\n },\n\n lostConnection: function (connection) {\n this.reconnect(connection);\n },\n\n send: function (connection, data) {\n transportLogic.ajaxSend(connection, data);\n },\n\n stop: function (connection) {\n // Don't trigger a reconnect after stopping\n clearReconnectAttemptTimeout(connection);\n transportLogic.clearReconnectTimeout(connection);\n\n if (connection && connection.eventSource) {\n connection.log(\"EventSource calling close().\");\n connection.eventSource.close();\n connection.eventSource = null;\n delete connection.eventSource;\n }\n },\n\n abort: function (connection, async) {\n transportLogic.ajaxAbort(connection, async);\n }\n };\n\n}(window.jQuery, window));\n/* jquery.signalR.transports.foreverFrame.js */\n// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.\n\n/*global window:false */\n/// \n\n(function ($, window, undefined) {\n\n var signalR = $.signalR,\n events = $.signalR.events,\n changeState = $.signalR.changeState,\n transportLogic = signalR.transports._logic,\n createFrame = function () {\n var frame = window.document.createElement(\"iframe\");\n frame.setAttribute(\"style\", \"position:absolute;top:0;left:0;width:0;height:0;visibility:hidden;\");\n return frame;\n },\n // Used to prevent infinite loading icon spins in older versions of ie\n // We build this object inside a closure so we don't pollute the rest of \n // the foreverFrame transport with unnecessary functions/utilities.\n loadPreventer = (function () {\n var loadingFixIntervalId = null,\n loadingFixInterval = 1000,\n attachedTo = 0;\n\n return {\n prevent: function () {\n // Prevent additional iframe removal procedures from newer browsers\n if (signalR._.ieVersion <= 8) {\n // We only ever want to set the interval one time, so on the first attachedTo\n if (attachedTo === 0) {\n // Create and destroy iframe every 3 seconds to prevent loading icon, super hacky\n loadingFixIntervalId = window.setInterval(function () {\n var tempFrame = createFrame();\n\n window.document.body.appendChild(tempFrame);\n window.document.body.removeChild(tempFrame);\n\n tempFrame = null;\n }, loadingFixInterval);\n }\n\n attachedTo++;\n }\n },\n cancel: function () {\n // Only clear the interval if there's only one more object that the loadPreventer is attachedTo\n if (attachedTo === 1) {\n window.clearInterval(loadingFixIntervalId);\n }\n\n if (attachedTo > 0) {\n attachedTo--;\n }\n }\n };\n })();\n\n signalR.transports.foreverFrame = {\n name: \"foreverFrame\",\n\n supportsKeepAlive: function () {\n return true;\n },\n\n // Added as a value here so we can create tests to verify functionality\n iframeClearThreshold: 50,\n\n start: function (connection, onSuccess, onFailed) {\n var that = this,\n frameId = (transportLogic.foreverFrame.count += 1),\n url,\n frame = createFrame(),\n frameLoadHandler = function () {\n connection.log(\"Forever frame iframe finished loading and is no longer receiving messages.\");\n that.reconnect(connection);\n };\n\n if (window.EventSource) {\n // If the browser supports SSE, don't use Forever Frame\n if (onFailed) {\n connection.log(\"This browser supports SSE, skipping Forever Frame.\");\n onFailed();\n }\n return;\n }\n\n frame.setAttribute(\"data-signalr-connection-id\", connection.id);\n\n // Start preventing loading icon\n // This will only perform work if the loadPreventer is not attached to another connection.\n loadPreventer.prevent();\n\n // Build the url\n url = transportLogic.getUrl(connection, this.name);\n url += \"&frameId=\" + frameId;\n\n // Set body prior to setting URL to avoid caching issues.\n window.document.body.appendChild(frame);\n\n connection.log(\"Binding to iframe's load event.\");\n\n if (frame.addEventListener) {\n frame.addEventListener(\"load\", frameLoadHandler, false);\n } else if (frame.attachEvent) {\n frame.attachEvent(\"onload\", frameLoadHandler);\n }\n\n frame.src = url;\n transportLogic.foreverFrame.connections[frameId] = connection;\n\n connection.frame = frame;\n connection.frameId = frameId;\n\n if (onSuccess) {\n connection.onSuccess = function () {\n connection.log(\"Iframe transport started.\");\n onSuccess();\n };\n }\n },\n\n reconnect: function (connection) {\n var that = this;\n\n // Need to verify connection state and verify before the setTimeout occurs because an application sleep could occur during the setTimeout duration.\n if (transportLogic.isConnectedOrReconnecting(connection) && transportLogic.verifyLastActive(connection)) {\n window.setTimeout(function () {\n // Verify that we're ok to reconnect.\n if (!transportLogic.verifyLastActive(connection)) {\n return;\n }\n\n if (connection.frame && transportLogic.ensureReconnectingState(connection)) {\n var frame = connection.frame,\n src = transportLogic.getUrl(connection, that.name, true) + \"&frameId=\" + connection.frameId;\n connection.log(\"Updating iframe src to '\" + src + \"'.\");\n frame.src = src;\n }\n }, connection.reconnectDelay);\n }\n },\n\n lostConnection: function (connection) {\n this.reconnect(connection);\n },\n\n send: function (connection, data) {\n transportLogic.ajaxSend(connection, data);\n },\n\n receive: function (connection, data) {\n var cw,\n body,\n response;\n\n if (connection.json !== connection._originalJson) {\n // If there's a custom JSON parser configured then serialize the object\n // using the original (browser) JSON parser and then deserialize it using\n // the custom parser (connection._parseResponse does that). This is so we\n // can easily send the response from the server as \"raw\" JSON but still \n // support custom JSON deserialization in the browser.\n data = connection._originalJson.stringify(data);\n }\n\n response = connection._parseResponse(data);\n\n transportLogic.processMessages(connection, response, connection.onSuccess);\n\n // Protect against connection stopping from a callback trigger within the processMessages above.\n if (connection.state === $.signalR.connectionState.connected) {\n // Delete the script & div elements\n connection.frameMessageCount = (connection.frameMessageCount || 0) + 1;\n if (connection.frameMessageCount > signalR.transports.foreverFrame.iframeClearThreshold) {\n connection.frameMessageCount = 0;\n cw = connection.frame.contentWindow || connection.frame.contentDocument;\n if (cw && cw.document && cw.document.body) {\n body = cw.document.body;\n\n // Remove all the child elements from the iframe's body to conserver memory\n while (body.firstChild) {\n body.removeChild(body.firstChild);\n }\n }\n }\n }\n },\n\n stop: function (connection) {\n var cw = null;\n\n // Stop attempting to prevent loading icon\n loadPreventer.cancel();\n\n if (connection.frame) {\n if (connection.frame.stop) {\n connection.frame.stop();\n } else {\n try {\n cw = connection.frame.contentWindow || connection.frame.contentDocument;\n if (cw.document && cw.document.execCommand) {\n cw.document.execCommand(\"Stop\");\n }\n }\n catch (e) {\n connection.log(\"Error occured when stopping foreverFrame transport. Message = \" + e.message + \".\");\n }\n }\n\n // Ensure the iframe is where we left it\n if (connection.frame.parentNode === window.document.body) {\n window.document.body.removeChild(connection.frame);\n }\n\n delete transportLogic.foreverFrame.connections[connection.frameId];\n connection.frame = null;\n connection.frameId = null;\n delete connection.frame;\n delete connection.frameId;\n delete connection.onSuccess;\n delete connection.frameMessageCount;\n connection.log(\"Stopping forever frame.\");\n }\n },\n\n abort: function (connection, async) {\n transportLogic.ajaxAbort(connection, async);\n },\n\n getConnection: function (id) {\n return transportLogic.foreverFrame.connections[id];\n },\n\n started: function (connection) {\n if (changeState(connection,\n signalR.connectionState.reconnecting,\n signalR.connectionState.connected) === true) {\n // If there's no onSuccess handler we assume this is a reconnect\n $(connection).triggerHandler(events.onReconnect);\n }\n }\n };\n\n}(window.jQuery, window));\n/* jquery.signalR.transports.longPolling.js */\n// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.\n\n/*global window:false */\n/// \n\n(function ($, window, undefined) {\n\n var signalR = $.signalR,\n events = $.signalR.events,\n changeState = $.signalR.changeState,\n isDisconnecting = $.signalR.isDisconnecting,\n transportLogic = signalR.transports._logic;\n\n signalR.transports.longPolling = {\n name: \"longPolling\",\n\n supportsKeepAlive: function () {\n return false;\n },\n\n reconnectDelay: 3000,\n\n start: function (connection, onSuccess, onFailed) {\n /// Starts the long polling connection\n /// The SignalR connection to start\n var that = this,\n fireConnect = function () {\n fireConnect = $.noop;\n\n // Reset onFailed to null because it shouldn't be called again\n onFailed = null;\n\n connection.log(\"LongPolling connected.\");\n onSuccess();\n },\n tryFailConnect = function () {\n if (onFailed) {\n onFailed();\n onFailed = null;\n connection.log(\"LongPolling failed to connect.\");\n return true;\n }\n\n return false;\n },\n privateData = connection._,\n reconnectErrors = 0,\n fireReconnected = function (instance) {\n window.clearTimeout(privateData.reconnectTimeoutId);\n privateData.reconnectTimeoutId = null;\n\n if (changeState(instance,\n signalR.connectionState.reconnecting,\n signalR.connectionState.connected) === true) {\n // Successfully reconnected!\n instance.log(\"Raising the reconnect event\");\n $(instance).triggerHandler(events.onReconnect);\n }\n },\n // 1 hour\n maxFireReconnectedTimeout = 3600000;\n\n if (connection.pollXhr) {\n connection.log(\"Polling xhr requests already exists, aborting.\");\n connection.stop();\n }\n\n connection.messageId = null;\n\n privateData.reconnectTimeoutId = null;\n\n privateData.pollTimeoutId = window.setTimeout(function () {\n (function poll(instance, raiseReconnect) {\n var messageId = instance.messageId,\n connect = (messageId === null),\n reconnecting = !connect,\n polling = !raiseReconnect,\n url = transportLogic.getUrl(instance, that.name, reconnecting, polling);\n\n // If we've disconnected during the time we've tried to re-instantiate the poll then stop.\n if (isDisconnecting(instance) === true) {\n return;\n }\n\n connection.log(\"Opening long polling request to '\" + url + \"'.\");\n instance.pollXhr = transportLogic.ajax(connection, {\n xhrFields: {\n onprogress: function () {\n transportLogic.markLastMessage(connection);\n }\n },\n url: url,\n timeout: connection._.pollTimeout,\n success: function (result) {\n var minData,\n delay = 0,\n data,\n shouldReconnect;\n\n connection.log(\"Long poll complete.\");\n\n // Reset our reconnect errors so if we transition into a reconnecting state again we trigger\n // reconnected quickly\n reconnectErrors = 0;\n\n try {\n // Remove any keep-alives from the beginning of the result\n minData = connection._parseResponse(result);\n }\n catch (error) {\n transportLogic.handleParseFailure(instance, result, error, tryFailConnect, instance.pollXhr);\n return;\n }\n\n // If there's currently a timeout to trigger reconnect, fire it now before processing messages\n if (privateData.reconnectTimeoutId !== null) {\n fireReconnected(instance);\n }\n\n if (minData) {\n data = transportLogic.maximizePersistentResponse(minData);\n }\n\n transportLogic.processMessages(instance, minData, fireConnect);\n\n if (data &&\n $.type(data.LongPollDelay) === \"number\") {\n delay = data.LongPollDelay;\n }\n\n if (data && data.Disconnect) {\n return;\n }\n\n if (isDisconnecting(instance) === true) {\n return;\n }\n\n shouldReconnect = data && data.ShouldReconnect;\n if (shouldReconnect) {\n // Transition into the reconnecting state\n // If this fails then that means that the user transitioned the connection into a invalid state in processMessages.\n if (!transportLogic.ensureReconnectingState(instance)) {\n return;\n }\n }\n\n // We never want to pass a raiseReconnect flag after a successful poll. This is handled via the error function\n if (delay > 0) {\n privateData.pollTimeoutId = window.setTimeout(function () {\n poll(instance, shouldReconnect);\n }, delay);\n } else {\n poll(instance, shouldReconnect);\n }\n },\n\n error: function (data, textStatus) {\n // Stop trying to trigger reconnect, connection is in an error state\n // If we're not in the reconnect state this will noop\n window.clearTimeout(privateData.reconnectTimeoutId);\n privateData.reconnectTimeoutId = null;\n\n if (textStatus === \"abort\") {\n connection.log(\"Aborted xhr request.\");\n return;\n }\n\n if (!tryFailConnect()) {\n\n // Increment our reconnect errors, we assume all errors to be reconnect errors\n // In the case that it's our first error this will cause Reconnect to be fired\n // after 1 second due to reconnectErrors being = 1.\n reconnectErrors++;\n\n if (connection.state !== signalR.connectionState.reconnecting) {\n connection.log(\"An error occurred using longPolling. Status = \" + textStatus + \". Response = \" + data.responseText + \".\");\n $(instance).triggerHandler(events.onError, [signalR._.transportError(signalR.resources.longPollFailed, connection.transport, data, instance.pollXhr)]);\n }\n\n // We check the state here to verify that we're not in an invalid state prior to verifying Reconnect.\n // If we're not in connected or reconnecting then the next ensureReconnectingState check will fail and will return.\n // Therefore we don't want to change that failure code path.\n if ((connection.state === signalR.connectionState.connected ||\n connection.state === signalR.connectionState.reconnecting) &&\n !transportLogic.verifyLastActive(connection)) {\n return;\n }\n\n // Transition into the reconnecting state\n // If this fails then that means that the user transitioned the connection into the disconnected or connecting state within the above error handler trigger.\n if (!transportLogic.ensureReconnectingState(instance)) {\n return;\n }\n\n // Call poll with the raiseReconnect flag as true after the reconnect delay\n privateData.pollTimeoutId = window.setTimeout(function () {\n poll(instance, true);\n }, that.reconnectDelay);\n }\n }\n });\n\n // This will only ever pass after an error has occured via the poll ajax procedure.\n if (reconnecting && raiseReconnect === true) {\n // We wait to reconnect depending on how many times we've failed to reconnect.\n // This is essentially a heuristic that will exponentially increase in wait time before\n // triggering reconnected. This depends on the \"error\" handler of Poll to cancel this \n // timeout if it triggers before the Reconnected event fires.\n // The Math.min at the end is to ensure that the reconnect timeout does not overflow.\n privateData.reconnectTimeoutId = window.setTimeout(function () { fireReconnected(instance); }, Math.min(1000 * (Math.pow(2, reconnectErrors) - 1), maxFireReconnectedTimeout));\n }\n }(connection));\n }, 250); // Have to delay initial poll so Chrome doesn't show loader spinner in tab\n },\n\n lostConnection: function (connection) {\n if (connection.pollXhr) {\n connection.pollXhr.abort(\"lostConnection\");\n }\n },\n\n send: function (connection, data) {\n transportLogic.ajaxSend(connection, data);\n },\n\n stop: function (connection) {\n /// Stops the long polling connection\n /// The SignalR connection to stop\n\n window.clearTimeout(connection._.pollTimeoutId);\n window.clearTimeout(connection._.reconnectTimeoutId);\n\n delete connection._.pollTimeoutId;\n delete connection._.reconnectTimeoutId;\n\n if (connection.pollXhr) {\n connection.pollXhr.abort();\n connection.pollXhr = null;\n delete connection.pollXhr;\n }\n },\n\n abort: function (connection, async) {\n transportLogic.ajaxAbort(connection, async);\n }\n };\n\n}(window.jQuery, window));\n/* jquery.signalR.hubs.js */\n// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.\n\n/*global window:false */\n/// \n\n(function ($, window, undefined) {\n\n var eventNamespace = \".hubProxy\",\n signalR = $.signalR;\n\n function makeEventName(event) {\n return event + eventNamespace;\n }\n\n // Equivalent to Array.prototype.map\n function map(arr, fun, thisp) {\n var i,\n length = arr.length,\n result = [];\n for (i = 0; i < length; i += 1) {\n if (arr.hasOwnProperty(i)) {\n result[i] = fun.call(thisp, arr[i], i, arr);\n }\n }\n return result;\n }\n\n function getArgValue(a) {\n return $.isFunction(a) ? null : ($.type(a) === \"undefined\" ? null : a);\n }\n\n function hasMembers(obj) {\n for (var key in obj) {\n // If we have any properties in our callback map then we have callbacks and can exit the loop via return\n if (obj.hasOwnProperty(key)) {\n return true;\n }\n }\n\n return false;\n }\n\n function clearInvocationCallbacks(connection, error) {\n /// \n var callbacks = connection._.invocationCallbacks,\n callback;\n\n if (hasMembers(callbacks)) {\n connection.log(\"Clearing hub invocation callbacks with error: \" + error + \".\");\n }\n\n // Reset the callback cache now as we have a local var referencing it\n connection._.invocationCallbackId = 0;\n delete connection._.invocationCallbacks;\n connection._.invocationCallbacks = {};\n\n // Loop over the callbacks and invoke them.\n // We do this using a local var reference and *after* we've cleared the cache\n // so that if a fail callback itself tries to invoke another method we don't \n // end up with its callback in the list we're looping over.\n for (var callbackId in callbacks) {\n callback = callbacks[callbackId];\n callback.method.call(callback.scope, { E: error });\n }\n }\n\n // hubProxy\n function hubProxy(hubConnection, hubName) {\n /// \n /// Creates a new proxy object for the given hub connection that can be used to invoke\n /// methods on server hubs and handle client method invocation requests from the server.\n /// \n return new hubProxy.fn.init(hubConnection, hubName);\n }\n\n hubProxy.fn = hubProxy.prototype = {\n init: function (connection, hubName) {\n this.state = {};\n this.connection = connection;\n this.hubName = hubName;\n this._ = {\n callbackMap: {}\n };\n },\n\n constructor: hubProxy,\n\n hasSubscriptions: function () {\n return hasMembers(this._.callbackMap);\n },\n\n on: function (eventName, callback) {\n /// Wires up a callback to be invoked when a invocation request is received from the server hub.\n /// The name of the hub event to register the callback for.\n /// The callback to be invoked.\n var that = this,\n callbackMap = that._.callbackMap;\n\n // Normalize the event name to lowercase\n eventName = eventName.toLowerCase();\n\n // If there is not an event registered for this callback yet we want to create its event space in the callback map.\n if (!callbackMap[eventName]) {\n callbackMap[eventName] = {};\n }\n\n // Map the callback to our encompassed function\n callbackMap[eventName][callback] = function (e, data) {\n callback.apply(that, data);\n };\n\n $(that).bind(makeEventName(eventName), callbackMap[eventName][callback]);\n\n return that;\n },\n\n off: function (eventName, callback) {\n /// Removes the callback invocation request from the server hub for the given event name.\n /// The name of the hub event to unregister the callback for.\n /// The callback to be invoked.\n var that = this,\n callbackMap = that._.callbackMap,\n callbackSpace;\n\n // Normalize the event name to lowercase\n eventName = eventName.toLowerCase();\n\n callbackSpace = callbackMap[eventName];\n\n // Verify that there is an event space to unbind\n if (callbackSpace) {\n // Only unbind if there's an event bound with eventName and a callback with the specified callback\n if (callbackSpace[callback]) {\n $(that).unbind(makeEventName(eventName), callbackSpace[callback]);\n\n // Remove the callback from the callback map\n delete callbackSpace[callback];\n\n // Check if there are any members left on the event, if not we need to destroy it.\n if (!hasMembers(callbackSpace)) {\n delete callbackMap[eventName];\n }\n } else if (!callback) { // Check if we're removing the whole event and we didn't error because of an invalid callback\n $(that).unbind(makeEventName(eventName));\n\n delete callbackMap[eventName];\n }\n }\n\n return that;\n },\n\n invoke: function (methodName) {\n /// Invokes a server hub method with the given arguments.\n /// The name of the server hub method.\n\n var that = this,\n connection = that.connection,\n args = $.makeArray(arguments).slice(1),\n argValues = map(args, getArgValue),\n data = { H: that.hubName, M: methodName, A: argValues, I: connection._.invocationCallbackId },\n d = $.Deferred(),\n callback = function (minResult) {\n var result = that._maximizeHubResponse(minResult),\n source,\n error;\n\n // Update the hub state\n $.extend(that.state, result.State);\n\n if (result.Progress) {\n if (d.notifyWith) {\n // Progress is only supported in jQuery 1.7+\n d.notifyWith(that, [result.Progress.Data]);\n } else if(!connection._.progressjQueryVersionLogged) {\n connection.log(\"A hub method invocation progress update was received but the version of jQuery in use (\" + $.prototype.jquery + \") does not support progress updates. Upgrade to jQuery 1.7+ to receive progress notifications.\");\n connection._.progressjQueryVersionLogged = true;\n }\n } else if (result.Error) {\n // Server hub method threw an exception, log it & reject the deferred\n if (result.StackTrace) {\n connection.log(result.Error + \"\\n\" + result.StackTrace + \".\");\n }\n\n // result.ErrorData is only set if a HubException was thrown\n source = result.IsHubException ? \"HubException\" : \"Exception\";\n error = signalR._.error(result.Error, source);\n error.data = result.ErrorData;\n\n connection.log(that.hubName + \".\" + methodName + \" failed to execute. Error: \" + error.message);\n d.rejectWith(that, [error]);\n } else {\n // Server invocation succeeded, resolve the deferred\n connection.log(\"Invoked \" + that.hubName + \".\" + methodName);\n d.resolveWith(that, [result.Result]);\n }\n };\n\n connection._.invocationCallbacks[connection._.invocationCallbackId.toString()] = { scope: that, method: callback };\n connection._.invocationCallbackId += 1;\n\n if (!$.isEmptyObject(that.state)) {\n data.S = that.state;\n }\n\n connection.log(\"Invoking \" + that.hubName + \".\" + methodName);\n connection.send(data);\n\n return d.promise();\n },\n\n _maximizeHubResponse: function (minHubResponse) {\n return {\n State: minHubResponse.S,\n Result: minHubResponse.R,\n Progress: minHubResponse.P ? {\n Id: minHubResponse.P.I,\n Data: minHubResponse.P.D\n } : null,\n Id: minHubResponse.I,\n IsHubException: minHubResponse.H,\n Error: minHubResponse.E,\n StackTrace: minHubResponse.T,\n ErrorData: minHubResponse.D\n };\n }\n };\n\n hubProxy.fn.init.prototype = hubProxy.fn;\n\n // hubConnection\n function hubConnection(url, options) {\n /// Creates a new hub connection.\n /// [Optional] The hub route url, defaults to \"/signalr\".\n /// [Optional] Settings to use when creating the hubConnection.\n var settings = {\n qs: null,\n logging: false,\n useDefaultPath: true\n };\n\n $.extend(settings, options);\n\n if (!url || settings.useDefaultPath) {\n url = (url || \"\") + \"/signalr\";\n }\n return new hubConnection.fn.init(url, settings);\n }\n\n hubConnection.fn = hubConnection.prototype = $.connection();\n\n hubConnection.fn.init = function (url, options) {\n var settings = {\n qs: null,\n logging: false,\n useDefaultPath: true\n },\n connection = this;\n\n $.extend(settings, options);\n\n // Call the base constructor\n $.signalR.fn.init.call(connection, url, settings.qs, settings.logging);\n\n // Object to store hub proxies for this connection\n connection.proxies = {};\n\n connection._.invocationCallbackId = 0;\n connection._.invocationCallbacks = {};\n\n // Wire up the received handler\n connection.received(function (minData) {\n var data, proxy, dataCallbackId, callback, hubName, eventName;\n if (!minData) {\n return;\n }\n\n // We have to handle progress updates first in order to ensure old clients that receive\n // progress updates enter the return value branch and then no-op when they can't find\n // the callback in the map (because the minData.I value will not be a valid callback ID)\n if (typeof (minData.P) !== \"undefined\") {\n // Process progress notification\n dataCallbackId = minData.P.I.toString();\n callback = connection._.invocationCallbacks[dataCallbackId];\n if (callback) {\n callback.method.call(callback.scope, minData);\n }\n } else if (typeof (minData.I) !== \"undefined\") {\n // We received the return value from a server method invocation, look up callback by id and call it\n dataCallbackId = minData.I.toString();\n callback = connection._.invocationCallbacks[dataCallbackId];\n if (callback) {\n // Delete the callback from the proxy\n connection._.invocationCallbacks[dataCallbackId] = null;\n delete connection._.invocationCallbacks[dataCallbackId];\n\n // Invoke the callback\n callback.method.call(callback.scope, minData);\n }\n } else {\n data = this._maximizeClientHubInvocation(minData);\n\n // We received a client invocation request, i.e. broadcast from server hub\n connection.log(\"Triggering client hub event '\" + data.Method + \"' on hub '\" + data.Hub + \"'.\");\n\n // Normalize the names to lowercase\n hubName = data.Hub.toLowerCase();\n eventName = data.Method.toLowerCase();\n\n // Trigger the local invocation event\n proxy = this.proxies[hubName];\n\n // Update the hub state\n $.extend(proxy.state, data.State);\n $(proxy).triggerHandler(makeEventName(eventName), [data.Args]);\n }\n });\n\n connection.error(function (errData, origData) {\n var callbackId, callback;\n\n if (!origData) {\n // No original data passed so this is not a send error\n return;\n }\n\n callbackId = origData.I;\n callback = connection._.invocationCallbacks[callbackId];\n\n // Verify that there is a callback bound (could have been cleared)\n if (callback) {\n // Delete the callback\n connection._.invocationCallbacks[callbackId] = null;\n delete connection._.invocationCallbacks[callbackId];\n\n // Invoke the callback with an error to reject the promise\n callback.method.call(callback.scope, { E: errData });\n }\n });\n\n connection.reconnecting(function () {\n if (connection.transport && connection.transport.name === \"webSockets\") {\n clearInvocationCallbacks(connection, \"Connection started reconnecting before invocation result was received.\");\n }\n });\n\n connection.disconnected(function () {\n clearInvocationCallbacks(connection, \"Connection was disconnected before invocation result was received.\");\n });\n };\n\n hubConnection.fn._maximizeClientHubInvocation = function (minClientHubInvocation) {\n return {\n Hub: minClientHubInvocation.H,\n Method: minClientHubInvocation.M,\n Args: minClientHubInvocation.A,\n State: minClientHubInvocation.S\n };\n };\n\n hubConnection.fn._registerSubscribedHubs = function () {\n /// \n /// Sets the starting event to loop through the known hubs and register any new hubs \n /// that have been added to the proxy.\n /// \n var connection = this;\n\n if (!connection._subscribedToHubs) {\n connection._subscribedToHubs = true;\n connection.starting(function () {\n // Set the connection's data object with all the hub proxies with active subscriptions.\n // These proxies will receive notifications from the server.\n var subscribedHubs = [];\n\n $.each(connection.proxies, function (key) {\n if (this.hasSubscriptions()) {\n subscribedHubs.push({ name: key });\n connection.log(\"Client subscribed to hub '\" + key + \"'.\");\n }\n });\n\n if (subscribedHubs.length === 0) {\n connection.log(\"No hubs have been subscribed to. The client will not receive data from hubs. To fix, declare at least one client side function prior to connection start for each hub you wish to subscribe to.\");\n }\n\n connection.data = connection.json.stringify(subscribedHubs);\n });\n }\n };\n\n hubConnection.fn.createHubProxy = function (hubName) {\n /// \n /// Creates a new proxy object for the given hub connection that can be used to invoke\n /// methods on server hubs and handle client method invocation requests from the server.\n /// \n /// \n /// The name of the hub on the server to create the proxy for.\n /// \n\n // Normalize the name to lowercase\n hubName = hubName.toLowerCase();\n\n var proxy = this.proxies[hubName];\n if (!proxy) {\n proxy = hubProxy(this, hubName);\n this.proxies[hubName] = proxy;\n }\n\n this._registerSubscribedHubs();\n\n return proxy;\n };\n\n hubConnection.fn.init.prototype = hubConnection.fn;\n\n $.hubConnection = hubConnection;\n\n}(window.jQuery, window));\n/* jquery.signalR.version.js */\n// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.md in the project root for license information.\n\n/*global window:false */\n/// \n(function ($, undefined) {\n $.signalR.version = \"2.1.2\";\n}(window.jQuery));\n","/* angular-moment.js / v0.8.2 / (c) 2013, 2014 Uri Shaked / MIT Licence */\n\n/* global define */\n\n(function () {\n\t'use strict';\n\n\tfunction angularMoment(angular, moment) {\n\n\t\t/**\n\t\t * @ngdoc overview\n\t\t * @name angularMoment\n\t\t *\n\t\t * @description\n\t\t * angularMoment module provides moment.js functionality for angular.js apps.\n\t\t */\n\t\treturn angular.module('angularMoment', [])\n\n\t\t/**\n\t\t * @ngdoc object\n\t\t * @name angularMoment.config:angularMomentConfig\n\t\t *\n\t\t * @description\n\t\t * Common configuration of the angularMoment module\n\t\t */\n\t\t\t.constant('angularMomentConfig', {\n\t\t\t\t/**\n\t\t\t\t * @ngdoc property\n\t\t\t\t * @name angularMoment.config.angularMomentConfig#preprocess\n\t\t\t\t * @propertyOf angularMoment.config:angularMomentConfig\n\t\t\t\t * @returns {string} The default preprocessor to apply\n\t\t\t\t *\n\t\t\t\t * @description\n\t\t\t\t * Defines a default preprocessor to apply (e.g. 'unix', 'etc', ...). The default value is null,\n\t\t\t\t * i.e. no preprocessor will be applied.\n\t\t\t\t */\n\t\t\t\tpreprocess: null, // e.g. 'unix', 'utc', ...\n\n\t\t\t\t/**\n\t\t\t\t * @ngdoc property\n\t\t\t\t * @name angularMoment.config.angularMomentConfig#timezone\n\t\t\t\t * @propertyOf angularMoment.config:angularMomentConfig\n\t\t\t\t * @returns {string} The default timezone\n\t\t\t\t *\n\t\t\t\t * @description\n\t\t\t\t * The default timezone (e.g. 'Europe/London'). Empty string by default (does not apply\n\t\t\t\t * any timezone shift).\n\t\t\t\t */\n\t\t\t\ttimezone: '',\n\n\t\t\t\t/**\n\t\t\t\t * @ngdoc property\n\t\t\t\t * @name angularMoment.config.angularMomentConfig#format\n\t\t\t\t * @propertyOf angularMoment.config:angularMomentConfig\n\t\t\t\t * @returns {string} The pre-conversion format of the date\n\t\t\t\t *\n\t\t\t\t * @description\n\t\t\t\t * Specify the format of the input date. Essentially it's a\n\t\t\t\t * default and saves you from specifying a format in every\n\t\t\t\t * element. Overridden by element attr. Null by default.\n\t\t\t\t */\n\t\t\t\tformat: null\n\t\t\t})\n\n\t\t/**\n\t\t * @ngdoc object\n\t\t * @name angularMoment.object:moment\n\t\t *\n\t\t * @description\n\t\t * moment global (as provided by the moment.js library)\n\t\t */\n\t\t\t.constant('moment', moment)\n\n\t\t/**\n\t\t * @ngdoc object\n\t\t * @name angularMoment.config:amTimeAgoConfig\n\t\t * @module angularMoment\n\t\t *\n\t\t * @description\n\t\t * configuration specific to the amTimeAgo directive\n\t\t */\n\t\t\t.constant('amTimeAgoConfig', {\n\t\t\t\t/**\n\t\t\t\t * @ngdoc property\n\t\t\t\t * @name angularMoment.config.amTimeAgoConfig#withoutSuffix\n\t\t\t\t * @propertyOf angularMoment.config:amTimeAgoConfig\n\t\t\t\t * @returns {boolean} Whether to include a suffix in am-time-ago directive\n\t\t\t\t *\n\t\t\t\t * @description\n\t\t\t\t * Defaults to false.\n\t\t\t\t */\n\t\t\t\twithoutSuffix: false,\n\n\t\t\t\t/**\n\t\t\t\t * @ngdoc property\n\t\t\t\t * @name angularMoment.config.amTimeAgoConfig#serverTime\n\t\t\t\t * @propertyOf angularMoment.config:amTimeAgoConfig\n\t\t\t\t * @returns {number} Server time in milliseconds since the epoch\n\t\t\t\t *\n\t\t\t\t * @description\n\t\t\t\t * If set, time ago will be calculated relative to the given value.\n\t\t\t\t * If null, local time will be used. Defaults to null.\n\t\t\t\t */\n\t\t\t\tserverTime: null,\n\n\t\t\t\t/**\n\t\t\t\t * @ngdoc property\n\t\t\t\t * @name angularMoment.config.amTimeAgoConfig#format\n\t\t\t\t * @propertyOf angularMoment.config:amTimeAgoConfig\n\t\t\t\t * @returns {string} The format of the date to be displayed in the title of the element. If null,\n\t\t\t\t * \t\tthe directive set the title of the element.\n\t\t\t\t *\n\t\t\t\t * @description\n\t\t\t\t * Specify the format of the date when displayed. null by default.\n\t\t\t\t */\n\t\t\t\ttitleFormat: null\n\t\t\t})\n\n\t\t/**\n\t\t * @ngdoc directive\n\t\t * @name angularMoment.directive:amTimeAgo\n\t\t * @module angularMoment\n\t\t *\n\t\t * @restrict A\n\t\t */\n\t\t\t.directive('amTimeAgo', ['$window', 'moment', 'amMoment', 'amTimeAgoConfig', 'angularMomentConfig', function ($window, moment, amMoment, amTimeAgoConfig, angularMomentConfig) {\n\n\t\t\t\treturn function (scope, element, attr) {\n\t\t\t\t\tvar activeTimeout = null;\n\t\t\t\t\tvar currentValue;\n\t\t\t\t\tvar currentFormat = angularMomentConfig.format;\n\t\t\t\t\tvar withoutSuffix = amTimeAgoConfig.withoutSuffix;\n\t\t\t\t\tvar titleFormat = amTimeAgoConfig.titleFormat;\n\t\t\t\t\tvar localDate = new Date().getTime();\n\t\t\t\t\tvar preprocess = angularMomentConfig.preprocess;\n\t\t\t\t\tvar modelName = attr.amTimeAgo.replace(/^::/, '');\n\t\t\t\t\tvar isBindOnce = (attr.amTimeAgo.indexOf('::') === 0);\n\t\t\t\t\tvar isTimeElement = ('TIME' === element[0].nodeName.toUpperCase());\n\t\t\t\t\tvar unwatchChanges;\n\n\t\t\t\t\tfunction getNow() {\n\t\t\t\t\t\tvar now;\n\t\t\t\t\t\tif (amTimeAgoConfig.serverTime) {\n\t\t\t\t\t\t\tvar localNow = new Date().getTime();\n\t\t\t\t\t\t\tvar nowMillis = localNow - localDate + amTimeAgoConfig.serverTime;\n\t\t\t\t\t\t\tnow = moment(nowMillis);\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\tnow = moment();\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn now;\n\t\t\t\t\t}\n\n\t\t\t\t\tfunction cancelTimer() {\n\t\t\t\t\t\tif (activeTimeout) {\n\t\t\t\t\t\t\t$window.clearTimeout(activeTimeout);\n\t\t\t\t\t\t\tactiveTimeout = null;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfunction updateTime(momentInstance) {\n\t\t\t\t\t\telement.text(momentInstance.from(getNow(), withoutSuffix));\n\n\t\t\t\t\t\tif (titleFormat && !element.attr('title')) {\n\t\t\t\t\t\t\telement.attr('title', momentInstance.local().format(titleFormat));\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tif (!isBindOnce) {\n\n\t\t\t\t\t\t\tvar howOld = Math.abs(getNow().diff(momentInstance, 'minute'));\n\t\t\t\t\t\t\tvar secondsUntilUpdate = 3600;\n\t\t\t\t\t\t\tif (howOld < 1) {\n\t\t\t\t\t\t\t\tsecondsUntilUpdate = 1;\n\t\t\t\t\t\t\t} else if (howOld < 60) {\n\t\t\t\t\t\t\t\tsecondsUntilUpdate = 30;\n\t\t\t\t\t\t\t} else if (howOld < 180) {\n\t\t\t\t\t\t\t\tsecondsUntilUpdate = 300;\n\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\tactiveTimeout = $window.setTimeout(function () {\n\t\t\t\t\t\t\t\tupdateTime(momentInstance);\n\t\t\t\t\t\t\t}, secondsUntilUpdate * 1000);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfunction updateDateTimeAttr(value) {\n\t\t\t\t\t\tif (isTimeElement) {\n\t\t\t\t\t\t\telement.attr('datetime', value);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tfunction updateMoment() {\n\t\t\t\t\t\tcancelTimer();\n\t\t\t\t\t\tif (currentValue) {\n\t\t\t\t\t\t\tvar momentValue = amMoment.preprocessDate(currentValue, preprocess, currentFormat);\n\t\t\t\t\t\t\tupdateTime(momentValue);\n\t\t\t\t\t\t\tupdateDateTimeAttr(momentValue.toISOString());\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tunwatchChanges = scope.$watch(modelName, function (value) {\n\t\t\t\t\t\tif ((typeof value === 'undefined') || (value === null) || (value === '')) {\n\t\t\t\t\t\t\tcancelTimer();\n\t\t\t\t\t\t\tif (currentValue) {\n\t\t\t\t\t\t\t\telement.text('');\n\t\t\t\t\t\t\t\tupdateDateTimeAttr('');\n\t\t\t\t\t\t\t\tcurrentValue = null;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treturn;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\tcurrentValue = value;\n\t\t\t\t\t\tupdateMoment();\n\n\t\t\t\t\t\tif (value !== undefined && isBindOnce) {\n\t\t\t\t\t\t\tunwatchChanges();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tif (angular.isDefined(attr.amWithoutSuffix)) {\n\t\t\t\t\t\tscope.$watch(attr.amWithoutSuffix, function (value) {\n\t\t\t\t\t\t\tif (typeof value === 'boolean') {\n\t\t\t\t\t\t\t\twithoutSuffix = value;\n\t\t\t\t\t\t\t\tupdateMoment();\n\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\twithoutSuffix = amTimeAgoConfig.withoutSuffix;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t});\n\t\t\t\t\t}\n\n\t\t\t\t\tattr.$observe('amFormat', function (format) {\n\t\t\t\t\t\tif (typeof format !== 'undefined') {\n\t\t\t\t\t\t\tcurrentFormat = format;\n\t\t\t\t\t\t\tupdateMoment();\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tattr.$observe('amPreprocess', function (newValue) {\n\t\t\t\t\t\tpreprocess = newValue;\n\t\t\t\t\t\tupdateMoment();\n\t\t\t\t\t});\n\n\t\t\t\t\tscope.$on('$destroy', function () {\n\t\t\t\t\t\tcancelTimer();\n\t\t\t\t\t});\n\n\t\t\t\t\tscope.$on('amMoment:localeChanged', function () {\n\t\t\t\t\t\tupdateMoment();\n\t\t\t\t\t});\n\t\t\t\t};\n\t\t\t}])\n\n\t\t/**\n\t\t * @ngdoc service\n\t\t * @name angularMoment.service.amMoment\n\t\t * @module angularMoment\n\t\t */\n\t\t\t.service('amMoment', ['moment', '$rootScope', '$log', 'angularMomentConfig', function (moment, $rootScope, $log, angularMomentConfig) {\n\t\t\t\tvar that = this;\n\t\t\t\t/**\n\t\t\t\t * @ngdoc property\n\t\t\t\t * @name angularMoment:amMoment#preprocessors\n\t\t\t\t * @module angularMoment\n\t\t\t\t *\n\t\t\t\t * @description\n\t\t\t\t * Defines the preprocessors for the preprocessDate method. By default, the following preprocessors\n\t\t\t\t * are defined: utc, unix.\n\t\t\t\t */\n\t\t\t\tthis.preprocessors = {\n\t\t\t\t\tutc: moment.utc,\n\t\t\t\t\tunix: moment.unix\n\t\t\t\t};\n\n\t\t\t\t/**\n\t\t\t\t * @ngdoc function\n\t\t\t\t * @name angularMoment.service.amMoment#changeLocale\n\t\t\t\t * @methodOf angularMoment.service.amMoment\n\t\t\t\t *\n\t\t\t\t * @description\n\t\t\t\t * Changes the locale for moment.js and updates all the am-time-ago directive instances\n\t\t\t\t * with the new locale. Also broadcasts a `amMoment:localeChanged` event on $rootScope.\n\t\t\t\t *\n\t\t\t\t * @param {string} locale 2-letter language code (e.g. en, es, ru, etc.)\n\t\t\t\t */\n\t\t\t\tthis.changeLocale = function (locale) {\n\t\t\t\t\tvar result = (moment.locale||moment.lang)(locale);\n\t\t\t\t\tif (angular.isDefined(locale)) {\n\t\t\t\t\t\t$rootScope.$broadcast('amMoment:localeChanged');\n\n\t\t\t\t\t\t// The following event is deprecated and will be removed in an upcoming\n\t\t\t\t\t\t// major release.\n\t\t\t\t\t\t$rootScope.$broadcast('amMoment:languageChange');\n\t\t\t\t\t}\n\t\t\t\t\treturn result;\n\t\t\t\t};\n\n\t\t\t\t/**\n\t\t\t\t * @ngdoc function\n\t\t\t\t * @name angularMoment.service.amMoment#changeLanguage\n\t\t\t\t * @methodOf angularMoment.service.amMoment\n\t\t\t\t * @deprecated Please use changeLocale() instead.\n\t\t\t\t *\n\t\t\t\t * @description\n\t\t\t\t * Deprecated. Please use changeLocale() instead.\n\t\t\t\t */\n\t\t\t\tthis.changeLanguage = function (lang) {\n\t\t\t\t\t$log.warn('angular-moment: Usage of amMoment.changeLanguage() is deprecated. Please use changeLocale()');\n\t\t\t\t\treturn that.changeLocale(lang);\n\t\t\t\t};\n\n\t\t\t\t/**\n\t\t\t\t * @ngdoc function\n\t\t\t\t * @name angularMoment.service.amMoment#preprocessDate\n\t\t\t\t * @methodOf angularMoment.service.amMoment\n\t\t\t\t *\n\t\t\t\t * @description\n\t\t\t\t * Preprocess a given value and convert it into a Moment instance appropriate for use in the\n\t\t\t\t * am-time-ago directive and the filters.\n\t\t\t\t *\n\t\t\t\t * @param {*} value The value to be preprocessed\n\t\t\t\t * @param {string} preprocess The name of the preprocessor the apply (e.g. utc, unix)\n\t\t\t\t * @param {string=} format Specifies how to parse the value (see {@link http://momentjs.com/docs/#/parsing/string-format/})\n\t\t\t\t * @return {Moment} A value that can be parsed by the moment library\n\t\t\t\t */\n\t\t\t\tthis.preprocessDate = function (value, preprocess, format) {\n\t\t\t\t\tif (angular.isUndefined(preprocess)) {\n\t\t\t\t\t\tpreprocess = angularMomentConfig.preprocess;\n\t\t\t\t\t}\n\t\t\t\t\tif (this.preprocessors[preprocess]) {\n\t\t\t\t\t\treturn this.preprocessors[preprocess](value, format);\n\t\t\t\t\t}\n\t\t\t\t\tif (preprocess) {\n\t\t\t\t\t\t$log.warn('angular-moment: Ignoring unsupported value for preprocess: ' + preprocess);\n\t\t\t\t\t}\n\t\t\t\t\tif (!isNaN(parseFloat(value)) && isFinite(value)) {\n\t\t\t\t\t\t// Milliseconds since the epoch\n\t\t\t\t\t\treturn moment(parseInt(value, 10));\n\t\t\t\t\t}\n\t\t\t\t\t// else just returns the value as-is.\n\t\t\t\t\treturn moment(value, format);\n\t\t\t\t};\n\n\t\t\t\t/**\n\t\t\t\t * @ngdoc function\n\t\t\t\t * @name angularMoment.service.amMoment#applyTimezone\n\t\t\t\t * @methodOf angularMoment.service.amMoment\n\t\t\t\t *\n\t\t\t\t * @description\n\t\t\t\t * Apply a timezone onto a given moment object - if moment-timezone.js is included\n\t\t\t\t * Otherwise, it'll not apply any timezone shift.\n\t\t\t\t *\n\t\t\t\t * @param {Moment} aMoment a moment() instance to apply the timezone shift to\n\t\t\t\t * @returns {Moment} The given moment with the timezone shift applied\n\t\t\t\t */\n\t\t\t\tthis.applyTimezone = function (aMoment) {\n\t\t\t\t\tvar timezone = angularMomentConfig.timezone;\n\t\t\t\t\tif (aMoment && timezone) {\n\t\t\t\t\t\tif (aMoment.tz) {\n\t\t\t\t\t\t\taMoment = aMoment.tz(timezone);\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t$log.warn('angular-moment: timezone specified but moment.tz() is undefined. Did you forget to include moment-timezone.js?');\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t\treturn aMoment;\n\t\t\t\t};\n\t\t\t}])\n\n\t\t/**\n\t\t * @ngdoc filter\n\t\t * @name angularMoment.filter:amCalendar\n\t\t * @module angularMoment\n\t\t */\n\t\t\t.filter('amCalendar', ['moment', 'amMoment', function (moment, amMoment) {\n\t\t\t\treturn function (value, preprocess) {\n\t\t\t\t\tif (typeof value === 'undefined' || value === null) {\n\t\t\t\t\t\treturn '';\n\t\t\t\t\t}\n\n\t\t\t\t\tvalue = amMoment.preprocessDate(value, preprocess);\n\t\t\t\t\tvar date = moment(value);\n\t\t\t\t\tif (!date.isValid()) {\n\t\t\t\t\t\treturn '';\n\t\t\t\t\t}\n\n\t\t\t\t\treturn amMoment.applyTimezone(date).calendar();\n\t\t\t\t};\n\t\t\t}])\n\n\t\t/**\n\t\t * @ngdoc filter\n\t\t * @name angularMoment.filter:amDateFormat\n\t\t * @module angularMoment\n\t\t * @function\n\t\t */\n\t\t\t.filter('amDateFormat', ['moment', 'amMoment', function (moment, amMoment) {\n\t\t\t\treturn function (value, format, preprocess) {\n\t\t\t\t\tif (typeof value === 'undefined' || value === null) {\n\t\t\t\t\t\treturn '';\n\t\t\t\t\t}\n\n\t\t\t\t\tvalue = amMoment.preprocessDate(value, preprocess);\n\t\t\t\t\tvar date = moment(value);\n\t\t\t\t\tif (!date.isValid()) {\n\t\t\t\t\t\treturn '';\n\t\t\t\t\t}\n\n\t\t\t\t\treturn amMoment.applyTimezone(date).format(format);\n\t\t\t\t};\n\t\t\t}])\n\n\t\t/**\n\t\t * @ngdoc filter\n\t\t * @name angularMoment.filter:amDurationFormat\n\t\t * @module angularMoment\n\t\t * @function\n\t\t */\n\t\t\t.filter('amDurationFormat', ['moment', function (moment) {\n\t\t\t\treturn function (value, format, suffix) {\n\t\t\t\t\tif (typeof value === 'undefined' || value === null) {\n\t\t\t\t\t\treturn '';\n\t\t\t\t\t}\n\n\t\t\t\t\treturn moment.duration(value, format).humanize(suffix);\n\t\t\t\t};\n\t\t\t}]);\n\t}\n\n\tif (typeof define === 'function' && define.amd) {\n\t\tdefine('angular-moment', ['angular', 'moment'], angularMoment);\n\t} else {\n\t\tangularMoment(angular, window.moment);\n\t}\n})();\n\n","/**\n * Copyright (c) 2011-2014 Felix Gnass\n * Licensed under the MIT license\n */\n(function(root, factory) {\n\n /* CommonJS */\n if (typeof exports == 'object') module.exports = factory()\n\n /* AMD module */\n else if (typeof define == 'function' && define.amd) define(factory)\n\n /* Browser global */\n else root.Spinner = factory()\n}\n(this, function() {\n \"use strict\";\n\n var prefixes = ['webkit', 'Moz', 'ms', 'O'] /* Vendor prefixes */\n , animations = {} /* Animation rules keyed by their name */\n , useCssAnimations /* Whether to use CSS animations or setTimeout */\n\n /**\n * Utility function to create elements. If no tag name is given,\n * a DIV is created. Optionally properties can be passed.\n */\n function createEl(tag, prop) {\n var el = document.createElement(tag || 'div')\n , n\n\n for(n in prop) el[n] = prop[n]\n return el\n }\n\n /**\n * Appends children and returns the parent.\n */\n function ins(parent /* child1, child2, ...*/) {\n for (var i=1, n=arguments.length; i>1) + 'px'\n })\n }\n\n for (; i < o.lines; i++) {\n seg = css(createEl(), {\n position: 'absolute',\n top: 1+~(o.width/2) + 'px',\n transform: o.hwaccel ? 'translate3d(0,0,0)' : '',\n opacity: o.opacity,\n animation: useCssAnimations && addAnimation(o.opacity, o.trail, start + i * o.direction, o.lines) + ' ' + 1/o.speed + 's linear infinite'\n })\n\n if (o.shadow) ins(seg, css(fill('#000', '0 0 4px ' + '#000'), {top: 2+'px'}))\n ins(el, ins(seg, fill(getColor(o.color, i), '0 0 1px rgba(0,0,0,.1)')))\n }\n return el\n },\n\n /**\n * Internal method that adjusts the opacity of a single line.\n * Will be overwritten in VML fallback mode below.\n */\n opacity: function(el, i, val) {\n if (i < el.childNodes.length) el.childNodes[i].style.opacity = val\n }\n\n })\n\n\n function initVML() {\n\n /* Utility function to create a VML tag */\n function vml(tag, attr) {\n return createEl('<' + tag + ' xmlns=\"urn:schemas-microsoft.com:vml\" class=\"spin-vml\">', attr)\n }\n\n // No CSS transforms but VML support, add a CSS rule for VML elements:\n sheet.addRule('.spin-vml', 'behavior:url(#default#VML)')\n\n Spinner.prototype.lines = function(el, o) {\n var r = o.length+o.width\n , s = 2*r\n\n function grp() {\n return css(\n vml('group', {\n coordsize: s + ' ' + s,\n coordorigin: -r + ' ' + -r\n }),\n { width: s, height: s }\n )\n }\n\n var margin = -(o.width+o.length)*2 + 'px'\n , g = css(grp(), {position: 'absolute', top: margin, left: margin})\n , i\n\n function seg(i, dx, filter) {\n ins(g,\n ins(css(grp(), {rotation: 360 / o.lines * i + 'deg', left: ~~dx}),\n ins(css(vml('roundrect', {arcsize: o.corners}), {\n width: r,\n height: o.width,\n left: o.radius,\n top: -o.width>>1,\n filter: filter\n }),\n vml('fill', {color: getColor(o.color, i), opacity: o.opacity}),\n vml('stroke', {opacity: 0}) // transparent stroke to fix color bleeding upon opacity change\n )\n )\n )\n }\n\n if (o.shadow)\n for (i = 1; i <= o.lines; i++)\n seg(i, -2, 'progid:DXImageTransform.Microsoft.Blur(pixelradius=2,makeshadow=1,shadowopacity=.3)')\n\n for (i = 1; i <= o.lines; i++) seg(i)\n return ins(el, g)\n }\n\n Spinner.prototype.opacity = function(el, i, val, o) {\n var c = el.firstChild\n o = o.shadow && o.lines || 0\n if (c && i+o < c.childNodes.length) {\n c = c.childNodes[i+o]; c = c && c.firstChild; c = c && c.firstChild\n if (c) c.opacity = val\n }\n }\n }\n\n var probe = css(createEl('group'), {behavior: 'url(#default#VML)'})\n\n if (!vendor(probe, 'transform') && probe.adj) initVML()\n else useCssAnimations = vendor(probe, 'animation')\n\n return Spinner\n\n}));\n","/*\n jQuery UI Sortable plugin wrapper\n\n @param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config\n */\nangular.module('ui.sortable', [])\n .value('uiSortableConfig', {})\n .directive('uiSortable', [\n 'uiSortableConfig', '$timeout', '$log',\n function (uiSortableConfig, $timeout, $log) {\n return {\n require: '?ngModel',\n link: function (scope, element, attrs, ngModel) {\n var savedNodes;\n\n function combineCallbacks(first, second) {\n if (second && (typeof second === 'function')) {\n return function (e, ui) {\n first(e, ui);\n second(e, ui);\n };\n }\n return first;\n }\n\n function hasSortingHelper(element, ui) {\n var helperOption = element.sortable('option', 'helper');\n return helperOption === 'clone' || (typeof helperOption === 'function' && ui.item.sortable.isCustomHelperUsed());\n }\n\n var opts = {};\n\n var callbacks = {\n receive: null,\n remove: null,\n start: null,\n stop: null,\n update: null\n };\n\n var wrappers = {\n helper: null\n };\n\n angular.extend(opts, uiSortableConfig, scope.$eval(attrs.uiSortable));\n\n if (!angular.element.fn || !angular.element.fn.jquery) {\n $log.error('ui.sortable: jQuery should be included before AngularJS!');\n return;\n }\n\n if (ngModel) {\n\n // When we add or remove elements, we need the sortable to 'refresh'\n // so it can find the new/removed elements.\n scope.$watch(attrs.ngModel + '.length', function () {\n // Timeout to let ng-repeat modify the DOM\n $timeout(function () {\n // ensure that the jquery-ui-sortable widget instance\n // is still bound to the directive's element\n if (!!element.data('ui-sortable')) {\n element.sortable('refresh');\n }\n });\n });\n\n callbacks.start = function (e, ui) {\n // Save the starting position of dragged item\n ui.item.sortable = {\n index: ui.item.index(),\n cancel: function () {\n ui.item.sortable._isCanceled = true;\n },\n isCanceled: function () {\n return ui.item.sortable._isCanceled;\n },\n isCustomHelperUsed: function () {\n return !!ui.item.sortable._isCustomHelperUsed;\n },\n _isCanceled: false,\n _isCustomHelperUsed: ui.item.sortable._isCustomHelperUsed\n };\n };\n\n callbacks.activate = function (/*e, ui*/) {\n // We need to make a copy of the current element's contents so\n // we can restore it after sortable has messed it up.\n // This is inside activate (instead of start) in order to save\n // both lists when dragging between connected lists.\n savedNodes = element.contents();\n\n // If this list has a placeholder (the connected lists won't),\n // don't inlcude it in saved nodes.\n var placeholder = element.sortable('option', 'placeholder');\n\n // placeholder.element will be a function if the placeholder, has\n // been created (placeholder will be an object). If it hasn't\n // been created, either placeholder will be false if no\n // placeholder class was given or placeholder.element will be\n // undefined if a class was given (placeholder will be a string)\n if (placeholder && placeholder.element && typeof placeholder.element === 'function') {\n var phElement = placeholder.element();\n // workaround for jquery ui 1.9.x,\n // not returning jquery collection\n phElement = angular.element(phElement);\n\n // exact match with the placeholder's class attribute to handle\n // the case that multiple connected sortables exist and\n // the placehoilder option equals the class of sortable items\n var excludes = element.find('[class=\"' + phElement.attr('class') + '\"]');\n\n savedNodes = savedNodes.not(excludes);\n }\n };\n\n callbacks.update = function (e, ui) {\n // Save current drop position but only if this is not a second\n // update that happens when moving between lists because then\n // the value will be overwritten with the old value\n if (!ui.item.sortable.received) {\n ui.item.sortable.dropindex = ui.item.index();\n ui.item.sortable.droptarget = ui.item.parent();\n\n // Cancel the sort (let ng-repeat do the sort for us)\n // Don't cancel if this is the received list because it has\n // already been canceled in the other list, and trying to cancel\n // here will mess up the DOM.\n element.sortable('cancel');\n }\n\n // Put the nodes back exactly the way they started (this is very\n // important because ng-repeat uses comment elements to delineate\n // the start and stop of repeat sections and sortable doesn't\n // respect their order (even if we cancel, the order of the\n // comments are still messed up).\n if (hasSortingHelper(element, ui) && !ui.item.sortable.received &&\n element.sortable('option', 'appendTo') === 'parent') {\n // restore all the savedNodes except .ui-sortable-helper element\n // (which is placed last). That way it will be garbage collected.\n savedNodes = savedNodes.not(savedNodes.last());\n }\n savedNodes.appendTo(element);\n\n // If this is the target connected list then\n // it's safe to clear the restored nodes since:\n // update is currently running and\n // stop is not called for the target list.\n if (ui.item.sortable.received) {\n savedNodes = null;\n }\n\n // If received is true (an item was dropped in from another list)\n // then we add the new item to this list otherwise wait until the\n // stop event where we will know if it was a sort or item was\n // moved here from another list\n if (ui.item.sortable.received && !ui.item.sortable.isCanceled()) {\n scope.$apply(function () {\n ngModel.$modelValue.splice(ui.item.sortable.dropindex, 0,\n ui.item.sortable.moved);\n });\n }\n };\n\n callbacks.stop = function (e, ui) {\n // If the received flag hasn't be set on the item, this is a\n // normal sort, if dropindex is set, the item was moved, so move\n // the items in the list.\n if (!ui.item.sortable.received &&\n ('dropindex' in ui.item.sortable) &&\n !ui.item.sortable.isCanceled()) {\n\n scope.$apply(function () {\n ngModel.$modelValue.splice(\n ui.item.sortable.dropindex, 0,\n ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]);\n });\n } else {\n // if the item was not moved, then restore the elements\n // so that the ngRepeat's comment are correct.\n if ((!('dropindex' in ui.item.sortable) || ui.item.sortable.isCanceled()) &&\n !hasSortingHelper(element, ui)) {\n savedNodes.appendTo(element);\n }\n }\n\n // It's now safe to clear the savedNodes\n // since stop is the last callback.\n savedNodes = null;\n };\n\n callbacks.receive = function (e, ui) {\n // An item was dropped here from another list, set a flag on the\n // item.\n ui.item.sortable.received = true;\n };\n\n callbacks.remove = function (e, ui) {\n // Workaround for a problem observed in nested connected lists.\n // There should be an 'update' event before 'remove' when moving\n // elements. If the event did not fire, cancel sorting.\n if (!('dropindex' in ui.item.sortable)) {\n element.sortable('cancel');\n ui.item.sortable.cancel();\n }\n\n // Remove the item from this list's model and copy data into item,\n // so the next list can retrive it\n if (!ui.item.sortable.isCanceled()) {\n scope.$apply(function () {\n ui.item.sortable.moved = ngModel.$modelValue.splice(\n ui.item.sortable.index, 1)[0];\n });\n }\n };\n\n wrappers.helper = function (inner) {\n if (inner && typeof inner === 'function') {\n return function (e, item) {\n var innerResult = inner(e, item);\n item.sortable._isCustomHelperUsed = item !== innerResult;\n return innerResult;\n };\n }\n return inner;\n };\n\n scope.$watch(attrs.uiSortable, function (newVal /*, oldVal*/) {\n // ensure that the jquery-ui-sortable widget instance\n // is still bound to the directive's element\n if (!!element.data('ui-sortable')) {\n angular.forEach(newVal, function (value, key) {\n if (callbacks[key]) {\n if (key === 'stop') {\n // call apply after stop\n value = combineCallbacks(\n value, function () { scope.$apply(); });\n }\n // wrap the callback\n value = combineCallbacks(callbacks[key], value);\n } else if (wrappers[key]) {\n value = wrappers[key](value);\n }\n\n element.sortable('option', key, value);\n });\n }\n }, true);\n\n angular.forEach(callbacks, function (value, key) {\n opts[key] = combineCallbacks(value, opts[key]);\n });\n\n } else {\n $log.info('ui.sortable: ngModel not provided!', element);\n }\n\n // Create sortable\n element.sortable(opts);\n }\n };\n }\n ]);","/*\n * Toastr\n * Copyright 2012-2014 John Papa and Hans Fjällemark.\n * All Rights Reserved.\n * Use, reproduction, distribution, and modification of this code is subject to the terms and\n * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php\n *\n * Author: John Papa and Hans Fjällemark\n * ARIA Support: Greta Krafsig\n * Project: https://github.com/CodeSeven/toastr\n */\n; (function (define) {\n define(['jquery'], function ($) {\n return (function () {\n var $container;\n var listener;\n var toastId = 0;\n var toastType = {\n error: 'error',\n info: 'info',\n success: 'success',\n warning: 'warning'\n };\n\n var toastr = {\n clear: clear,\n remove: remove,\n error: error,\n getContainer: getContainer,\n info: info,\n options: {},\n subscribe: subscribe,\n success: success,\n version: '2.1.0',\n warning: warning\n };\n\n var previousToast;\n\n return toastr;\n\n //#region Accessible Methods\n function error(message, title, optionsOverride) {\n return notify({\n type: toastType.error,\n iconClass: getOptions().iconClasses.error,\n message: message,\n optionsOverride: optionsOverride,\n title: title\n });\n }\n\n function getContainer(options, create) {\n if (!options) { options = getOptions(); }\n $container = $('#' + options.containerId);\n if ($container.length) {\n return $container;\n }\n if(create) {\n $container = createContainer(options);\n }\n return $container;\n }\n\n function info(message, title, optionsOverride) {\n return notify({\n type: toastType.info,\n iconClass: getOptions().iconClasses.info,\n message: message,\n optionsOverride: optionsOverride,\n title: title\n });\n }\n\n function subscribe(callback) {\n listener = callback;\n }\n\n function success(message, title, optionsOverride) {\n return notify({\n type: toastType.success,\n iconClass: getOptions().iconClasses.success,\n message: message,\n optionsOverride: optionsOverride,\n title: title\n });\n }\n\n function warning(message, title, optionsOverride) {\n return notify({\n type: toastType.warning,\n iconClass: getOptions().iconClasses.warning,\n message: message,\n optionsOverride: optionsOverride,\n title: title\n });\n }\n\n function clear($toastElement) {\n var options = getOptions();\n if (!$container) { getContainer(options); }\n if (!clearToast($toastElement, options)) {\n clearContainer(options);\n }\n }\n\n function remove($toastElement) {\n var options = getOptions();\n if (!$container) { getContainer(options); }\n if ($toastElement && $(':focus', $toastElement).length === 0) {\n removeToast($toastElement);\n return;\n }\n if ($container.children().length) {\n $container.remove();\n }\n }\n //#endregion\n\n //#region Internal Methods\n\n function clearContainer(options){\n var toastsToClear = $container.children();\n for (var i = toastsToClear.length - 1; i >= 0; i--) {\n clearToast($(toastsToClear[i]), options);\n };\n }\n\n function clearToast($toastElement, options){\n if ($toastElement && $(':focus', $toastElement).length === 0) {\n $toastElement[options.hideMethod]({\n duration: options.hideDuration,\n easing: options.hideEasing,\n complete: function () { removeToast($toastElement); }\n });\n return true;\n }\n return false;\n }\n\n function createContainer(options) {\n $container = $('
      ')\n .attr('id', options.containerId)\n .addClass(options.positionClass)\n .attr('aria-live', 'polite')\n .attr('role', 'alert');\n\n $container.appendTo($(options.target));\n return $container;\n }\n\n function getDefaults() {\n return {\n tapToDismiss: true,\n toastClass: 'toast',\n containerId: 'toast-container',\n debug: false,\n\n showMethod: 'fadeIn', //fadeIn, slideDown, and show are built into jQuery\n showDuration: 300,\n showEasing: 'swing', //swing and linear are built into jQuery\n onShown: undefined,\n hideMethod: 'fadeOut',\n hideDuration: 1000,\n hideEasing: 'swing',\n onHidden: undefined,\n\n extendedTimeOut: 1000,\n iconClasses: {\n error: 'toast-error',\n info: 'toast-info',\n success: 'toast-success',\n warning: 'toast-warning'\n },\n iconClass: 'toast-info',\n positionClass: 'toast-top-right',\n timeOut: 5000, // Set timeOut and extendedTimeOut to 0 to make it sticky\n titleClass: 'toast-title',\n messageClass: 'toast-message',\n target: 'body',\n closeHtml: '',\n newestOnTop: true,\n preventDuplicates: false\n };\n }\n\n function publish(args) {\n if (!listener) { return; }\n listener(args);\n }\n\n function notify(map) {\n var options = getOptions(),\n iconClass = map.iconClass || options.iconClass;\n\n if(options.preventDuplicates){\n if(map.message === previousToast){\n return;\n }\n else{\n previousToast = map.message;\n }\n }\n\n if (typeof (map.optionsOverride) !== 'undefined') {\n options = $.extend(options, map.optionsOverride);\n iconClass = map.optionsOverride.iconClass || iconClass;\n }\n\n toastId++;\n\n $container = getContainer(options, true);\n var intervalId = null,\n $toastElement = $('
      '),\n $titleElement = $('
      '),\n $messageElement = $('
      '),\n $closeElement = $(options.closeHtml),\n response = {\n toastId: toastId,\n state: 'visible',\n startTime: new Date(),\n options: options,\n map: map\n };\n\n if (map.iconClass) {\n $toastElement.addClass(options.toastClass).addClass(iconClass);\n }\n\n if (map.title) {\n $titleElement.append(map.title).addClass(options.titleClass);\n $toastElement.append($titleElement);\n }\n\n if (map.message) {\n $messageElement.append(map.message).addClass(options.messageClass);\n $toastElement.append($messageElement);\n }\n\n if (options.closeButton) {\n $closeElement.addClass('toast-close-button').attr(\"role\", \"button\");\n $toastElement.prepend($closeElement);\n }\n\n $toastElement.hide();\n if (options.newestOnTop) {\n $container.prepend($toastElement);\n } else {\n $container.append($toastElement);\n }\n\n\n $toastElement[options.showMethod](\n { duration: options.showDuration, easing: options.showEasing, complete: options.onShown }\n );\n\n if (options.timeOut > 0) {\n intervalId = setTimeout(hideToast, options.timeOut);\n }\n\n $toastElement.hover(stickAround, delayedHideToast);\n if (!options.onclick && options.tapToDismiss) {\n $toastElement.click(hideToast);\n }\n\n if (options.closeButton && $closeElement) {\n $closeElement.click(function (event) {\n if( event.stopPropagation ) {\n event.stopPropagation();\n } else if( event.cancelBubble !== undefined && event.cancelBubble !== true ) {\n event.cancelBubble = true;\n }\n hideToast(true);\n });\n }\n\n if (options.onclick) {\n $toastElement.click(function () {\n options.onclick();\n hideToast();\n });\n }\n\n publish(response);\n\n if (options.debug && console) {\n console.log(response);\n }\n\n return $toastElement;\n\n function hideToast(override) {\n if ($(':focus', $toastElement).length && !override) {\n return;\n }\n return $toastElement[options.hideMethod]({\n duration: options.hideDuration,\n easing: options.hideEasing,\n complete: function () {\n removeToast($toastElement);\n if (options.onHidden && response.state !== 'hidden') {\n options.onHidden();\n }\n response.state = 'hidden';\n response.endTime = new Date();\n publish(response);\n }\n });\n }\n\n function delayedHideToast() {\n if (options.timeOut > 0 || options.extendedTimeOut > 0) {\n intervalId = setTimeout(hideToast, options.extendedTimeOut);\n }\n }\n\n function stickAround() {\n clearTimeout(intervalId);\n $toastElement.stop(true, true)[options.showMethod](\n { duration: options.showDuration, easing: options.showEasing }\n );\n }\n }\n\n function getOptions() {\n return $.extend({}, getDefaults(), toastr.options);\n }\n\n function removeToast($toastElement) {\n if (!$container) { $container = getContainer(); }\n if ($toastElement.is(':visible')) {\n return;\n }\n $toastElement.remove();\n $toastElement = null;\n if ($container.children().length === 0) {\n $container.remove();\n }\n }\n //#endregion\n\n })();\n });\n}(typeof define === 'function' && define.amd ? define : function (deps, factory) {\n if (typeof module !== 'undefined' && module.exports) { //Node\n module.exports = factory(require('jquery'));\n } else {\n window['toastr'] = factory(window['jQuery']);\n }\n}));\n","/*!\n * accounting.js v0.4.1\n * Copyright 2014 Open Exchange Rates\n *\n * Freely distributable under the MIT license.\n * Portions of accounting.js are inspired or borrowed from underscore.js\n *\n * Full details and documentation:\n * http://openexchangerates.github.io/accounting.js/\n */\n\n(function(root, undefined) {\n\n\t/* --- Setup --- */\n\n\t// Create the local library object, to be exported or referenced globally later\n\tvar lib = {};\n\n\t// Current version\n\tlib.version = '0.4.1';\n\n\n\t/* --- Exposed settings --- */\n\n\t// The library's settings configuration object. Contains default parameters for\n\t// currency and number formatting\n\tlib.settings = {\n\t\tcurrency: {\n\t\t\tsymbol : \"$\",\t\t// default currency symbol is '$'\n\t\t\tformat : \"%s%v\",\t// controls output: %s = symbol, %v = value (can be object, see docs)\n\t\t\tdecimal : \".\",\t\t// decimal point separator\n\t\t\tthousand : \",\",\t\t// thousands separator\n\t\t\tprecision : 2,\t\t// decimal places\n\t\t\tgrouping : 3\t\t// digit grouping (not implemented yet)\n\t\t},\n\t\tnumber: {\n\t\t\tprecision : 0,\t\t// default precision on numbers is 0\n\t\t\tgrouping : 3,\t\t// digit grouping (not implemented yet)\n\t\t\tthousand : \",\",\n\t\t\tdecimal : \".\"\n\t\t}\n\t};\n\n\n\t/* --- Internal Helper Methods --- */\n\n\t// Store reference to possibly-available ECMAScript 5 methods for later\n\tvar nativeMap = Array.prototype.map,\n\t\tnativeIsArray = Array.isArray,\n\t\ttoString = Object.prototype.toString;\n\n\t/**\n\t * Tests whether supplied parameter is a string\n\t * from underscore.js\n\t */\n\tfunction isString(obj) {\n\t\treturn !!(obj === '' || (obj && obj.charCodeAt && obj.substr));\n\t}\n\n\t/**\n\t * Tests whether supplied parameter is a string\n\t * from underscore.js, delegates to ECMA5's native Array.isArray\n\t */\n\tfunction isArray(obj) {\n\t\treturn nativeIsArray ? nativeIsArray(obj) : toString.call(obj) === '[object Array]';\n\t}\n\n\t/**\n\t * Tests whether supplied parameter is a true object\n\t */\n\tfunction isObject(obj) {\n\t\treturn obj && toString.call(obj) === '[object Object]';\n\t}\n\n\t/**\n\t * Extends an object with a defaults object, similar to underscore's _.defaults\n\t *\n\t * Used for abstracting parameter handling from API methods\n\t */\n\tfunction defaults(object, defs) {\n\t\tvar key;\n\t\tobject = object || {};\n\t\tdefs = defs || {};\n\t\t// Iterate over object non-prototype properties:\n\t\tfor (key in defs) {\n\t\t\tif (defs.hasOwnProperty(key)) {\n\t\t\t\t// Replace values with defaults only if undefined (allow empty/zero values):\n\t\t\t\tif (object[key] == null) object[key] = defs[key];\n\t\t\t}\n\t\t}\n\t\treturn object;\n\t}\n\n\t/**\n\t * Implementation of `Array.map()` for iteration loops\n\t *\n\t * Returns a new Array as a result of calling `iterator` on each array value.\n\t * Defers to native Array.map if available\n\t */\n\tfunction map(obj, iterator, context) {\n\t\tvar results = [], i, j;\n\n\t\tif (!obj) return results;\n\n\t\t// Use native .map method if it exists:\n\t\tif (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);\n\n\t\t// Fallback for native .map:\n\t\tfor (i = 0, j = obj.length; i < j; i++ ) {\n\t\t\tresults[i] = iterator.call(context, obj[i], i, obj);\n\t\t}\n\t\treturn results;\n\t}\n\n\t/**\n\t * Check and normalise the value of precision (must be positive integer)\n\t */\n\tfunction checkPrecision(val, base) {\n\t\tval = Math.round(Math.abs(val));\n\t\treturn isNaN(val)? base : val;\n\t}\n\n\n\t/**\n\t * Parses a format string or object and returns format obj for use in rendering\n\t *\n\t * `format` is either a string with the default (positive) format, or object\n\t * containing `pos` (required), `neg` and `zero` values (or a function returning\n\t * either a string or object)\n\t *\n\t * Either string or format.pos must contain \"%v\" (value) to be valid\n\t */\n\tfunction checkCurrencyFormat(format) {\n\t\tvar defaults = lib.settings.currency.format;\n\n\t\t// Allow function as format parameter (should return string or object):\n\t\tif ( typeof format === \"function\" ) format = format();\n\n\t\t// Format can be a string, in which case `value` (\"%v\") must be present:\n\t\tif ( isString( format ) && format.match(\"%v\") ) {\n\n\t\t\t// Create and return positive, negative and zero formats:\n\t\t\treturn {\n\t\t\t\tpos : format,\n\t\t\t\tneg : format.replace(\"-\", \"\").replace(\"%v\", \"-%v\"),\n\t\t\t\tzero : format\n\t\t\t};\n\n\t\t// If no format, or object is missing valid positive value, use defaults:\n\t\t} else if ( !format || !format.pos || !format.pos.match(\"%v\") ) {\n\n\t\t\t// If defaults is a string, casts it to an object for faster checking next time:\n\t\t\treturn ( !isString( defaults ) ) ? defaults : lib.settings.currency.format = {\n\t\t\t\tpos : defaults,\n\t\t\t\tneg : defaults.replace(\"%v\", \"-%v\"),\n\t\t\t\tzero : defaults\n\t\t\t};\n\n\t\t}\n\t\t// Otherwise, assume format was fine:\n\t\treturn format;\n\t}\n\n\n\t/* --- API Methods --- */\n\n\t/**\n\t * Takes a string/array of strings, removes all formatting/cruft and returns the raw float value\n\t * Alias: `accounting.parse(string)`\n\t *\n\t * Decimal must be included in the regular expression to match floats (defaults to\n\t * accounting.settings.number.decimal), so if the number uses a non-standard decimal \n\t * separator, provide it as the second argument.\n\t *\n\t * Also matches bracketed negatives (eg. \"$ (1.99)\" => -1.99)\n\t *\n\t * Doesn't throw any errors (`NaN`s become 0) but this may change in future\n\t */\n\tvar unformat = lib.unformat = lib.parse = function(value, decimal) {\n\t\t// Recursively unformat arrays:\n\t\tif (isArray(value)) {\n\t\t\treturn map(value, function(val) {\n\t\t\t\treturn unformat(val, decimal);\n\t\t\t});\n\t\t}\n\n\t\t// Fails silently (need decent errors):\n\t\tvalue = value || 0;\n\n\t\t// Return the value as-is if it's already a number:\n\t\tif (typeof value === \"number\") return value;\n\n\t\t// Default decimal point comes from settings, but could be set to eg. \",\" in opts:\n\t\tdecimal = decimal || lib.settings.number.decimal;\n\n\t\t // Build regex to strip out everything except digits, decimal point and minus sign:\n\t\tvar regex = new RegExp(\"[^0-9-\" + decimal + \"]\", [\"g\"]),\n\t\t\tunformatted = parseFloat(\n\t\t\t\t(\"\" + value)\n\t\t\t\t.replace(/\\((.*)\\)/, \"-$1\") // replace bracketed values with negatives\n\t\t\t\t.replace(regex, '') // strip out any cruft\n\t\t\t\t.replace(decimal, '.') // make sure decimal point is standard\n\t\t\t);\n\n\t\t// This will fail silently which may cause trouble, let's wait and see:\n\t\treturn !isNaN(unformatted) ? unformatted : 0;\n\t};\n\n\n\t/**\n\t * Implementation of toFixed() that treats floats more like decimals\n\t *\n\t * Fixes binary rounding issues (eg. (0.615).toFixed(2) === \"0.61\") that present\n\t * problems for accounting- and finance-related software.\n\t */\n var toFixed = lib.toFixed = function(value, precision) {\n precision = checkPrecision(precision, lib.settings.number.precision);\n var power = Math.pow(10, precision);\n\n // Multiply up by precision, round accurately, then divide and use native toFixed():\n\n var dif = ((lib.unformat(value) * power) / power) - ((((lib.unformat(value) * power).toFixed(0))) / power);\n if ((dif.toFixed(3) * 1) == 0.005) {\n if (value < 0) {\n return (Math.round(lib.unformat(value) * power) / power);\n }\n return (Math.round(lib.unformat(value) * power) / power) + 0.01;\n }\n return (Math.round(lib.unformat(value) * power) / power);\n };\n\n\n\t/**\n\t * Format a number, with comma-separated thousands and custom precision/decimal places\n\t * Alias: `accounting.format()`\n\t *\n\t * Localise by overriding the precision and thousand / decimal separators\n\t * 2nd parameter `precision` can be an object matching `settings.number`\n\t */\n\tvar formatNumber = lib.formatNumber = lib.format = function(number, precision, thousand, decimal) {\n\t\t// Resursively format arrays:\n\t\tif (isArray(number)) {\n\t\t\treturn map(number, function(val) {\n\t\t\t\treturn formatNumber(val, precision, thousand, decimal);\n\t\t\t});\n\t\t}\n\n\t\t// Clean up number:\n\t\tnumber = unformat(number);\n\n\t\t// Build options object from second param (if object) or all params, extending defaults:\n\t\tvar opts = defaults(\n\t\t\t\t(isObject(precision) ? precision : {\n\t\t\t\t\tprecision : precision,\n\t\t\t\t\tthousand : thousand,\n\t\t\t\t\tdecimal : decimal\n\t\t\t\t}),\n\t\t\t\tlib.settings.number\n\t\t\t),\n\n\t\t\t// Clean up precision\n\t\t\tusePrecision = checkPrecision(opts.precision),\n\n\t\t\t// Do some calc:\n\t\t\tnegative = number < 0 ? \"-\" : \"\",\n\t\t\tbase = parseInt(toFixed(Math.abs(number || 0), usePrecision), 10) + \"\",\n\t\t\tmod = base.length > 3 ? base.length % 3 : 0;\n\n\t\t// Format the number:\n\t\treturn negative + (mod ? base.substr(0, mod) + opts.thousand : \"\") + base.substr(mod).replace(/(\\d{3})(?=\\d)/g, \"$1\" + opts.thousand) + (usePrecision ? opts.decimal + toFixed(Math.abs(number), usePrecision).split('.')[1] : \"\");\n\t};\n\n\n\t/**\n\t * Format a number into currency\n\t *\n\t * Usage: accounting.formatMoney(number, symbol, precision, thousandsSep, decimalSep, format)\n\t * defaults: (0, \"$\", 2, \",\", \".\", \"%s%v\")\n\t *\n\t * Localise by overriding the symbol, precision, thousand / decimal separators and format\n\t * Second param can be an object matching `settings.currency` which is the easiest way.\n\t *\n\t * To do: tidy up the parameters\n\t */\n\tvar formatMoney = lib.formatMoney = function(number, symbol, precision, thousand, decimal, format) {\n\t\t// Resursively format arrays:\n\t\tif (isArray(number)) {\n\t\t\treturn map(number, function(val){\n\t\t\t\treturn formatMoney(val, symbol, precision, thousand, decimal, format);\n\t\t\t});\n\t\t}\n\n\t\t// Clean up number:\n\t\tnumber = unformat(number);\n\n\t\t// Build options object from second param (if object) or all params, extending defaults:\n\t\tvar opts = defaults(\n\t\t\t\t(isObject(symbol) ? symbol : {\n\t\t\t\t\tsymbol : symbol,\n\t\t\t\t\tprecision : precision,\n\t\t\t\t\tthousand : thousand,\n\t\t\t\t\tdecimal : decimal,\n\t\t\t\t\tformat : format\n\t\t\t\t}),\n\t\t\t\tlib.settings.currency\n\t\t\t),\n\n\t\t\t// Check format (returns object with pos, neg and zero):\n\t\t\tformats = checkCurrencyFormat(opts.format),\n\n\t\t\t// Choose which format to use for this value:\n\t\t\tuseFormat = number > 0 ? formats.pos : number < 0 ? formats.neg : formats.zero;\n\n\t\t// Return with currency symbol added:\n\t\treturn useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(number), checkPrecision(opts.precision), opts.thousand, opts.decimal));\n\t};\n\n\n\t/**\n\t * Format a list of numbers into an accounting column, padding with whitespace\n\t * to line up currency symbols, thousand separators and decimals places\n\t *\n\t * List should be an array of numbers\n\t * Second parameter can be an object containing keys that match the params\n\t *\n\t * Returns array of accouting-formatted number strings of same length\n\t *\n\t * NB: `white-space:pre` CSS rule is required on the list container to prevent\n\t * browsers from collapsing the whitespace in the output strings.\n\t */\n\tlib.formatColumn = function(list, symbol, precision, thousand, decimal, format) {\n\t\tif (!list) return [];\n\n\t\t// Build options object from second param (if object) or all params, extending defaults:\n\t\tvar opts = defaults(\n\t\t\t\t(isObject(symbol) ? symbol : {\n\t\t\t\t\tsymbol : symbol,\n\t\t\t\t\tprecision : precision,\n\t\t\t\t\tthousand : thousand,\n\t\t\t\t\tdecimal : decimal,\n\t\t\t\t\tformat : format\n\t\t\t\t}),\n\t\t\t\tlib.settings.currency\n\t\t\t),\n\n\t\t\t// Check format (returns object with pos, neg and zero), only need pos for now:\n\t\t\tformats = checkCurrencyFormat(opts.format),\n\n\t\t\t// Whether to pad at start of string or after currency symbol:\n\t\t\tpadAfterSymbol = formats.pos.indexOf(\"%s\") < formats.pos.indexOf(\"%v\") ? true : false,\n\n\t\t\t// Store value for the length of the longest string in the column:\n\t\t\tmaxLength = 0,\n\n\t\t\t// Format the list according to options, store the length of the longest string:\n\t\t\tformatted = map(list, function(val, i) {\n\t\t\t\tif (isArray(val)) {\n\t\t\t\t\t// Recursively format columns if list is a multi-dimensional array:\n\t\t\t\t\treturn lib.formatColumn(val, opts);\n\t\t\t\t} else {\n\t\t\t\t\t// Clean up the value\n\t\t\t\t\tval = unformat(val);\n\n\t\t\t\t\t// Choose which format to use for this value (pos, neg or zero):\n\t\t\t\t\tvar useFormat = val > 0 ? formats.pos : val < 0 ? formats.neg : formats.zero,\n\n\t\t\t\t\t\t// Format this value, push into formatted list and save the length:\n\t\t\t\t\t\tfVal = useFormat.replace('%s', opts.symbol).replace('%v', formatNumber(Math.abs(val), checkPrecision(opts.precision), opts.thousand, opts.decimal));\n\n\t\t\t\t\tif (fVal.length > maxLength) maxLength = fVal.length;\n\t\t\t\t\treturn fVal;\n\t\t\t\t}\n\t\t\t});\n\n\t\t// Pad each number in the list and send back the column of numbers:\n\t\treturn map(formatted, function(val, i) {\n\t\t\t// Only if this is a string (not a nested array, which would have already been padded):\n\t\t\tif (isString(val) && val.length < maxLength) {\n\t\t\t\t// Depending on symbol position, pad after symbol or at index 0:\n\t\t\t\treturn padAfterSymbol ? val.replace(opts.symbol, opts.symbol+(new Array(maxLength - val.length + 1).join(\" \"))) : (new Array(maxLength - val.length + 1).join(\" \")) + val;\n\t\t\t}\n\t\t\treturn val;\n\t\t});\n\t};\n\n\n\t/* --- Module Definition --- */\n\n\t// Export accounting for CommonJS. If being loaded as an AMD module, define it as such.\n\t// Otherwise, just add `accounting` to the global object\n\tif (typeof exports !== 'undefined') {\n\t\tif (typeof module !== 'undefined' && module.exports) {\n\t\t\texports = module.exports = lib;\n\t\t}\n\t\texports.accounting = lib;\n\t} else if (typeof define === 'function' && define.amd) {\n\t\t// Return the library as an AMD module:\n\t\tdefine([], function() {\n\t\t\treturn lib;\n\t\t});\n\t} else {\n\t\t// Use accounting.noConflict to restore `accounting` back to its original value.\n\t\t// Returns a reference to the library's `accounting` object;\n\t\t// e.g. `var numbers = accounting.noConflict();`\n\t\tlib.noConflict = (function(oldAccounting) {\n\t\t\treturn function() {\n\t\t\t\t// Reset the value of the root's `accounting` variable:\n\t\t\t\troot.accounting = oldAccounting;\n\t\t\t\t// Delete the noConflict method:\n\t\t\t\tlib.noConflict = undefined;\n\t\t\t\t// Return reference to the library to re-assign it:\n\t\t\t\treturn lib;\n\t\t\t};\n\t\t})(root.accounting);\n\n\t\t// Declare `fx` on the root (global/window) object:\n\t\troot['accounting'] = lib;\n\t}\n\n\t// Root will be `window` in browser or `global` on the server:\n}(this));\n","// Domain Public by Eric Wendelin http://www.eriwen.com/ (2008)\n// Luke Smith http://lucassmith.name/ (2008)\n// Loic Dachary (2008)\n// Johan Euphrosine (2008)\n// Oyvind Sean Kinsey http://kinsey.no/blog (2010)\n// Victor Homyakov (2010)\n/*global module, exports, define, ActiveXObject*/\n(function(global, factory) {\n if (typeof exports === 'object') {\n // Node\n module.exports = factory();\n } else if (typeof define === 'function' && define.amd) {\n // AMD\n define(factory);\n } else {\n // Browser globals\n global.printStackTrace = factory();\n }\n}(this, function() {\n /**\n * Main function giving a function stack trace with a forced or passed in Error\n *\n * @cfg {Error} e The error to create a stacktrace from (optional)\n * @cfg {Boolean} guess If we should try to resolve the names of anonymous functions\n * @return {Array} of Strings with functions, lines, files, and arguments where possible\n */\n function printStackTrace(options) {\n options = options || {guess: true};\n var ex = options.e || null, guess = !!options.guess, mode = options.mode || null;\n var p = new printStackTrace.implementation(), result = p.run(ex, mode);\n return (guess) ? p.guessAnonymousFunctions(result) : result;\n }\n\n printStackTrace.implementation = function() {\n };\n\n printStackTrace.implementation.prototype = {\n /**\n * @param {Error} [ex] The error to create a stacktrace from (optional)\n * @param {String} [mode] Forced mode (optional, mostly for unit tests)\n */\n run: function(ex, mode) {\n ex = ex || this.createException();\n mode = mode || this.mode(ex);\n if (mode === 'other') {\n return this.other(arguments.callee);\n } else {\n return this[mode](ex);\n }\n },\n\n createException: function() {\n try {\n this.undef();\n } catch (e) {\n return e;\n }\n },\n\n /**\n * Mode could differ for different exception, e.g.\n * exceptions in Chrome may or may not have arguments or stack.\n *\n * @return {String} mode of operation for the exception\n */\n mode: function(e) {\n if (e['arguments'] && e.stack) {\n return 'chrome';\n }\n\n if (e.stack && e.sourceURL) {\n return 'safari';\n }\n\n if (e.stack && e.number) {\n return 'ie';\n }\n\n if (e.stack && e.fileName) {\n return 'firefox';\n }\n\n if (e.message && e['opera#sourceloc']) {\n // e.message.indexOf(\"Backtrace:\") > -1 -> opera9\n // 'opera#sourceloc' in e -> opera9, opera10a\n // !e.stacktrace -> opera9\n if (!e.stacktrace) {\n return 'opera9'; // use e.message\n }\n if (e.message.indexOf('\\n') > -1 && e.message.split('\\n').length > e.stacktrace.split('\\n').length) {\n // e.message may have more stack entries than e.stacktrace\n return 'opera9'; // use e.message\n }\n return 'opera10a'; // use e.stacktrace\n }\n\n if (e.message && e.stack && e.stacktrace) {\n // e.stacktrace && e.stack -> opera10b\n if (e.stacktrace.indexOf(\"called from line\") < 0) {\n return 'opera10b'; // use e.stacktrace, format differs from 'opera10a'\n }\n // e.stacktrace && e.stack -> opera11\n return 'opera11'; // use e.stacktrace, format differs from 'opera10a', 'opera10b'\n }\n\n if (e.stack && !e.fileName) {\n // Chrome 27 does not have e.arguments as earlier versions,\n // but still does not have e.fileName as Firefox\n return 'chrome';\n }\n\n return 'other';\n },\n\n /**\n * Given a context, function name, and callback function, overwrite it so that it calls\n * printStackTrace() first with a callback and then runs the rest of the body.\n *\n * @param {Object} context of execution (e.g. window)\n * @param {String} functionName to instrument\n * @param {Function} callback function to call with a stack trace on invocation\n */\n instrumentFunction: function(context, functionName, callback) {\n context = context || window;\n var original = context[functionName];\n context[functionName] = function instrumented() {\n callback.call(this, printStackTrace().slice(4));\n return context[functionName]._instrumented.apply(this, arguments);\n };\n context[functionName]._instrumented = original;\n },\n\n /**\n * Given a context and function name of a function that has been\n * instrumented, revert the function to it's original (non-instrumented)\n * state.\n *\n * @param {Object} context of execution (e.g. window)\n * @param {String} functionName to de-instrument\n */\n deinstrumentFunction: function(context, functionName) {\n if (context[functionName].constructor === Function &&\n context[functionName]._instrumented &&\n context[functionName]._instrumented.constructor === Function) {\n context[functionName] = context[functionName]._instrumented;\n }\n },\n\n /**\n * Given an Error object, return a formatted Array based on Chrome's stack string.\n *\n * @param e - Error object to inspect\n * @return Array of function calls, files and line numbers\n */\n chrome: function(e) {\n return (e.stack + '\\n')\n .replace(/^[\\s\\S]+?\\s+at\\s+/, ' at ') // remove message\n .replace(/^\\s+(at eval )?at\\s+/gm, '') // remove 'at' and indentation\n .replace(/^([^\\(]+?)([\\n$])/gm, '{anonymous}() ($1)$2')\n .replace(/^Object.\\s*\\(([^\\)]+)\\)/gm, '{anonymous}() ($1)')\n .replace(/^(.+) \\((.+)\\)$/gm, '$1@$2')\n .split('\\n')\n .slice(0, -1);\n },\n\n /**\n * Given an Error object, return a formatted Array based on Safari's stack string.\n *\n * @param e - Error object to inspect\n * @return Array of function calls, files and line numbers\n */\n safari: function(e) {\n return e.stack.replace(/\\[native code\\]\\n/m, '')\n .replace(/^(?=\\w+Error\\:).*$\\n/m, '')\n .replace(/^@/gm, '{anonymous}()@')\n .split('\\n');\n },\n\n /**\n * Given an Error object, return a formatted Array based on IE's stack string.\n *\n * @param e - Error object to inspect\n * @return Array of function calls, files and line numbers\n */\n ie: function(e) {\n return e.stack\n .replace(/^\\s*at\\s+(.*)$/gm, '$1')\n .replace(/^Anonymous function\\s+/gm, '{anonymous}() ')\n .replace(/^(.+)\\s+\\((.+)\\)$/gm, '$1@$2')\n .split('\\n')\n .slice(1);\n },\n\n /**\n * Given an Error object, return a formatted Array based on Firefox's stack string.\n *\n * @param e - Error object to inspect\n * @return Array of function calls, files and line numbers\n */\n firefox: function(e) {\n return e.stack.replace(/(?:\\n@:0)?\\s+$/m, '')\n .replace(/^(?:\\((\\S*)\\))?@/gm, '{anonymous}($1)@')\n .split('\\n');\n },\n\n opera11: function(e) {\n var ANON = '{anonymous}', lineRE = /^.*line (\\d+), column (\\d+)(?: in (.+))? in (\\S+):$/;\n var lines = e.stacktrace.split('\\n'), result = [];\n\n for (var i = 0, len = lines.length; i < len; i += 2) {\n var match = lineRE.exec(lines[i]);\n if (match) {\n var location = match[4] + ':' + match[1] + ':' + match[2];\n var fnName = match[3] || \"global code\";\n fnName = fnName.replace(//, \"$1\").replace(//, ANON);\n result.push(fnName + '@' + location + ' -- ' + lines[i + 1].replace(/^\\s+/, ''));\n }\n }\n\n return result;\n },\n\n opera10b: function(e) {\n // \"([arguments not available])@file://localhost/G:/js/stacktrace.js:27\\n\" +\n // \"printStackTrace([arguments not available])@file://localhost/G:/js/stacktrace.js:18\\n\" +\n // \"@file://localhost/G:/js/test/functional/testcase1.html:15\"\n var lineRE = /^(.*)@(.+):(\\d+)$/;\n var lines = e.stacktrace.split('\\n'), result = [];\n\n for (var i = 0, len = lines.length; i < len; i++) {\n var match = lineRE.exec(lines[i]);\n if (match) {\n var fnName = match[1] ? (match[1] + '()') : \"global code\";\n result.push(fnName + '@' + match[2] + ':' + match[3]);\n }\n }\n\n return result;\n },\n\n /**\n * Given an Error object, return a formatted Array based on Opera 10's stacktrace string.\n *\n * @param e - Error object to inspect\n * @return Array of function calls, files and line numbers\n */\n opera10a: function(e) {\n // \" Line 27 of linked script file://localhost/G:/js/stacktrace.js\\n\"\n // \" Line 11 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html: In function foo\\n\"\n var ANON = '{anonymous}', lineRE = /Line (\\d+).*script (?:in )?(\\S+)(?:: In function (\\S+))?$/i;\n var lines = e.stacktrace.split('\\n'), result = [];\n\n for (var i = 0, len = lines.length; i < len; i += 2) {\n var match = lineRE.exec(lines[i]);\n if (match) {\n var fnName = match[3] || ANON;\n result.push(fnName + '()@' + match[2] + ':' + match[1] + ' -- ' + lines[i + 1].replace(/^\\s+/, ''));\n }\n }\n\n return result;\n },\n\n // Opera 7.x-9.2x only!\n opera9: function(e) {\n // \" Line 43 of linked script file://localhost/G:/js/stacktrace.js\\n\"\n // \" Line 7 of inline#1 script in file://localhost/G:/js/test/functional/testcase1.html\\n\"\n var ANON = '{anonymous}', lineRE = /Line (\\d+).*script (?:in )?(\\S+)/i;\n var lines = e.message.split('\\n'), result = [];\n\n for (var i = 2, len = lines.length; i < len; i += 2) {\n var match = lineRE.exec(lines[i]);\n if (match) {\n result.push(ANON + '()@' + match[2] + ':' + match[1] + ' -- ' + lines[i + 1].replace(/^\\s+/, ''));\n }\n }\n\n return result;\n },\n\n // Safari 5-, IE 9-, and others\n other: function(curr) {\n var ANON = '{anonymous}', fnRE = /function(?:\\s+([\\w$]+))?\\s*\\(/, stack = [], fn, args, maxStackSize = 10;\n var slice = Array.prototype.slice;\n while (curr && stack.length < maxStackSize) {\n fn = fnRE.test(curr.toString()) ? RegExp.$1 || ANON : ANON;\n try {\n args = slice.call(curr['arguments'] || []);\n } catch (e) {\n args = ['Cannot access arguments: ' + e];\n }\n stack[stack.length] = fn + '(' + this.stringifyArguments(args) + ')';\n try {\n curr = curr.caller;\n } catch (e) {\n stack[stack.length] = 'Cannot access caller: ' + e;\n break;\n }\n }\n return stack;\n },\n\n /**\n * Given arguments array as a String, substituting type names for non-string types.\n *\n * @param {Arguments,Array} args\n * @return {String} stringified arguments\n */\n stringifyArguments: function(args) {\n var result = [];\n var slice = Array.prototype.slice;\n for (var i = 0; i < args.length; ++i) {\n var arg = args[i];\n if (arg === undefined) {\n result[i] = 'undefined';\n } else if (arg === null) {\n result[i] = 'null';\n } else if (arg.constructor) {\n // TODO constructor comparison does not work for iframes\n if (arg.constructor === Array) {\n if (arg.length < 3) {\n result[i] = '[' + this.stringifyArguments(arg) + ']';\n } else {\n result[i] = '[' + this.stringifyArguments(slice.call(arg, 0, 1)) + '...' + this.stringifyArguments(slice.call(arg, -1)) + ']';\n }\n } else if (arg.constructor === Object) {\n result[i] = '#object';\n } else if (arg.constructor === Function) {\n result[i] = '#function';\n } else if (arg.constructor === String) {\n result[i] = '\"' + arg + '\"';\n } else if (arg.constructor === Number) {\n result[i] = arg;\n } else {\n result[i] = '?';\n }\n }\n }\n return result.join(',');\n },\n\n sourceCache: {},\n\n /**\n * @return {String} the text from a given URL\n */\n ajax: function(url) {\n var req = this.createXMLHTTPObject();\n if (req) {\n try {\n req.open('GET', url, false);\n //req.overrideMimeType('text/plain');\n //req.overrideMimeType('text/javascript');\n req.send(null);\n //return req.status == 200 ? req.responseText : '';\n return req.responseText;\n } catch (e) {\n }\n }\n return '';\n },\n\n /**\n * Try XHR methods in order and store XHR factory.\n *\n * @return {XMLHttpRequest} XHR function or equivalent\n */\n createXMLHTTPObject: function() {\n var xmlhttp, XMLHttpFactories = [\n function() {\n return new XMLHttpRequest();\n }, function() {\n return new ActiveXObject('Msxml2.XMLHTTP');\n }, function() {\n return new ActiveXObject('Msxml3.XMLHTTP');\n }, function() {\n return new ActiveXObject('Microsoft.XMLHTTP');\n }\n ];\n for (var i = 0; i < XMLHttpFactories.length; i++) {\n try {\n xmlhttp = XMLHttpFactories[i]();\n // Use memoization to cache the factory\n this.createXMLHTTPObject = XMLHttpFactories[i];\n return xmlhttp;\n } catch (e) {\n }\n }\n },\n\n /**\n * Given a URL, check if it is in the same domain (so we can get the source\n * via Ajax).\n *\n * @param url {String} source url\n * @return {Boolean} False if we need a cross-domain request\n */\n isSameDomain: function(url) {\n return typeof location !== \"undefined\" && url.indexOf(location.hostname) !== -1; // location may not be defined, e.g. when running from nodejs.\n },\n\n /**\n * Get source code from given URL if in the same domain.\n *\n * @param url {String} JS source URL\n * @return {Array} Array of source code lines\n */\n getSource: function(url) {\n // TODO reuse source from script tags?\n if (!(url in this.sourceCache)) {\n this.sourceCache[url] = this.ajax(url).split('\\n');\n }\n return this.sourceCache[url];\n },\n\n guessAnonymousFunctions: function(stack) {\n for (var i = 0; i < stack.length; ++i) {\n var reStack = /\\{anonymous\\}\\(.*\\)@(.*)/,\n reRef = /^(.*?)(?::(\\d+))(?::(\\d+))?(?: -- .+)?$/,\n frame = stack[i], ref = reStack.exec(frame);\n\n if (ref) {\n var m = reRef.exec(ref[1]);\n if (m) { // If falsey, we did not get any file/line information\n var file = m[1], lineno = m[2], charno = m[3] || 0;\n if (file && this.isSameDomain(file) && lineno) {\n var functionName = this.guessAnonymousFunction(file, lineno, charno);\n stack[i] = frame.replace('{anonymous}', functionName);\n }\n }\n }\n }\n return stack;\n },\n\n guessAnonymousFunction: function(url, lineNo, charNo) {\n var ret;\n try {\n ret = this.findFunctionName(this.getSource(url), lineNo);\n } catch (e) {\n ret = 'getSource failed with url: ' + url + ', exception: ' + e.toString();\n }\n return ret;\n },\n\n findFunctionName: function(source, lineNo) {\n // FIXME findFunctionName fails for compressed source\n // (more than one function on the same line)\n // function {name}({args}) m[1]=name m[2]=args\n var reFunctionDeclaration = /function\\s+([^(]*?)\\s*\\(([^)]*)\\)/;\n // {name} = function ({args}) TODO args capture\n // /['\"]?([0-9A-Za-z_]+)['\"]?\\s*[:=]\\s*function(?:[^(]*)/\n var reFunctionExpression = /['\"]?([$_A-Za-z][$_A-Za-z0-9]*)['\"]?\\s*[:=]\\s*function\\b/;\n // {name} = eval()\n var reFunctionEvaluation = /['\"]?([$_A-Za-z][$_A-Za-z0-9]*)['\"]?\\s*[:=]\\s*(?:eval|new Function)\\b/;\n // Walk backwards in the source lines until we find\n // the line which matches one of the patterns above\n var code = \"\", line, maxLines = Math.min(lineNo, 20), m, commentPos;\n for (var i = 0; i < maxLines; ++i) {\n // lineNo is 1-based, source[] is 0-based\n line = source[lineNo - i - 1];\n commentPos = line.indexOf('//');\n if (commentPos >= 0) {\n line = line.substr(0, commentPos);\n }\n // TODO check other types of comments? Commented code may lead to false positive\n if (line) {\n code = line + code;\n m = reFunctionExpression.exec(code);\n if (m && m[1]) {\n return m[1];\n }\n m = reFunctionDeclaration.exec(code);\n if (m && m[1]) {\n //return m[1] + \"(\" + (m[2] || \"\") + \")\";\n return m[1];\n }\n m = reFunctionEvaluation.exec(code);\n if (m && m[1]) {\n return m[1];\n }\n }\n }\n return '(?)';\n }\n };\n\n return printStackTrace;\n}));\n","/* FileSaver.js\n * A saveAs() FileSaver implementation.\n * 2015-03-04\n *\n * By Eli Grey, http://eligrey.com\n * License: X11/MIT\n * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md\n */\n\n/*global self */\n/*jslint bitwise: true, indent: 4, laxbreak: true, laxcomma: true, smarttabs: true, plusplus: true */\n\n/*! @source http://purl.eligrey.com/github/FileSaver.js/blob/master/FileSaver.js */\n\nvar saveAs = saveAs\n // IE 10+ (native saveAs)\n || (typeof navigator !== \"undefined\" &&\n navigator.msSaveOrOpenBlob && navigator.msSaveOrOpenBlob.bind(navigator))\n // Everyone else\n || (function (view) {\n \"use strict\";\n // IE <10 is explicitly unsupported\n if (typeof navigator !== \"undefined\" &&\n /MSIE [1-9]\\./.test(navigator.userAgent)) {\n return;\n }\n var\n doc = view.document\n // only get URL when necessary in case Blob.js hasn't overridden it yet\n , get_URL = function () {\n return view.URL || view.webkitURL || view;\n }\n , save_link = doc.createElementNS(\"http://www.w3.org/1999/xhtml\", \"a\")\n , can_use_save_link = \"download\" in save_link\n , click = function (node) {\n var event = doc.createEvent(\"MouseEvents\");\n event.initMouseEvent(\n \"click\", true, false, view, 0, 0, 0, 0, 0\n , false, false, false, false, 0, null\n );\n node.dispatchEvent(event);\n }\n , webkit_req_fs = view.webkitRequestFileSystem\n , req_fs = view.requestFileSystem || webkit_req_fs || view.mozRequestFileSystem\n , throw_outside = function (ex) {\n (view.setImmediate || view.setTimeout)(function () {\n throw ex;\n }, 0);\n }\n , force_saveable_type = \"application/octet-stream\"\n , fs_min_size = 0\n // See https://code.google.com/p/chromium/issues/detail?id=375297#c7 and\n // https://github.com/eligrey/FileSaver.js/commit/485930a#commitcomment-8768047\n // for the reasoning behind the timeout and revocation flow\n , arbitrary_revoke_timeout = 500 // in ms\n , revoke = function (file) {\n var revoker = function () {\n if (typeof file === \"string\") { // file is an object URL\n get_URL().revokeObjectURL(file);\n } else { // file is a File\n file.remove();\n }\n };\n if (view.chrome) {\n revoker();\n } else {\n setTimeout(revoker, arbitrary_revoke_timeout);\n }\n }\n , dispatch = function (filesaver, event_types, event) {\n event_types = [].concat(event_types);\n var i = event_types.length;\n while (i--) {\n var listener = filesaver[\"on\" + event_types[i]];\n if (typeof listener === \"function\") {\n try {\n listener.call(filesaver, event || filesaver);\n } catch (ex) {\n throw_outside(ex);\n }\n }\n }\n }\n , FileSaver = function (blob, name) {\n // First try a.download, then web filesystem, then object URLs\n var\n filesaver = this\n , type = blob.type\n , blob_changed = false\n , object_url\n , target_view\n , dispatch_all = function () {\n dispatch(filesaver, \"writestart progress write writeend\".split(\" \"));\n }\n // on any filesys errors revert to saving with object URLs\n , fs_error = function () {\n // don't create more object URLs than needed\n if (blob_changed || !object_url) {\n object_url = get_URL().createObjectURL(blob);\n }\n if (target_view) {\n target_view.location.href = object_url;\n } else {\n var new_tab = view.open(object_url, \"_blank\");\n if (new_tab == undefined && typeof safari !== \"undefined\") {\n //Apple do not allow window.open, see http://bit.ly/1kZffRI\n view.location.href = object_url\n }\n }\n filesaver.readyState = filesaver.DONE;\n dispatch_all();\n revoke(object_url);\n }\n , abortable = function (func) {\n return function () {\n if (filesaver.readyState !== filesaver.DONE) {\n return func.apply(this, arguments);\n }\n };\n }\n , create_if_not_found = { create: true, exclusive: false }\n , slice\n ;\n filesaver.readyState = filesaver.INIT;\n if (!name) {\n name = \"download\";\n }\n if (can_use_save_link) {\n object_url = get_URL().createObjectURL(blob);\n save_link.href = object_url;\n save_link.download = name;\n click(save_link);\n filesaver.readyState = filesaver.DONE;\n dispatch_all();\n revoke(object_url);\n return;\n }\n // prepend BOM for UTF-8 XML and text/plain types\n if (/^\\s*(?:text\\/(?:plain|xml)|application\\/xml|\\S*\\/\\S*\\+xml)\\s*;.*charset\\s*=\\s*utf-8/i.test(blob.type)) {\n blob = new Blob([\"\\ufeff\", blob], { type: blob.type });\n }\n // Object and web filesystem URLs have a problem saving in Google Chrome when\n // viewed in a tab, so I force save with application/octet-stream\n // http://code.google.com/p/chromium/issues/detail?id=91158\n // Update: Google errantly closed 91158, I submitted it again:\n // https://code.google.com/p/chromium/issues/detail?id=389642\n if (view.chrome && type && type !== force_saveable_type) {\n slice = blob.slice || blob.webkitSlice;\n blob = slice.call(blob, 0, blob.size, force_saveable_type);\n blob_changed = true;\n }\n // Since I can't be sure that the guessed media type will trigger a download\n // in WebKit, I append .download to the filename.\n // https://bugs.webkit.org/show_bug.cgi?id=65440\n if (webkit_req_fs && name !== \"download\") {\n name += \".download\";\n }\n if (type === force_saveable_type || webkit_req_fs) {\n target_view = view;\n }\n if (!req_fs) {\n fs_error();\n return;\n }\n fs_min_size += blob.size;\n req_fs(view.TEMPORARY, fs_min_size, abortable(function (fs) {\n fs.root.getDirectory(\"saved\", create_if_not_found, abortable(function (dir) {\n var save = function () {\n dir.getFile(name, create_if_not_found, abortable(function (file) {\n file.createWriter(abortable(function (writer) {\n writer.onwriteend = function (event) {\n target_view.location.href = file.toURL();\n filesaver.readyState = filesaver.DONE;\n dispatch(filesaver, \"writeend\", event);\n revoke(file);\n };\n writer.onerror = function () {\n var error = writer.error;\n if (error.code !== error.ABORT_ERR) {\n fs_error();\n }\n };\n \"writestart progress write abort\".split(\" \").forEach(function (event) {\n writer[\"on\" + event] = filesaver[\"on\" + event];\n });\n writer.write(blob);\n filesaver.abort = function () {\n writer.abort();\n filesaver.readyState = filesaver.DONE;\n };\n filesaver.readyState = filesaver.WRITING;\n }), fs_error);\n }), fs_error);\n };\n dir.getFile(name, { create: false }, abortable(function (file) {\n // delete file if it already exists\n file.remove();\n save();\n }), abortable(function (ex) {\n if (ex.code === ex.NOT_FOUND_ERR) {\n save();\n } else {\n fs_error();\n }\n }));\n }), fs_error);\n }), fs_error);\n }\n , FS_proto = FileSaver.prototype\n , saveAs = function (blob, name) {\n return new FileSaver(blob, name);\n }\n ;\n FS_proto.abort = function () {\n var filesaver = this;\n filesaver.readyState = filesaver.DONE;\n dispatch(filesaver, \"abort\");\n };\n FS_proto.readyState = FS_proto.INIT = 0;\n FS_proto.WRITING = 1;\n FS_proto.DONE = 2;\n\n FS_proto.error =\n FS_proto.onwritestart =\n FS_proto.onprogress =\n FS_proto.onwrite =\n FS_proto.onabort =\n FS_proto.onerror =\n FS_proto.onwriteend =\n null;\n\n return saveAs;\n }(\n\t typeof self !== \"undefined\" && self\n\t|| typeof window !== \"undefined\" && window\n\t|| this.content\n));\n// `self` is undefined in Firefox for Android content script context\n// while `this` is nsIContentFrameMessageManager\n// with an attribute `content` that corresponds to the window\n\nif (typeof module !== \"undefined\" && module.exports) {\n module.exports.saveAs = saveAs;\n} else if ((typeof define !== \"undefined\" && define !== null) && (define.amd != null)) {\n define([], function () {\n return saveAs;\n });\n}","// Generated by CoffeeScript 1.7.1\n(function() {\n var $, cardFromNumber, cardFromType, cards, defaultFormat, formatBackCardNumber, formatBackExpiry, formatCardNumber, formatExpiry, formatForwardExpiry, formatForwardSlashAndSpace, hasTextSelected, luhnCheck, reFormatCardNumber, reFormatExpiry, restrictCVC, restrictCardNumber, restrictExpiry, restrictNumeric, setCardType,\n __slice = [].slice,\n __indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };\n\n $ = jQuery;\n\n $.payment = {};\n\n $.payment.fn = {};\n\n $.fn.payment = function() {\n var args, method;\n method = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];\n return $.payment.fn[method].apply(this, args);\n };\n\n defaultFormat = /(\\d{1,4})/g;\n\n cards = [\n {\n type: 'visaelectron',\n pattern: /^4(026|17500|405|508|844|91[37])/,\n format: defaultFormat,\n length: [16],\n cvcLength: [3],\n luhn: true\n }, {\n type: 'maestro',\n pattern: /^(5(018|0[23]|[68])|6(39|7))/,\n format: defaultFormat,\n length: [12, 13, 14, 15, 16, 17, 18, 19],\n cvcLength: [3],\n luhn: true\n }, {\n type: 'forbrugsforeningen',\n pattern: /^600/,\n format: defaultFormat,\n length: [16],\n cvcLength: [3],\n luhn: true\n }, {\n type: 'dankort',\n pattern: /^5019/,\n format: defaultFormat,\n length: [16],\n cvcLength: [3],\n luhn: true\n }, {\n type: 'visa',\n pattern: /^4/,\n format: defaultFormat,\n length: [13, 16],\n cvcLength: [3],\n luhn: true\n }, {\n type: 'mastercard',\n pattern: /^5[0-5]/,\n format: defaultFormat,\n length: [16],\n cvcLength: [3],\n luhn: true\n }, {\n type: 'amex',\n pattern: /^3[47]/,\n format: /(\\d{1,4})(\\d{1,6})?(\\d{1,5})?/,\n length: [15],\n cvcLength: [3, 4],\n luhn: true\n }, {\n type: 'dinersclub',\n pattern: /^3[0689]/,\n format: defaultFormat,\n length: [14],\n cvcLength: [3],\n luhn: true\n }, {\n type: 'discover',\n pattern: /^6([045]|22)/,\n format: defaultFormat,\n length: [16],\n cvcLength: [3],\n luhn: true\n }, {\n type: 'unionpay',\n pattern: /^(62|88)/,\n format: defaultFormat,\n length: [16, 17, 18, 19],\n cvcLength: [3],\n luhn: false\n }, {\n type: 'jcb',\n pattern: /^35/,\n format: defaultFormat,\n length: [16],\n cvcLength: [3],\n luhn: true\n }\n ];\n\n cardFromNumber = function(num) {\n var card, _i, _len;\n num = (num + '').replace(/\\D/g, '');\n for (_i = 0, _len = cards.length; _i < _len; _i++) {\n card = cards[_i];\n if (card.pattern.test(num)) {\n return card;\n }\n }\n };\n\n cardFromType = function(type) {\n var card, _i, _len;\n for (_i = 0, _len = cards.length; _i < _len; _i++) {\n card = cards[_i];\n if (card.type === type) {\n return card;\n }\n }\n };\n\n luhnCheck = function(num) {\n var digit, digits, odd, sum, _i, _len;\n odd = true;\n sum = 0;\n digits = (num + '').split('').reverse();\n for (_i = 0, _len = digits.length; _i < _len; _i++) {\n digit = digits[_i];\n digit = parseInt(digit, 10);\n if ((odd = !odd)) {\n digit *= 2;\n }\n if (digit > 9) {\n digit -= 9;\n }\n sum += digit;\n }\n return sum % 10 === 0;\n };\n\n hasTextSelected = function($target) {\n var _ref;\n if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== $target.prop('selectionEnd')) {\n return true;\n }\n if (typeof document !== \"undefined\" && document !== null ? (_ref = document.selection) != null ? typeof _ref.createRange === \"function\" ? _ref.createRange().text : void 0 : void 0 : void 0) {\n return true;\n }\n return false;\n };\n\n reFormatCardNumber = function(e) {\n return setTimeout(function() {\n var $target, value;\n $target = $(e.currentTarget);\n value = $target.val();\n value = $.payment.formatCardNumber(value);\n return $target.val(value);\n });\n };\n\n formatCardNumber = function(e) {\n var $target, card, digit, length, re, upperLength, value;\n digit = String.fromCharCode(e.which);\n if (!/^\\d+$/.test(digit)) {\n return;\n }\n $target = $(e.currentTarget);\n value = $target.val();\n card = cardFromNumber(value + digit);\n length = (value.replace(/\\D/g, '') + digit).length;\n upperLength = 16;\n if (card) {\n upperLength = card.length[card.length.length - 1];\n }\n if (length >= upperLength) {\n return;\n }\n if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) {\n return;\n }\n if (card && card.type === 'amex') {\n re = /^(\\d{4}|\\d{4}\\s\\d{6})$/;\n } else {\n re = /(?:^|\\s)(\\d{4})$/;\n }\n if (re.test(value)) {\n e.preventDefault();\n return setTimeout(function() {\n return $target.val(value + ' ' + digit);\n });\n } else if (re.test(value + digit)) {\n e.preventDefault();\n return setTimeout(function() {\n return $target.val(value + digit + ' ');\n });\n }\n };\n\n formatBackCardNumber = function(e) {\n var $target, value;\n $target = $(e.currentTarget);\n value = $target.val();\n if (e.which !== 8) {\n return;\n }\n if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) {\n return;\n }\n if (/\\d\\s$/.test(value)) {\n e.preventDefault();\n return setTimeout(function() {\n return $target.val(value.replace(/\\d\\s$/, ''));\n });\n } else if (/\\s\\d?$/.test(value)) {\n e.preventDefault();\n return setTimeout(function() {\n return $target.val(value.replace(/\\s\\d?$/, ''));\n });\n }\n };\n\n reFormatExpiry = function(e) {\n return setTimeout(function() {\n var $target, value;\n $target = $(e.currentTarget);\n value = $target.val();\n value = $.payment.formatExpiry(value);\n return $target.val(value);\n });\n };\n\n formatExpiry = function(e) {\n var $target, digit, val;\n digit = String.fromCharCode(e.which);\n if (!/^\\d+$/.test(digit)) {\n return;\n }\n $target = $(e.currentTarget);\n val = $target.val() + digit;\n if (/^\\d$/.test(val) && (val !== '0' && val !== '1')) {\n e.preventDefault();\n return setTimeout(function() {\n return $target.val(\"0\" + val + \" / \");\n });\n } else if (/^\\d\\d$/.test(val)) {\n e.preventDefault();\n return setTimeout(function() {\n return $target.val(\"\" + val + \" / \");\n });\n }\n };\n\n formatForwardExpiry = function(e) {\n var $target, digit, val;\n digit = String.fromCharCode(e.which);\n if (!/^\\d+$/.test(digit)) {\n return;\n }\n $target = $(e.currentTarget);\n val = $target.val();\n if (/^\\d\\d$/.test(val)) {\n return $target.val(\"\" + val + \" / \");\n }\n };\n\n formatForwardSlashAndSpace = function(e) {\n var $target, val, which;\n which = String.fromCharCode(e.which);\n if (!(which === '/' || which === ' ')) {\n return;\n }\n $target = $(e.currentTarget);\n val = $target.val();\n if (/^\\d$/.test(val) && val !== '0') {\n return $target.val(\"0\" + val + \" / \");\n }\n };\n\n formatBackExpiry = function(e) {\n var $target, value;\n $target = $(e.currentTarget);\n value = $target.val();\n if (e.which !== 8) {\n return;\n }\n if (($target.prop('selectionStart') != null) && $target.prop('selectionStart') !== value.length) {\n return;\n }\n if (/\\s\\/\\s\\d?$/.test(value)) {\n e.preventDefault();\n return setTimeout(function() {\n return $target.val(value.replace(/\\s\\/\\s\\d?$/, ''));\n });\n }\n };\n\n restrictNumeric = function(e) {\n var input;\n if (e.metaKey || e.ctrlKey) {\n return true;\n }\n if (e.which === 32) {\n return false;\n }\n if (e.which === 0) {\n return true;\n }\n if (e.which < 33) {\n return true;\n }\n input = String.fromCharCode(e.which);\n return !!/[\\d\\s]/.test(input);\n };\n\n restrictCardNumber = function(e) {\n var $target, card, digit, value;\n $target = $(e.currentTarget);\n digit = String.fromCharCode(e.which);\n if (!/^\\d+$/.test(digit)) {\n return;\n }\n if (hasTextSelected($target)) {\n return;\n }\n value = ($target.val() + digit).replace(/\\D/g, '');\n card = cardFromNumber(value);\n if (card) {\n return value.length <= card.length[card.length.length - 1];\n } else {\n return value.length <= 16;\n }\n };\n\n restrictExpiry = function(e) {\n var $target, digit, value;\n $target = $(e.currentTarget);\n digit = String.fromCharCode(e.which);\n if (!/^\\d+$/.test(digit)) {\n return;\n }\n if (hasTextSelected($target)) {\n return;\n }\n value = $target.val() + digit;\n value = value.replace(/\\D/g, '');\n if (value.length > 6) {\n return false;\n }\n };\n\n restrictCVC = function(e) {\n var $target, digit, val;\n $target = $(e.currentTarget);\n digit = String.fromCharCode(e.which);\n if (!/^\\d+$/.test(digit)) {\n return;\n }\n if (hasTextSelected($target)) {\n return;\n }\n val = $target.val() + digit;\n return val.length <= 4;\n };\n\n setCardType = function(e) {\n var $target, allTypes, card, cardType, val;\n $target = $(e.currentTarget);\n val = $target.val();\n cardType = $.payment.cardType(val) || 'unknown';\n if (!$target.hasClass(cardType)) {\n allTypes = (function() {\n var _i, _len, _results;\n _results = [];\n for (_i = 0, _len = cards.length; _i < _len; _i++) {\n card = cards[_i];\n _results.push(card.type);\n }\n return _results;\n })();\n $target.removeClass('unknown');\n $target.removeClass(allTypes.join(' '));\n $target.addClass(cardType);\n $target.toggleClass('identified', cardType !== 'unknown');\n return $target.trigger('payment.cardType', cardType);\n }\n };\n\n $.payment.fn.formatCardCVC = function() {\n this.payment('restrictNumeric');\n this.on('keypress', restrictCVC);\n return this;\n };\n\n $.payment.fn.formatCardExpiry = function() {\n this.payment('restrictNumeric');\n this.on('keypress', restrictExpiry);\n this.on('keypress', formatExpiry);\n this.on('keypress', formatForwardSlashAndSpace);\n this.on('keypress', formatForwardExpiry);\n this.on('keydown', formatBackExpiry);\n this.on('change', reFormatExpiry);\n this.on('input', reFormatExpiry);\n return this;\n };\n\n $.payment.fn.formatCardNumber = function() {\n this.payment('restrictNumeric');\n this.on('keypress', restrictCardNumber);\n this.on('keypress', formatCardNumber);\n this.on('keydown', formatBackCardNumber);\n this.on('keyup', setCardType);\n this.on('paste', reFormatCardNumber);\n this.on('change', reFormatCardNumber);\n this.on('input', reFormatCardNumber);\n this.on('input', setCardType);\n return this;\n };\n\n $.payment.fn.restrictNumeric = function() {\n this.on('keypress', restrictNumeric);\n return this;\n };\n\n $.payment.fn.cardExpiryVal = function() {\n return $.payment.cardExpiryVal($(this).val());\n };\n\n $.payment.cardExpiryVal = function(value) {\n var month, prefix, year, _ref;\n value = value.replace(/\\s/g, '');\n _ref = value.split('/', 2), month = _ref[0], year = _ref[1];\n if ((year != null ? year.length : void 0) === 2 && /^\\d+$/.test(year)) {\n prefix = (new Date).getFullYear();\n prefix = prefix.toString().slice(0, 2);\n year = prefix + year;\n }\n month = parseInt(month, 10);\n year = parseInt(year, 10);\n return {\n month: month,\n year: year\n };\n };\n\n $.payment.validateCardNumber = function(num) {\n var card, _ref;\n num = (num + '').replace(/\\s+|-/g, '');\n if (!/^\\d+$/.test(num)) {\n return false;\n }\n card = cardFromNumber(num);\n if (!card) {\n return false;\n }\n return (_ref = num.length, __indexOf.call(card.length, _ref) >= 0) && (card.luhn === false || luhnCheck(num));\n };\n\n $.payment.validateCardExpiry = function(month, year) {\n var currentTime, expiry, _ref;\n if (typeof month === 'object' && 'month' in month) {\n _ref = month, month = _ref.month, year = _ref.year;\n }\n if (!(month && year)) {\n return false;\n }\n month = $.trim(month);\n year = $.trim(year);\n if (!/^\\d+$/.test(month)) {\n return false;\n }\n if (!/^\\d+$/.test(year)) {\n return false;\n }\n if (!((1 <= month && month <= 12))) {\n return false;\n }\n if (year.length === 2) {\n if (year < 70) {\n year = \"20\" + year;\n } else {\n year = \"19\" + year;\n }\n }\n if (year.length !== 4) {\n return false;\n }\n expiry = new Date(year, month);\n currentTime = new Date;\n expiry.setMonth(expiry.getMonth() - 1);\n expiry.setMonth(expiry.getMonth() + 1, 1);\n return expiry > currentTime;\n };\n\n $.payment.validateCardCVC = function(cvc, type) {\n var card, _ref;\n cvc = $.trim(cvc);\n if (!/^\\d+$/.test(cvc)) {\n return false;\n }\n card = cardFromType(type);\n if (card != null) {\n return _ref = cvc.length, __indexOf.call(card.cvcLength, _ref) >= 0;\n } else {\n return cvc.length >= 3 && cvc.length < 4;\n }\n };\n\n $.payment.cardType = function(num) {\n var _ref;\n if (!num) {\n return null;\n }\n return ((_ref = cardFromNumber(num)) != null ? _ref.type : void 0) || null;\n };\n\n $.payment.formatCardNumber = function(num) {\n var card, groups, upperLength, _ref;\n card = cardFromNumber(num);\n if (!card) {\n return num;\n }\n upperLength = card.length[card.length.length - 1];\n num = num.replace(/\\D/g, '');\n num = num.slice(0, upperLength);\n if (card.format.global) {\n return (_ref = num.match(card.format)) != null ? _ref.join(' ') : void 0;\n } else {\n groups = card.format.exec(num);\n if (groups == null) {\n return;\n }\n groups.shift();\n groups = $.grep(groups, function(n) {\n return n;\n });\n return groups.join(' ');\n }\n };\n\n $.payment.formatExpiry = function(expiry) {\n var mon, parts, sep, year;\n parts = expiry.match(/^\\D*(\\d{1,2})(\\D+)?(\\d{1,4})?/);\n if (!parts) {\n return '';\n }\n mon = parts[1] || '';\n sep = parts[2] || '';\n year = parts[3] || '';\n if (year.length > 0 || (sep.length > 0 && !(/\\ \\/?\\ ?/.test(sep)))) {\n sep = ' / ';\n }\n if (mon.length === 1 && (mon !== '0' && mon !== '1')) {\n mon = \"0\" + mon;\n sep = ' / ';\n }\n return mon + sep + year;\n };\n\n}).call(this);\n","/**\n * Restful Resources service for AngularJS apps\n * @version v1.4.0 - 2014-04-25 * @link https://github.com/mgonto/restangular\n * @author Martin Gontovnikas \n * @license MIT License, http://www.opensource.org/licenses/MIT\n */(function () {\n\n \tvar module = angular.module('restangular', []);\n\n \tmodule.provider('Restangular', function () {\n \t\t// Configuration\n \t\tvar Configurer = {};\n \t\tConfigurer.init = function (object, config) {\n \t\t\t/**\n * Those are HTTP safe methods for which there is no need to pass any data with the request.\n */\n\n \t\t\tobject.configuration = config;\n\n \t\t\tvar safeMethods = [\"get\", \"head\", \"options\", \"trace\", \"getlist\"];\n \t\t\tconfig.isSafe = function (operation) {\n \t\t\t\treturn _.contains(safeMethods, operation.toLowerCase());\n \t\t\t};\n\n \t\t\tvar absolutePattern = /^https?:\\/\\//i;\n \t\t\tconfig.isAbsoluteUrl = function (string) {\n \t\t\t\treturn _.isUndefined(config.absoluteUrl) || _.isNull(config.absoluteUrl) ?\n\t\t\t\t\t\tstring && absolutePattern.test(string) :\n\t\t\t\t\t\tconfig.absoluteUrl;\n \t\t\t};\n\n \t\t\tconfig.absoluteUrl = _.isUndefined(config.absoluteUrl) ? true : config.absoluteUrl;\n \t\t\tobject.setSelfLinkAbsoluteUrl = function (value) {\n \t\t\t\tconfig.absoluteUrl = value;\n \t\t\t};\n \t\t\t/**\n * This is the BaseURL to be used with Restangular\n */\n \t\t\tconfig.baseUrl = _.isUndefined(config.baseUrl) ? \"\" : config.baseUrl;\n \t\t\tobject.setBaseUrl = function (newBaseUrl) {\n \t\t\t\tconfig.baseUrl = /\\/$/.test(newBaseUrl)\n ? newBaseUrl.substring(0, newBaseUrl.length - 1)\n : newBaseUrl;\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\t/**\n * Sets the extra fields to keep from the parents\n */\n \t\t\tconfig.extraFields = config.extraFields || [];\n \t\t\tobject.setExtraFields = function (newExtraFields) {\n \t\t\t\tconfig.extraFields = newExtraFields;\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\t/**\n * Some default $http parameter to be used in EVERY call\n **/\n \t\t\tconfig.defaultHttpFields = config.defaultHttpFields || {};\n \t\t\tobject.setDefaultHttpFields = function (values) {\n \t\t\t\tconfig.defaultHttpFields = values;\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tconfig.withHttpValues = function (httpLocalConfig, obj) {\n \t\t\t\treturn _.defaults(obj, httpLocalConfig, config.defaultHttpFields);\n \t\t\t};\n\n \t\t\tconfig.encodeIds = _.isUndefined(config.encodeIds) ? true : config.encodeIds;\n \t\t\tobject.setEncodeIds = function (encode) {\n \t\t\t\tconfig.encodeIds = encode;\n \t\t\t};\n\n \t\t\tconfig.defaultRequestParams = config.defaultRequestParams || {\n \t\t\t\tget: {},\n \t\t\t\tpost: {},\n \t\t\t\tput: {},\n \t\t\t\tremove: {},\n \t\t\t\tcommon: {}\n \t\t\t};\n\n \t\t\tobject.setDefaultRequestParams = function (param1, param2) {\n \t\t\t\tvar methods = [],\n\t\t\t\t\tparams = param2 || param1;\n \t\t\t\tif (!_.isUndefined(param2)) {\n \t\t\t\t\tif (_.isArray(param1)) {\n \t\t\t\t\t\tmethods = param1;\n \t\t\t\t\t} else {\n \t\t\t\t\t\tmethods.push(param1);\n \t\t\t\t\t}\n \t\t\t\t} else {\n \t\t\t\t\tmethods.push('common');\n \t\t\t\t}\n\n \t\t\t\t_.each(methods, function (method) {\n \t\t\t\t\tconfig.defaultRequestParams[method] = params;\n \t\t\t\t});\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tobject.requestParams = config.defaultRequestParams;\n\n\n \t\t\tconfig.defaultHeaders = config.defaultHeaders || {};\n \t\t\tobject.setDefaultHeaders = function (headers) {\n \t\t\t\tconfig.defaultHeaders = headers;\n \t\t\t\tobject.defaultHeaders = config.defaultHeaders;\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tobject.defaultHeaders = config.defaultHeaders;\n\n \t\t\t/**\n * Method overriders will set which methods are sent via POST with an X-HTTP-Method-Override\n **/\n \t\t\tconfig.methodOverriders = config.methodOverriders || [];\n \t\t\tobject.setMethodOverriders = function (values) {\n \t\t\t\tvar overriders = _.extend([], values);\n \t\t\t\tif (config.isOverridenMethod('delete', overriders)) {\n \t\t\t\t\toverriders.push(\"remove\");\n \t\t\t\t}\n \t\t\t\tconfig.methodOverriders = overriders;\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tconfig.jsonp = _.isUndefined(config.jsonp) ? false : config.jsonp;\n \t\t\tobject.setJsonp = function (active) {\n \t\t\t\tconfig.jsonp = active;\n \t\t\t};\n\n \t\t\tconfig.isOverridenMethod = function (method, values) {\n \t\t\t\tvar search = values || config.methodOverriders;\n \t\t\t\treturn !_.isUndefined(_.find(search, function (one) {\n \t\t\t\t\treturn one.toLowerCase() === method.toLowerCase();\n \t\t\t\t}));\n \t\t\t};\n\n \t\t\t/**\n * Sets the URL creator type. For now, only Path is created. In the future we'll have queryParams\n **/\n \t\t\tconfig.urlCreator = config.urlCreator || \"path\";\n \t\t\tobject.setUrlCreator = function (name) {\n \t\t\t\tif (!_.has(config.urlCreatorFactory, name)) {\n \t\t\t\t\tthrow new Error(\"URL Path selected isn't valid\");\n \t\t\t\t}\n\n \t\t\t\tconfig.urlCreator = name;\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\t/**\n * You can set the restangular fields here. The 3 required fields for Restangular are:\n *\n * id: Id of the element\n * route: name of the route of this element\n * parentResource: the reference to the parent resource\n *\n * All of this fields except for id, are handled (and created) by Restangular. By default,\n * the field values will be id, route and parentResource respectively\n */\n \t\t\tconfig.restangularFields = config.restangularFields || {\n \t\t\t\tid: \"id\",\n \t\t\t\troute: \"route\",\n \t\t\t\tparentResource: \"parentResource\",\n \t\t\t\trestangularCollection: \"restangularCollection\",\n \t\t\t\tcannonicalId: \"__cannonicalId\",\n \t\t\t\tetag: \"restangularEtag\",\n \t\t\t\tselfLink: \"href\",\n \t\t\t\tget: \"get\",\n \t\t\t\tgetList: \"getList\",\n \t\t\t\tput: \"put\",\n \t\t\t\tpost: \"post\",\n \t\t\t\tremove: \"remove\",\n \t\t\t\thead: \"head\",\n \t\t\t\ttrace: \"trace\",\n \t\t\t\toptions: \"options\",\n \t\t\t\tpatch: \"patch\",\n \t\t\t\tgetRestangularUrl: \"getRestangularUrl\",\n \t\t\t\tgetRequestedUrl: \"getRequestedUrl\",\n \t\t\t\tputElement: \"putElement\",\n \t\t\t\taddRestangularMethod: \"addRestangularMethod\",\n \t\t\t\tgetParentList: \"getParentList\",\n \t\t\t\tclone: \"clone\",\n \t\t\t\tids: \"ids\",\n \t\t\t\thttpConfig: '_$httpConfig',\n \t\t\t\treqParams: 'reqParams',\n \t\t\t\tone: 'one',\n \t\t\t\tall: 'all',\n \t\t\t\tseveral: 'several',\n \t\t\t\toneUrl: 'oneUrl',\n \t\t\t\tallUrl: 'allUrl',\n \t\t\t\tcustomPUT: 'customPUT',\n \t\t\t\tcustomPOST: 'customPOST',\n \t\t\t\tcustomDELETE: 'customDELETE',\n \t\t\t\tcustomGET: 'customGET',\n \t\t\t\tcustomGETLIST: 'customGETLIST',\n \t\t\t\tcustomOperation: 'customOperation',\n \t\t\t\tdoPUT: 'doPUT',\n \t\t\t\tdoPOST: 'doPOST',\n \t\t\t\tdoDELETE: 'doDELETE',\n \t\t\t\tdoGET: 'doGET',\n \t\t\t\tdoGETLIST: 'doGETLIST',\n \t\t\t\tfromServer: 'fromServer',\n \t\t\t\twithConfig: 'withConfig',\n \t\t\t\twithHttpConfig: 'withHttpConfig',\n \t\t\t\tsingleOne: 'singleOne',\n \t\t\t\tplain: 'plain',\n \t\t\t\tsave: 'save'\n \t\t\t};\n \t\t\tobject.setRestangularFields = function (resFields) {\n \t\t\t\tconfig.restangularFields =\n _.extend(config.restangularFields, resFields);\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tconfig.isRestangularized = function (obj) {\n \t\t\t\treturn !!obj[config.restangularFields.one] || !!obj[config.restangularFields.all];\n \t\t\t};\n\n \t\t\tconfig.setFieldToElem = function (field, elem, value) {\n \t\t\t\tvar properties = field.split('.');\n \t\t\t\tvar idValue = elem;\n \t\t\t\t_.each(_.initial(properties), function (prop) {\n \t\t\t\t\tidValue[prop] = {};\n \t\t\t\t\tidValue = idValue[prop];\n \t\t\t\t});\n \t\t\t\tidValue[_.last(properties)] = value;\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tconfig.getFieldFromElem = function (field, elem) {\n \t\t\t\tvar properties = field.split('.');\n \t\t\t\tvar idValue = elem;\n \t\t\t\t_.each(properties, function (prop) {\n \t\t\t\t\tif (idValue) {\n \t\t\t\t\t\tidValue = idValue[prop];\n \t\t\t\t\t}\n \t\t\t\t});\n \t\t\t\treturn angular.copy(idValue);\n \t\t\t};\n\n \t\t\tconfig.setIdToElem = function (elem, id) {\n \t\t\t\tconfig.setFieldToElem(config.restangularFields.id, elem, id);\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tconfig.getIdFromElem = function (elem) {\n \t\t\t\treturn config.getFieldFromElem(config.restangularFields.id, elem);\n \t\t\t};\n\n \t\t\tconfig.isValidId = function (elemId) {\n \t\t\t\treturn \"\" !== elemId && !_.isUndefined(elemId) && !_.isNull(elemId);\n \t\t\t};\n\n \t\t\tconfig.setUrlToElem = function (elem, url, route) {\n \t\t\t\tconfig.setFieldToElem(config.restangularFields.selfLink, elem, url);\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tconfig.getUrlFromElem = function (elem) {\n \t\t\t\treturn config.getFieldFromElem(config.restangularFields.selfLink, elem);\n \t\t\t};\n\n \t\t\tconfig.useCannonicalId = _.isUndefined(config.useCannonicalId) ? false : config.useCannonicalId;\n \t\t\tobject.setUseCannonicalId = function (value) {\n \t\t\t\tconfig.useCannonicalId = value;\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tconfig.getCannonicalIdFromElem = function (elem) {\n \t\t\t\tvar cannonicalId = elem[config.restangularFields.cannonicalId];\n \t\t\t\tvar actualId = config.isValidId(cannonicalId) ?\n \t\t\t\t\tcannonicalId : config.getIdFromElem(elem);\n \t\t\t\treturn actualId;\n \t\t\t};\n\n \t\t\t/**\n * Sets the Response parser. This is used in case your response isn't directly the data.\n * For example if you have a response like {meta: {'meta'}, data: {name: 'Gonto'}}\n * you can extract this data which is the one that needs wrapping\n *\n * The ResponseExtractor is a function that receives the response and the method executed.\n */\n\n \t\t\tconfig.responseInterceptors = config.responseInterceptors || [];\n\n \t\t\tconfig.defaultResponseInterceptor = function (data, operation,\n what, url, response, deferred) {\n \t\t\t\treturn data;\n \t\t\t};\n\n \t\t\tconfig.responseExtractor = function (data, operation,\n what, url, response, deferred) {\n \t\t\t\tvar interceptors = angular.copy(config.responseInterceptors);\n \t\t\t\tinterceptors.push(config.defaultResponseInterceptor);\n \t\t\t\tvar theData = data;\n \t\t\t\t_.each(interceptors, function (interceptor) {\n \t\t\t\t\ttheData = interceptor(theData, operation,\n\t\t\t\t\t what, url, response, deferred);\n \t\t\t\t});\n \t\t\t\treturn theData;\n \t\t\t};\n\n \t\t\tobject.addResponseInterceptor = function (extractor) {\n \t\t\t\tconfig.responseInterceptors.push(extractor);\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tobject.setResponseInterceptor = object.addResponseInterceptor;\n \t\t\tobject.setResponseExtractor = object.addResponseInterceptor;\n\n \t\t\t/**\n * Response interceptor is called just before resolving promises.\n */\n\n\n \t\t\t/**\n * Request interceptor is called before sending an object to the server.\n */\n \t\t\tconfig.requestInterceptors = config.requestInterceptors || [];\n\n \t\t\tconfig.defaultInterceptor = function (element, operation,\n\t\t\t path, url, headers, params, httpConfig) {\n \t\t\t\treturn {\n \t\t\t\t\telement: element,\n \t\t\t\t\theaders: headers,\n \t\t\t\t\tparams: params,\n \t\t\t\t\thttpConfig: httpConfig\n \t\t\t\t};\n \t\t\t};\n\n \t\t\tconfig.fullRequestInterceptor = function (element, operation,\n path, url, headers, params, httpConfig) {\n \t\t\t\tvar interceptors = angular.copy(config.requestInterceptors);\n \t\t\t\tvar defaultRequest = config.defaultInterceptor(element, operation, path, url, headers, params, httpConfig);\n \t\t\t\treturn _.reduce(interceptors, function (request, interceptor) {\n \t\t\t\t\treturn _.extend(request, interceptor(request.element, operation,\n\t\t\t\t\t path, url, request.headers, request.params, request.httpConfig));\n \t\t\t\t}, defaultRequest);\n \t\t\t};\n\n \t\t\tobject.addRequestInterceptor = function (interceptor) {\n \t\t\t\tconfig.requestInterceptors.push(function (elem, operation, path, url, headers, params, httpConfig) {\n \t\t\t\t\treturn {\n \t\t\t\t\t\theaders: headers,\n \t\t\t\t\t\tparams: params,\n \t\t\t\t\t\telement: interceptor(elem, operation, path, url),\n \t\t\t\t\t\thttpConfig: httpConfig\n \t\t\t\t\t};\n \t\t\t\t});\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tobject.setRequestInterceptor = object.addRequestInterceptor;\n\n \t\t\tobject.addFullRequestInterceptor = function (interceptor) {\n \t\t\t\tconfig.requestInterceptors.push(interceptor);\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tobject.setFullRequestInterceptor = object.addFullRequestInterceptor;\n\n \t\t\tconfig.errorInterceptor = config.errorInterceptor || function () { };\n\n \t\t\tobject.setErrorInterceptor = function (interceptor) {\n \t\t\t\tconfig.errorInterceptor = interceptor;\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tconfig.onBeforeElemRestangularized = config.onBeforeElemRestangularized || function (elem) {\n \t\t\t\treturn elem;\n \t\t\t};\n \t\t\tobject.setOnBeforeElemRestangularized = function (post) {\n \t\t\t\tconfig.onBeforeElemRestangularized = post;\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\t/**\n * This method is called after an element has been \"Restangularized\".\n *\n * It receives the element, a boolean indicating if it's an element or a collection\n * and the name of the model\n *\n */\n \t\t\tconfig.onElemRestangularized = config.onElemRestangularized || function (elem) {\n \t\t\t\treturn elem;\n \t\t\t};\n \t\t\tobject.setOnElemRestangularized = function (post) {\n \t\t\t\tconfig.onElemRestangularized = post;\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tconfig.shouldSaveParent = config.shouldSaveParent || function () {\n \t\t\t\treturn true;\n \t\t\t};\n \t\t\tobject.setParentless = function (values) {\n \t\t\t\tif (_.isArray(values)) {\n \t\t\t\t\tconfig.shouldSaveParent = function (route) {\n \t\t\t\t\t\treturn !_.contains(values, route);\n \t\t\t\t\t};\n \t\t\t\t} else if (_.isBoolean(values)) {\n \t\t\t\t\tconfig.shouldSaveParent = function () {\n \t\t\t\t\t\treturn !values;\n \t\t\t\t\t};\n \t\t\t\t}\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\t/**\n * This lets you set a suffix to every request.\n *\n * For example, if your api requires that for JSon requests you do /users/123.json, you can set that\n * in here.\n *\n *\n * By default, the suffix is null\n */\n \t\t\tconfig.suffix = _.isUndefined(config.suffix) ? null : config.suffix;\n \t\t\tobject.setRequestSuffix = function (newSuffix) {\n \t\t\t\tconfig.suffix = newSuffix;\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\t/**\n * Add element transformers for certain routes.\n */\n \t\t\tconfig.transformers = config.transformers || {};\n \t\t\tobject.addElementTransformer = function (type, secondArg, thirdArg) {\n \t\t\t\tvar isCollection = null;\n \t\t\t\tvar transformer = null;\n \t\t\t\tif (arguments.length === 2) {\n \t\t\t\t\ttransformer = secondArg;\n \t\t\t\t} else {\n \t\t\t\t\ttransformer = thirdArg;\n \t\t\t\t\tisCollection = secondArg;\n \t\t\t\t}\n\n \t\t\t\tvar typeTransformers = config.transformers[type];\n \t\t\t\tif (!typeTransformers) {\n \t\t\t\t\ttypeTransformers = config.transformers[type] = [];\n \t\t\t\t}\n\n \t\t\t\ttypeTransformers.push(function (coll, elem) {\n \t\t\t\t\tif (_.isNull(isCollection) || (coll == isCollection)) {\n \t\t\t\t\t\treturn transformer(elem);\n \t\t\t\t\t}\n \t\t\t\t\treturn elem;\n \t\t\t\t});\n\n \t\t\t\treturn object;\n \t\t\t};\n\n \t\t\tobject.extendCollection = function (route, fn) {\n \t\t\t\treturn object.addElementTransformer(route, true, fn);\n \t\t\t};\n\n \t\t\tobject.extendModel = function (route, fn) {\n \t\t\t\treturn object.addElementTransformer(route, false, fn);\n \t\t\t};\n\n \t\t\tconfig.transformElem = function (elem, isCollection, route, Restangular, force) {\n \t\t\t\tif (!force && !config.transformLocalElements && !elem[config.restangularFields.fromServer]) {\n \t\t\t\t\treturn elem;\n \t\t\t\t}\n \t\t\t\tvar typeTransformers = config.transformers[route];\n \t\t\t\tvar changedElem = elem;\n \t\t\t\tif (typeTransformers) {\n \t\t\t\t\t_.each(typeTransformers, function (transformer) {\n \t\t\t\t\t\tchangedElem = transformer(isCollection, changedElem);\n \t\t\t\t\t});\n \t\t\t\t}\n \t\t\t\treturn config.onElemRestangularized(changedElem,\n isCollection, route, Restangular);\n \t\t\t};\n\n \t\t\tconfig.transformLocalElements = _.isUndefined(config.transformLocalElements) ? false : config.transformLocalElements;\n \t\t\tobject.setTransformOnlyServerElements = function (active) {\n \t\t\t\tconfig.transformLocalElements = !active;\n \t\t\t}\n\n \t\t\tconfig.fullResponse = _.isUndefined(config.fullResponse) ? false : config.fullResponse;\n \t\t\tobject.setFullResponse = function (full) {\n \t\t\t\tconfig.fullResponse = full;\n \t\t\t\treturn this;\n \t\t\t};\n\n\n\n\n\n \t\t\t//Internal values and functions\n \t\t\tconfig.urlCreatorFactory = {};\n\n \t\t\t/**\n * Base URL Creator. Base prototype for everything related to it\n **/\n\n \t\t\tvar BaseCreator = function () {\n \t\t\t};\n\n \t\t\tBaseCreator.prototype.setConfig = function (config) {\n \t\t\t\tthis.config = config;\n \t\t\t\treturn this;\n \t\t\t};\n\n \t\t\tBaseCreator.prototype.parentsArray = function (current) {\n \t\t\t\tvar parents = [];\n \t\t\t\twhile (current) {\n \t\t\t\t\tparents.push(current);\n \t\t\t\t\tcurrent = current[this.config.restangularFields.parentResource];\n \t\t\t\t}\n \t\t\t\treturn parents.reverse();\n \t\t\t};\n\n \t\t\tfunction RestangularResource(config, $http, url, configurer) {\n \t\t\t\tvar resource = {};\n \t\t\t\t_.each(_.keys(configurer), function (key) {\n \t\t\t\t\tvar value = configurer[key];\n\n \t\t\t\t\t// Add default parameters\n \t\t\t\t\tvalue.params = _.extend({}, value.params,\n\t\t\t\t\t\t\tconfig.defaultRequestParams[value.method.toLowerCase()]);\n \t\t\t\t\t// We don't want the ? if no params are there\n \t\t\t\t\tif (_.isEmpty(value.params)) {\n \t\t\t\t\t\tdelete value.params;\n \t\t\t\t\t}\n\n \t\t\t\t\tif (config.isSafe(value.method)) {\n\n \t\t\t\t\t\tresource[key] = function () {\n \t\t\t\t\t\t\treturn $http(_.extend(value, {\n \t\t\t\t\t\t\t\turl: url\n \t\t\t\t\t\t\t}));\n \t\t\t\t\t\t};\n\n \t\t\t\t\t} else {\n\n \t\t\t\t\t\tresource[key] = function (data) {\n \t\t\t\t\t\t\treturn $http(_.extend(value, {\n \t\t\t\t\t\t\t\turl: url,\n \t\t\t\t\t\t\t\tdata: data\n \t\t\t\t\t\t\t}));\n \t\t\t\t\t\t};\n\n \t\t\t\t\t}\n \t\t\t\t});\n\n \t\t\t\treturn resource;\n \t\t\t}\n\n \t\t\tBaseCreator.prototype.resource = function (current, $http, localHttpConfig, callHeaders, callParams, what, etag, operation) {\n\n \t\t\t\tvar params = _.defaults(callParams || {}, this.config.defaultRequestParams.common);\n \t\t\t\tvar headers = _.defaults(callHeaders || {}, this.config.defaultHeaders);\n\n \t\t\t\tif (etag) {\n \t\t\t\t\tif (!config.isSafe(operation)) {\n \t\t\t\t\t\theaders['If-Match'] = etag;\n \t\t\t\t\t} else {\n \t\t\t\t\t\theaders['If-None-Match'] = etag;\n \t\t\t\t\t}\n \t\t\t\t}\n\n \t\t\t\tvar url = this.base(current);\n\n \t\t\t\tif (what) {\n \t\t\t\t\tvar add = '';\n \t\t\t\t\tif (!/\\/$/.test(url)) {\n \t\t\t\t\t\tadd += '/';\n \t\t\t\t\t}\n \t\t\t\t\tadd += what;\n \t\t\t\t\turl += add;\n \t\t\t\t}\n\n \t\t\t\tif (this.config.suffix\n && url.indexOf(this.config.suffix, url.length - this.config.suffix.length) === -1\n && !this.config.getUrlFromElem(current)) {\n \t\t\t\t\turl += this.config.suffix;\n \t\t\t\t}\n\n \t\t\t\tcurrent[this.config.restangularFields.httpConfig] = undefined;\n\n\n \t\t\t\treturn RestangularResource(this.config, $http, url, {\n \t\t\t\t\tgetList: this.config.withHttpValues(localHttpConfig,\n {\n \tmethod: 'GET',\n \tparams: params,\n \theaders: headers\n }),\n\n \t\t\t\t\tget: this.config.withHttpValues(localHttpConfig,\n {\n \tmethod: 'GET',\n \tparams: params,\n \theaders: headers\n }),\n\n \t\t\t\t\tjsonp: this.config.withHttpValues(localHttpConfig,\n {\n \tmethod: 'jsonp',\n \tparams: params,\n \theaders: headers\n }),\n\n \t\t\t\t\tput: this.config.withHttpValues(localHttpConfig,\n {\n \tmethod: 'PUT',\n \tparams: params,\n \theaders: headers\n }),\n\n \t\t\t\t\tpost: this.config.withHttpValues(localHttpConfig,\n {\n \tmethod: 'POST',\n \tparams: params,\n \theaders: headers\n }),\n\n \t\t\t\t\tremove: this.config.withHttpValues(localHttpConfig,\n {\n \tmethod: 'DELETE',\n \tparams: params,\n \theaders: headers\n }),\n\n \t\t\t\t\thead: this.config.withHttpValues(localHttpConfig,\n {\n \tmethod: 'HEAD',\n \tparams: params,\n \theaders: headers\n }),\n\n \t\t\t\t\ttrace: this.config.withHttpValues(localHttpConfig,\n {\n \tmethod: 'TRACE',\n \tparams: params,\n \theaders: headers\n }),\n\n \t\t\t\t\toptions: this.config.withHttpValues(localHttpConfig,\n {\n \tmethod: 'OPTIONS',\n \tparams: params,\n \theaders: headers\n }),\n\n \t\t\t\t\tpatch: this.config.withHttpValues(localHttpConfig,\n {\n \tmethod: 'PATCH',\n \tparams: params,\n \theaders: headers\n })\n \t\t\t\t});\n \t\t\t};\n\n \t\t\t/**\n * This is the Path URL creator. It uses Path to show Hierarchy in the Rest API.\n * This means that if you have an Account that then has a set of Buildings, a URL to a building\n * would be /accounts/123/buildings/456\n **/\n \t\t\tvar Path = function () {\n \t\t\t};\n\n \t\t\tPath.prototype = new BaseCreator();\n\n \t\t\tPath.prototype.base = function (current) {\n \t\t\t\tvar __this = this;\n \t\t\t\treturn _.reduce(this.parentsArray(current), function (acum, elem) {\n \t\t\t\t\tvar elemUrl;\n \t\t\t\t\tvar elemSelfLink = __this.config.getUrlFromElem(elem);\n \t\t\t\t\tif (elemSelfLink) {\n \t\t\t\t\t\tif (__this.config.isAbsoluteUrl(elemSelfLink)) {\n \t\t\t\t\t\t\treturn elemSelfLink;\n \t\t\t\t\t\t} else {\n \t\t\t\t\t\t\telemUrl = elemSelfLink;\n \t\t\t\t\t\t}\n \t\t\t\t\t} else {\n \t\t\t\t\t\telemUrl = elem[__this.config.restangularFields.route];\n\n \t\t\t\t\t\tif (elem[__this.config.restangularFields.restangularCollection]) {\n \t\t\t\t\t\t\tvar ids = elem[__this.config.restangularFields.ids];\n \t\t\t\t\t\t\tif (ids) {\n \t\t\t\t\t\t\t\telemUrl += \"/\" + ids.join(\",\");\n \t\t\t\t\t\t\t}\n \t\t\t\t\t\t} else {\n \t\t\t\t\t\t\tvar elemId;\n \t\t\t\t\t\t\tif (__this.config.useCannonicalId) {\n \t\t\t\t\t\t\t\telemId = __this.config.getCannonicalIdFromElem(elem);\n \t\t\t\t\t\t\t} else {\n \t\t\t\t\t\t\t\telemId = __this.config.getIdFromElem(elem);\n \t\t\t\t\t\t\t}\n\n \t\t\t\t\t\t\tif (config.isValidId(elemId) && !elem.singleOne) {\n \t\t\t\t\t\t\t\telemUrl += \"/\" + (__this.config.encodeIds ? encodeURIComponent(elemId) : elemId);\n \t\t\t\t\t\t\t}\n \t\t\t\t\t\t}\n \t\t\t\t\t}\n\n \t\t\t\t\treturn acum.replace(/\\/$/, \"\") + \"/\" + elemUrl;\n\n \t\t\t\t}, this.config.baseUrl);\n \t\t\t};\n\n\n\n \t\t\tPath.prototype.fetchUrl = function (current, what) {\n \t\t\t\tvar baseUrl = this.base(current);\n \t\t\t\tif (what) {\n \t\t\t\t\tbaseUrl += \"/\" + what;\n \t\t\t\t}\n \t\t\t\treturn baseUrl;\n \t\t\t};\n\n \t\t\tPath.prototype.fetchRequestedUrl = function (current, what) {\n \t\t\t\tvar url = this.fetchUrl(current, what);\n \t\t\t\tvar params = current[config.restangularFields.reqParams];\n\n \t\t\t\t// From here on and until the end of fetchRequestedUrl,\n \t\t\t\t// the code has been kindly borrowed from angular.js\n \t\t\t\t// The reason for such code bloating is coherence:\n \t\t\t\t// If the user were to use this for cache management, the\n \t\t\t\t// serialization of parameters would need to be identical\n \t\t\t\t// to the one done by angular for cache keys to match.\n \t\t\t\tfunction sortedKeys(obj) {\n \t\t\t\t\tvar keys = [];\n \t\t\t\t\tfor (var key in obj) {\n \t\t\t\t\t\tif (obj.hasOwnProperty(key)) {\n \t\t\t\t\t\t\tkeys.push(key);\n \t\t\t\t\t\t}\n \t\t\t\t\t}\n \t\t\t\t\treturn keys.sort();\n \t\t\t\t}\n\n \t\t\t\tfunction forEachSorted(obj, iterator, context) {\n \t\t\t\t\tvar keys = sortedKeys(obj);\n \t\t\t\t\tfor (var i = 0; i < keys.length; i++) {\n \t\t\t\t\t\titerator.call(context, obj[keys[i]], keys[i]);\n \t\t\t\t\t}\n \t\t\t\t\treturn keys;\n \t\t\t\t}\n\n \t\t\t\tfunction encodeUriQuery(val, pctEncodeSpaces) {\n \t\t\t\t\treturn encodeURIComponent(val).\n\t\t\t\t\t\t\t replace(/%40/gi, '@').\n\t\t\t\t\t\t\t replace(/%3A/gi, ':').\n\t\t\t\t\t\t\t replace(/%24/g, '$').\n\t\t\t\t\t\t\t replace(/%2C/gi, ',').\n\t\t\t\t\t\t\t replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));\n \t\t\t\t}\n\n \t\t\t\tif (!params) return url;\n \t\t\t\tvar parts = [];\n \t\t\t\tforEachSorted(params, function (value, key) {\n \t\t\t\t\tif (value == null || value == undefined) return;\n \t\t\t\t\tif (!angular.isArray(value)) value = [value];\n\n \t\t\t\t\tangular.forEach(value, function (v) {\n \t\t\t\t\t\tif (angular.isObject(v)) {\n \t\t\t\t\t\t\tv = angular.toJson(v);\n \t\t\t\t\t\t}\n \t\t\t\t\t\tparts.push(encodeUriQuery(key) + '=' +\n\t\t\t\t\t\t\t\t encodeUriQuery(v));\n \t\t\t\t\t});\n \t\t\t\t});\n \t\t\t\treturn url + (this.config.suffix || '') + ((url.indexOf('?') === -1) ? '?' : '&') + parts.join('&');\n \t\t\t};\n\n\n\n \t\t\tconfig.urlCreatorFactory.path = Path;\n\n \t\t};\n\n \t\tvar globalConfiguration = {};\n\n \t\tConfigurer.init(this, globalConfiguration);\n\n\n\n\n \t\tthis.$get = ['$http', '$q', function ($http, $q) {\n\n \t\t\tfunction createServiceForConfiguration(config) {\n \t\t\t\tvar service = {};\n\n \t\t\t\tvar urlHandler = new config.urlCreatorFactory[config.urlCreator]();\n \t\t\t\turlHandler.setConfig(config);\n\n \t\t\t\tfunction restangularizeBase(parent, elem, route, reqParams, fromServer) {\n \t\t\t\t\telem[config.restangularFields.route] = route;\n \t\t\t\t\telem[config.restangularFields.getRestangularUrl] = _.bind(urlHandler.fetchUrl, urlHandler, elem);\n \t\t\t\t\telem[config.restangularFields.getRequestedUrl] = _.bind(urlHandler.fetchRequestedUrl, urlHandler, elem);\n \t\t\t\t\telem[config.restangularFields.addRestangularMethod] = _.bind(addRestangularMethodFunction, elem);\n \t\t\t\t\telem[config.restangularFields.clone] = _.bind(copyRestangularizedElement, elem, elem);\n \t\t\t\t\telem[config.restangularFields.reqParams] = _.isEmpty(reqParams) ? null : reqParams;\n \t\t\t\t\telem[config.restangularFields.withHttpConfig] = _.bind(withHttpConfig, elem);\n \t\t\t\t\telem[config.restangularFields.plain] = _.bind(stripRestangular, elem, elem);\n\n \t\t\t\t\t// RequestLess connection\n \t\t\t\t\telem[config.restangularFields.one] = _.bind(one, elem, elem);\n \t\t\t\t\telem[config.restangularFields.all] = _.bind(all, elem, elem);\n \t\t\t\t\telem[config.restangularFields.several] = _.bind(several, elem, elem);\n \t\t\t\t\telem[config.restangularFields.oneUrl] = _.bind(oneUrl, elem, elem);\n \t\t\t\t\telem[config.restangularFields.allUrl] = _.bind(allUrl, elem, elem);\n\n \t\t\t\t\telem[config.restangularFields.fromServer] = !!fromServer;\n\n \t\t\t\t\tif (parent && config.shouldSaveParent(route)) {\n \t\t\t\t\t\tvar parentId = config.getIdFromElem(parent);\n \t\t\t\t\t\tvar parentUrl = config.getUrlFromElem(parent);\n\n \t\t\t\t\t\tvar restangularFieldsForParent = _.union(\n\t\t\t\t\t\t _.values(_.pick(config.restangularFields, ['route', 'singleOne', 'parentResource'])),\n\t\t\t\t\t\t config.extraFields\n\t\t\t\t\t\t);\n \t\t\t\t\t\tvar parentResource = _.pick(parent, restangularFieldsForParent);\n\n \t\t\t\t\t\tif (config.isValidId(parentId)) {\n \t\t\t\t\t\t\tconfig.setIdToElem(parentResource, parentId);\n \t\t\t\t\t\t}\n \t\t\t\t\t\tif (config.isValidId(parentUrl)) {\n \t\t\t\t\t\t\tconfig.setUrlToElem(parentResource, parentUrl);\n \t\t\t\t\t\t}\n\n \t\t\t\t\t\telem[config.restangularFields.parentResource] = parentResource;\n \t\t\t\t\t} else {\n \t\t\t\t\t\telem[config.restangularFields.parentResource] = null;\n \t\t\t\t\t}\n \t\t\t\t\treturn elem;\n \t\t\t\t}\n\n\n\n \t\t\t\tfunction one(parent, route, id, singleOne) {\n \t\t\t\t\tif (_.isNumber(route) || _.isNumber(parent)) {\n \t\t\t\t\t\tvar error = \"You're creating a Restangular entity with the number \"\n \t\t\t\t\t\terror += \"instead of the route or the parent. You can't call .one(12)\";\n \t\t\t\t\t\tthrow new Error(error);\n \t\t\t\t\t}\n \t\t\t\t\tvar elem = {};\n \t\t\t\t\tconfig.setIdToElem(elem, id);\n \t\t\t\t\tconfig.setFieldToElem(config.restangularFields.singleOne, elem, singleOne);\n \t\t\t\t\treturn restangularizeElem(parent, elem, route, false);\n \t\t\t\t}\n\n\n \t\t\t\tfunction all(parent, route) {\n \t\t\t\t\treturn restangularizeCollection(parent, [], route, false);\n \t\t\t\t}\n\n \t\t\t\tfunction several(parent, route, ids) {\n \t\t\t\t\tvar collection = [];\n \t\t\t\t\tcollection[config.restangularFields.ids] =\n\t\t\t\t\t Array.prototype.splice.call(arguments, 2);\n \t\t\t\t\treturn restangularizeCollection(parent, collection, route, false);\n \t\t\t\t}\n\n \t\t\t\tfunction oneUrl(parent, route, url) {\n \t\t\t\t\tif (!route) {\n \t\t\t\t\t\tthrow new Error(\"Route is mandatory when creating new Restangular objects.\");\n \t\t\t\t\t}\n \t\t\t\t\tvar elem = {};\n \t\t\t\t\tconfig.setUrlToElem(elem, url, route);\n \t\t\t\t\treturn restangularizeElem(parent, elem, route, false);\n \t\t\t\t}\n\n\n \t\t\t\tfunction allUrl(parent, route, url) {\n \t\t\t\t\tif (!route) {\n \t\t\t\t\t\tthrow new Error(\"Route is mandatory when creating new Restangular objects.\");\n \t\t\t\t\t}\n \t\t\t\t\tvar elem = {};\n \t\t\t\t\tconfig.setUrlToElem(elem, url, route);\n \t\t\t\t\treturn restangularizeCollection(parent, elem, route, false);\n \t\t\t\t}\n \t\t\t\t// Promises\n \t\t\t\tfunction restangularizePromise(promise, isCollection, valueToFill) {\n \t\t\t\t\tpromise.call = _.bind(promiseCall, promise);\n \t\t\t\t\tpromise.get = _.bind(promiseGet, promise);\n \t\t\t\t\tpromise[config.restangularFields.restangularCollection] = isCollection;\n \t\t\t\t\tif (isCollection) {\n \t\t\t\t\t\tpromise.push = _.bind(promiseCall, promise, \"push\");\n \t\t\t\t\t}\n \t\t\t\t\tpromise.$object = valueToFill;\n \t\t\t\t\treturn promise;\n \t\t\t\t}\n\n \t\t\t\tfunction promiseCall(method) {\n \t\t\t\t\tvar deferred = $q.defer();\n \t\t\t\t\tvar callArgs = arguments;\n \t\t\t\t\tvar filledValue = {};\n \t\t\t\t\tthis.then(function (val) {\n \t\t\t\t\t\tvar params = Array.prototype.slice.call(callArgs, 1);\n \t\t\t\t\t\tvar func = val[method];\n \t\t\t\t\t\tfunc.apply(val, params);\n \t\t\t\t\t\tfilledValue = val;\n \t\t\t\t\t\tdeferred.resolve(val);\n \t\t\t\t\t});\n \t\t\t\t\treturn restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection], filledValue);\n \t\t\t\t}\n\n \t\t\t\tfunction promiseGet(what) {\n \t\t\t\t\tvar deferred = $q.defer();\n \t\t\t\t\tvar filledValue = {};\n \t\t\t\t\tthis.then(function (val) {\n \t\t\t\t\t\tfilledValue = val[what];\n \t\t\t\t\t\tdeferred.resolve(filledValue);\n \t\t\t\t\t});\n \t\t\t\t\treturn restangularizePromise(deferred.promise, this[config.restangularFields.restangularCollection], filledValue);\n \t\t\t\t}\n\n \t\t\t\tfunction resolvePromise(deferred, response, data, filledValue) {\n\n \t\t\t\t\t_.extend(filledValue, data);\n\n \t\t\t\t\t// Trigger the full response interceptor.\n \t\t\t\t\tif (config.fullResponse) {\n \t\t\t\t\t\treturn deferred.resolve(_.extend(response, {\n \t\t\t\t\t\t\tdata: data\n \t\t\t\t\t\t}));\n \t\t\t\t\t} else {\n \t\t\t\t\t\tdeferred.resolve(data);\n \t\t\t\t\t}\n \t\t\t\t}\n\n\n \t\t\t\t// Elements\n\n \t\t\t\tfunction stripRestangular(elem) {\n \t\t\t\t\tif (_.isArray(elem)) {\n \t\t\t\t\t\tvar array = [];\n \t\t\t\t\t\t_.each(elem, function (value) {\n \t\t\t\t\t\t\tarray.push(stripRestangular(value));\n \t\t\t\t\t\t});\n \t\t\t\t\t\treturn array;\n \t\t\t\t\t} else {\n \t\t\t\t\t\treturn _.omit(elem, _.values(_.omit(config.restangularFields, 'id')));\n \t\t\t\t\t}\n\n\n \t\t\t\t}\n\n \t\t\t\tfunction addCustomOperation(elem) {\n \t\t\t\t\telem[config.restangularFields.customOperation] = _.bind(customFunction, elem);\n \t\t\t\t\t_.each([\"put\", \"post\", \"get\", \"delete\"], function (oper) {\n \t\t\t\t\t\t_.each([\"do\", \"custom\"], function (alias) {\n \t\t\t\t\t\t\tvar callOperation = oper === 'delete' ? 'remove' : oper;\n \t\t\t\t\t\t\tvar name = alias + oper.toUpperCase();\n \t\t\t\t\t\t\tvar callFunction;\n\n \t\t\t\t\t\t\tif (callOperation !== 'put' && callOperation !== 'post') {\n \t\t\t\t\t\t\t\tcallFunction = customFunction;\n \t\t\t\t\t\t\t} else {\n \t\t\t\t\t\t\t\tcallFunction = function (operation, elem, path, params, headers) {\n \t\t\t\t\t\t\t\t\treturn _.bind(customFunction, this)(operation, path, params, headers, elem);\n \t\t\t\t\t\t\t\t};\n \t\t\t\t\t\t\t}\n \t\t\t\t\t\t\telem[name] = _.bind(callFunction, elem, callOperation);\n \t\t\t\t\t\t});\n \t\t\t\t\t});\n \t\t\t\t\telem[config.restangularFields.customGETLIST] = _.bind(fetchFunction, elem);\n \t\t\t\t\telem[config.restangularFields.doGETLIST] = elem[config.restangularFields.customGETLIST];\n \t\t\t\t}\n\n \t\t\t\tfunction copyRestangularizedElement(fromElement, toElement) {\n \t\t\t\t\tvar copiedElement = angular.copy(fromElement, toElement);\n \t\t\t\t\treturn restangularizeElem(copiedElement[config.restangularFields.parentResource],\n\t\t\t\t\t\t\tcopiedElement, copiedElement[config.restangularFields.route], true);\n \t\t\t\t}\n\n \t\t\t\tfunction restangularizeElem(parent, element, route, fromServer, collection, reqParams) {\n \t\t\t\t\tvar elem = config.onBeforeElemRestangularized(element, false, route);\n\n \t\t\t\t\tvar localElem = restangularizeBase(parent, elem, route, reqParams, fromServer);\n\n \t\t\t\t\tif (config.useCannonicalId) {\n \t\t\t\t\t\tlocalElem[config.restangularFields.cannonicalId] = config.getIdFromElem(localElem);\n \t\t\t\t\t}\n\n \t\t\t\t\tif (collection) {\n \t\t\t\t\t\tlocalElem[config.restangularFields.getParentList] = function () {\n \t\t\t\t\t\t\treturn collection;\n \t\t\t\t\t\t};\n \t\t\t\t\t}\n\n \t\t\t\t\tlocalElem[config.restangularFields.restangularCollection] = false;\n \t\t\t\t\tlocalElem[config.restangularFields.get] = _.bind(getFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.getList] = _.bind(fetchFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.put] = _.bind(putFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.post] = _.bind(postFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.remove] = _.bind(deleteFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.head] = _.bind(headFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.trace] = _.bind(traceFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.options] = _.bind(optionsFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.patch] = _.bind(patchFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.save] = _.bind(save, localElem);\n\n \t\t\t\t\taddCustomOperation(localElem);\n \t\t\t\t\treturn config.transformElem(localElem, false, route, service, true);\n \t\t\t\t}\n\n \t\t\t\tfunction restangularizeCollection(parent, element, route, fromServer, reqParams) {\n \t\t\t\t\tvar elem = config.onBeforeElemRestangularized(element, true, route);\n\n \t\t\t\t\tvar localElem = restangularizeBase(parent, elem, route, reqParams, fromServer);\n \t\t\t\t\tlocalElem[config.restangularFields.restangularCollection] = true;\n \t\t\t\t\tlocalElem[config.restangularFields.post] = _.bind(postFunction, localElem, null);\n \t\t\t\t\tlocalElem[config.restangularFields.remove] = _.bind(deleteFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.head] = _.bind(headFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.trace] = _.bind(traceFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.putElement] = _.bind(putElementFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.options] = _.bind(optionsFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.patch] = _.bind(patchFunction, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.get] = _.bind(getById, localElem);\n \t\t\t\t\tlocalElem[config.restangularFields.getList] = _.bind(fetchFunction, localElem, null);\n\n \t\t\t\t\taddCustomOperation(localElem);\n \t\t\t\t\treturn config.transformElem(localElem, true, route, service, true);\n \t\t\t\t}\n\n \t\t\t\tfunction restangularizeCollectionAndElements(parent, element, route) {\n \t\t\t\t\tvar collection = restangularizeCollection(parent, element, route, false);\n \t\t\t\t\t_.each(collection, function (elem) {\n \t\t\t\t\t\trestangularizeElem(parent, elem, route, false);\n \t\t\t\t\t});\n \t\t\t\t\treturn collection;\n \t\t\t\t}\n\n \t\t\t\tfunction getById(id, reqParams, headers) {\n \t\t\t\t\treturn this.customGET(id.toString(), reqParams, headers);\n \t\t\t\t}\n\n \t\t\t\tfunction putElementFunction(idx, params, headers) {\n \t\t\t\t\tvar __this = this;\n \t\t\t\t\tvar elemToPut = this[idx];\n \t\t\t\t\tvar deferred = $q.defer();\n \t\t\t\t\tvar filledArray = [];\n \t\t\t\t\tfilledArray = config.transformElem(filledArray, true, elemToPut[config.restangularFields.route], service)\n \t\t\t\t\telemToPut.put(params, headers).then(function (serverElem) {\n \t\t\t\t\t\tvar newArray = copyRestangularizedElement(__this);\n \t\t\t\t\t\tnewArray[idx] = serverElem;\n \t\t\t\t\t\tfilledArray = newArray;\n \t\t\t\t\t\tdeferred.resolve(newArray);\n \t\t\t\t\t}, function (response) {\n \t\t\t\t\t\tdeferred.reject(response);\n \t\t\t\t\t});\n\n \t\t\t\t\treturn restangularizePromise(deferred.promise, true, filledArray);\n \t\t\t\t}\n\n \t\t\t\tfunction parseResponse(resData, operation, route, fetchUrl, response, deferred) {\n \t\t\t\t\tvar data = config.responseExtractor(resData, operation, route, fetchUrl, response, deferred);\n \t\t\t\t\tvar etag = response.headers(\"ETag\");\n \t\t\t\t\tif (data && etag) {\n \t\t\t\t\t\tdata[config.restangularFields.etag] = etag;\n \t\t\t\t\t}\n \t\t\t\t\treturn data;\n \t\t\t\t}\n\n\n \t\t\t\tfunction fetchFunction(what, reqParams, headers) {\n \t\t\t\t\tvar __this = this;\n \t\t\t\t\tvar deferred = $q.defer();\n \t\t\t\t\tvar operation = 'getList';\n \t\t\t\t\tvar url = urlHandler.fetchUrl(this, what);\n \t\t\t\t\tvar whatFetched = what || __this[config.restangularFields.route];\n\n \t\t\t\t\tvar request = config.fullRequestInterceptor(null, operation,\n\t\t\t\t\t\twhatFetched, url, headers || {}, reqParams || {}, this[config.restangularFields.httpConfig] || {});\n\n \t\t\t\t\tvar filledArray = [];\n \t\t\t\t\tfilledArray = config.transformElem(filledArray, true, whatFetched, service)\n\n \t\t\t\t\tvar method = \"getList\";\n\n \t\t\t\t\tif (config.jsonp) {\n \t\t\t\t\t\tmethod = \"jsonp\";\n \t\t\t\t\t}\n\n \t\t\t\t\turlHandler.resource(this, $http, request.httpConfig, request.headers, request.params, what,\n\t\t\t\t\t\t\tthis[config.restangularFields.etag], operation)[method]().then(function (response) {\n\t\t\t\t\t\t\t\tvar resData = response.data;\n\t\t\t\t\t\t\t\tvar fullParams = response.config.params;\n\t\t\t\t\t\t\t\tvar data = parseResponse(resData, operation, whatFetched, url, response, deferred);\n\n\t\t\t\t\t\t\t\t// support empty response for getList() calls (some APIs respond with 204 and empty body)\n\t\t\t\t\t\t\t\tif (_.isUndefined(data) || \"\" === data) {\n\t\t\t\t\t\t\t\t\tdata = []\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tif (!_.isArray(data)) {\n\t\t\t\t\t\t\t\t\tthrow new Error(\"Response for getList SHOULD be an array and not an object or something else\");\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tvar processedData = _.map(data, function (elem) {\n\t\t\t\t\t\t\t\t\tif (!__this[config.restangularFields.restangularCollection]) {\n\t\t\t\t\t\t\t\t\t\treturn restangularizeElem(__this, elem, what, true, data);\n\t\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\t\treturn restangularizeElem(__this[config.restangularFields.parentResource],\n\t\t\t\t\t\t\t\t\t\t elem, __this[config.restangularFields.route], true, data);\n\t\t\t\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\t\t});\n\n\t\t\t\t\t\t\t\tprocessedData = _.extend(data, processedData);\n\n\t\t\t\t\t\t\t\tif (!__this[config.restangularFields.restangularCollection]) {\n\t\t\t\t\t\t\t\t\tresolvePromise(deferred, response, restangularizeCollection(__this, processedData, what, true, fullParams), filledArray);\n\t\t\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\t\t\tresolvePromise(deferred, response, restangularizeCollection(__this[config.restangularFields.parentResource], processedData, __this[config.restangularFields.route], true, fullParams), filledArray);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}, function error(response) {\n\t\t\t\t\t\t\t\tif (response.status === 304 && __this[config.restangularFields.restangularCollection]) {\n\t\t\t\t\t\t\t\t\tresolvePromise(deferred, response, __this, filledArray);\n\t\t\t\t\t\t\t\t} else if (config.errorInterceptor(response, deferred) !== false) {\n\t\t\t\t\t\t\t\t\tdeferred.reject(response);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t});\n\n \t\t\t\t\treturn restangularizePromise(deferred.promise, true, filledArray);\n \t\t\t\t}\n\n \t\t\t\tfunction withHttpConfig(httpConfig) {\n \t\t\t\t\tthis[config.restangularFields.httpConfig] = httpConfig;\n \t\t\t\t\treturn this;\n \t\t\t\t}\n\n \t\t\t\tfunction save(params, headers) {\n \t\t\t\t\tif (this[config.restangularFields.fromServer]) {\n \t\t\t\t\t\treturn this[config.restangularFields.put](params, headers);\n \t\t\t\t\t} else {\n \t\t\t\t\t\treturn _.bind(elemFunction, this)(\"post\", undefined, params, undefined, headers);\n \t\t\t\t\t}\n \t\t\t\t}\n\n \t\t\t\tfunction elemFunction(operation, what, params, obj, headers) {\n \t\t\t\t\tvar __this = this;\n \t\t\t\t\tvar deferred = $q.defer();\n \t\t\t\t\tvar resParams = params || {};\n \t\t\t\t\tvar route = what || this[config.restangularFields.route];\n \t\t\t\t\tvar fetchUrl = urlHandler.fetchUrl(this, what);\n\n \t\t\t\t\tvar callObj = obj || this;\n \t\t\t\t\t// fallback to etag on restangular object (since for custom methods we probably don't explicitly specify the etag field)\n \t\t\t\t\tvar etag = callObj[config.restangularFields.etag] || (operation != \"post\" ? this[config.restangularFields.etag] : null);\n\n \t\t\t\t\tif (_.isObject(callObj) && config.isRestangularized(callObj)) {\n \t\t\t\t\t\tcallObj = stripRestangular(callObj);\n \t\t\t\t\t}\n \t\t\t\t\tvar request = config.fullRequestInterceptor(callObj, operation, route, fetchUrl,\n\t\t\t\t\t headers || {}, resParams || {}, this[config.restangularFields.httpConfig] || {});\n\n \t\t\t\t\tvar filledObject = {};\n \t\t\t\t\tfilledObject = config.transformElem(filledObject, false, route, service);\n\n \t\t\t\t\tvar okCallback = function (response) {\n \t\t\t\t\t\tvar resData = response.data;\n \t\t\t\t\t\tvar fullParams = response.config.params;\n \t\t\t\t\t\tvar elem = parseResponse(resData, operation, route, fetchUrl, response, deferred);\n \t\t\t\t\t\tif (elem) {\n\n \t\t\t\t\t\t\tif (operation === \"post\" && !__this[config.restangularFields.restangularCollection]) {\n \t\t\t\t\t\t\t\tresolvePromise(deferred, response, restangularizeElem(__this, elem, what, true, null, fullParams), filledObject);\n \t\t\t\t\t\t\t} else {\n \t\t\t\t\t\t\t\tdata = restangularizeElem(__this[config.restangularFields.parentResource], elem, __this[config.restangularFields.route], true, null, fullParams)\n \t\t\t\t\t\t\t\tdata[config.restangularFields.singleOne] = __this[config.restangularFields.singleOne]\n \t\t\t\t\t\t\t\tresolvePromise(deferred, response, data, filledObject);\n \t\t\t\t\t\t\t}\n\n \t\t\t\t\t\t} else {\n \t\t\t\t\t\t\tresolvePromise(deferred, response, undefined, filledObject);\n \t\t\t\t\t\t}\n \t\t\t\t\t};\n\n \t\t\t\t\tvar errorCallback = function (response) {\n \t\t\t\t\t\tif (response.status === 304 && config.isSafe(operation)) {\n \t\t\t\t\t\t\tresolvePromise(deferred, response, __this, filledObject);\n \t\t\t\t\t\t} else if (config.errorInterceptor(response, deferred) !== false) {\n \t\t\t\t\t\t\tdeferred.reject(response);\n \t\t\t\t\t\t}\n \t\t\t\t\t};\n \t\t\t\t\t// Overring HTTP Method\n \t\t\t\t\tvar callOperation = operation;\n \t\t\t\t\tvar callHeaders = _.extend({}, request.headers);\n \t\t\t\t\tvar isOverrideOperation = config.isOverridenMethod(operation);\n \t\t\t\t\tif (isOverrideOperation) {\n \t\t\t\t\t\tcallOperation = 'post';\n \t\t\t\t\t\tcallHeaders = _.extend(callHeaders, { 'X-HTTP-Method-Override': operation === 'remove' ? 'DELETE' : operation });\n \t\t\t\t\t} else if (config.jsonp && callOperation === 'get') {\n \t\t\t\t\t\tcallOperation = 'jsonp';\n \t\t\t\t\t}\n\n \t\t\t\t\tif (config.isSafe(operation)) {\n \t\t\t\t\t\tif (isOverrideOperation) {\n \t\t\t\t\t\t\turlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params,\n\t\t\t\t\t\t\t what, etag, callOperation)[callOperation]({}).then(okCallback, errorCallback);\n \t\t\t\t\t\t} else {\n \t\t\t\t\t\t\turlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params,\n\t\t\t\t\t\t\t what, etag, callOperation)[callOperation]().then(okCallback, errorCallback);\n \t\t\t\t\t\t}\n \t\t\t\t\t} else {\n \t\t\t\t\t\turlHandler.resource(this, $http, request.httpConfig, callHeaders, request.params,\n\t\t\t\t\t\t what, etag, callOperation)[callOperation](request.element).then(okCallback, errorCallback);\n \t\t\t\t\t}\n\n \t\t\t\t\treturn restangularizePromise(deferred.promise, false, filledObject);\n \t\t\t\t}\n\n \t\t\t\tfunction getFunction(params, headers) {\n \t\t\t\t\treturn _.bind(elemFunction, this)(\"get\", undefined, params, undefined, headers);\n \t\t\t\t}\n\n \t\t\t\tfunction deleteFunction(params, headers) {\n \t\t\t\t\treturn _.bind(elemFunction, this)(\"remove\", undefined, params, undefined, headers);\n \t\t\t\t}\n\n \t\t\t\tfunction putFunction(params, headers) {\n \t\t\t\t\treturn _.bind(elemFunction, this)(\"put\", undefined, params, undefined, headers);\n \t\t\t\t}\n\n \t\t\t\tfunction postFunction(what, elem, params, headers) {\n \t\t\t\t\treturn _.bind(elemFunction, this)(\"post\", what, params, elem, headers);\n \t\t\t\t}\n\n \t\t\t\tfunction headFunction(params, headers) {\n \t\t\t\t\treturn _.bind(elemFunction, this)(\"head\", undefined, params, undefined, headers);\n \t\t\t\t}\n\n \t\t\t\tfunction traceFunction(params, headers) {\n \t\t\t\t\treturn _.bind(elemFunction, this)(\"trace\", undefined, params, undefined, headers);\n \t\t\t\t}\n\n \t\t\t\tfunction optionsFunction(params, headers) {\n \t\t\t\t\treturn _.bind(elemFunction, this)(\"options\", undefined, params, undefined, headers);\n \t\t\t\t}\n\n \t\t\t\tfunction patchFunction(elem, params, headers) {\n \t\t\t\t\treturn _.bind(elemFunction, this)(\"patch\", undefined, params, elem, headers);\n \t\t\t\t}\n\n \t\t\t\tfunction customFunction(operation, path, params, headers, elem) {\n \t\t\t\t\treturn _.bind(elemFunction, this)(operation, path, params, elem, headers);\n \t\t\t\t}\n\n \t\t\t\tfunction addRestangularMethodFunction(name, operation, path, defaultParams, defaultHeaders, defaultElem) {\n \t\t\t\t\tvar bindedFunction;\n \t\t\t\t\tif (operation === 'getList') {\n \t\t\t\t\t\tbindedFunction = _.bind(fetchFunction, this, path);\n \t\t\t\t\t} else {\n \t\t\t\t\t\tbindedFunction = _.bind(customFunction, this, operation, path);\n \t\t\t\t\t}\n\n \t\t\t\t\tvar createdFunction = function (params, headers, elem) {\n \t\t\t\t\t\tvar callParams = _.defaults({\n \t\t\t\t\t\t\tparams: params,\n \t\t\t\t\t\t\theaders: headers,\n \t\t\t\t\t\t\telem: elem\n \t\t\t\t\t\t}, {\n \t\t\t\t\t\t\tparams: defaultParams,\n \t\t\t\t\t\t\theaders: defaultHeaders,\n \t\t\t\t\t\t\telem: defaultElem\n \t\t\t\t\t\t});\n \t\t\t\t\t\treturn bindedFunction(callParams.params, callParams.headers, callParams.elem);\n \t\t\t\t\t};\n\n \t\t\t\t\tif (config.isSafe(operation)) {\n \t\t\t\t\t\tthis[name] = createdFunction;\n \t\t\t\t\t} else {\n \t\t\t\t\t\tthis[name] = function (elem, params, headers) {\n \t\t\t\t\t\t\treturn createdFunction(params, headers, elem);\n \t\t\t\t\t\t};\n \t\t\t\t\t}\n\n \t\t\t\t}\n\n \t\t\t\tfunction withConfigurationFunction(configurer) {\n \t\t\t\t\tvar newConfig = angular.copy(_.omit(config, 'configuration'));\n \t\t\t\t\tConfigurer.init(newConfig, newConfig);\n \t\t\t\t\tconfigurer(newConfig);\n \t\t\t\t\treturn createServiceForConfiguration(newConfig);\n \t\t\t\t}\n\n \t\t\t\tfunction toService(route, parent) {\n \t\t\t\t\tvar serv = {};\n \t\t\t\t\tvar collection = (parent || service).all(route);\n \t\t\t\t\tserv.one = _.bind(one, (parent || service), parent, route);\n \t\t\t\t\tserv.post = _.bind(collection.post, collection);\n \t\t\t\t\tserv.getList = _.bind(collection.getList, collection);\n \t\t\t\t\treturn serv;\n \t\t\t\t}\n\n\n \t\t\t\tConfigurer.init(service, config);\n\n \t\t\t\tservice.copy = _.bind(copyRestangularizedElement, service);\n\n \t\t\t\tservice.service = _.bind(toService, service);\n\n \t\t\t\tservice.withConfig = _.bind(withConfigurationFunction, service);\n\n \t\t\t\tservice.one = _.bind(one, service, null);\n\n \t\t\t\tservice.all = _.bind(all, service, null);\n\n \t\t\t\tservice.several = _.bind(several, service, null);\n\n \t\t\t\tservice.oneUrl = _.bind(oneUrl, service, null);\n\n \t\t\t\tservice.allUrl = _.bind(allUrl, service, null);\n\n \t\t\t\tservice.stripRestangular = _.bind(stripRestangular, service);\n\n \t\t\t\tservice.restangularizeElement = _.bind(restangularizeElem, service);\n\n \t\t\t\tservice.restangularizeCollection = _.bind(restangularizeCollectionAndElements, service);\n\n \t\t\t\treturn service;\n \t\t\t}\n\n \t\t\treturn createServiceForConfiguration(globalConfiguration);\n\n \t\t}];\n \t}\n\t);\n\n })();","'use strict';\n\nangular.module('minicolors', []);\n\nangular.module('minicolors').provider('minicolors', function () {\n this.defaults = {\n theme: 'bootstrap',\n position: 'top left',\n defaultValue: '',\n animationSpeed: 50,\n animationEasing: 'swing',\n change: null,\n changeDelay: 0,\n control: 'hue',\n hide: null,\n hideSpeed: 100,\n inline: false,\n letterCase: 'lowercase',\n opacity: false,\n show: null,\n showSpeed: 100\n };\n\n this.$get = function () {\n return this;\n };\n\n});\n\nangular.module('minicolors').directive('minicolors', ['minicolors', '$timeout', function (minicolors, $timeout) {\n return {\n require: '?ngModel',\n restrict: 'A',\n priority: 1, //since we bind on an input element, we have to set a higher priority than angular-default input\n link: function (scope, element, attrs, ngModel) {\n\n var inititalized = false;\n\n //gets the settings object\n var getSettings = function () {\n var config = angular.extend({}, minicolors.defaults, scope.$eval(attrs.minicolors));\n return config;\n };\n\n //what to do if the value changed\n ngModel.$render = function () {\n\n //we are in digest or apply, and therefore call a timeout function\n $timeout(function () {\n var color = ngModel.$viewValue;\n element.minicolors('value', color);\n }, 0, false);\n };\n\n //init method\n var initMinicolors = function () {\n\n if (!ngModel) {\n return;\n }\n var settings = getSettings();\n settings.change = function (hex) {\n scope.$apply(function () {\n ngModel.$setViewValue(hex);\n });\n };\n\n // If we don't destroy the old one it doesn't update properly when the config changes\n element.minicolors('destroy');\n\n // Create the new minicolors widget\n element.minicolors(settings);\n\n // are we inititalized yet ?\n //needs to be wrapped in $timeout, to prevent $apply / $digest errors\n //$scope.$apply will be called by $timeout, so we don't have to handle that case\n if (!inititalized) {\n $timeout(function () {\n var color = ngModel.$viewValue;\n element.minicolors('value', color);\n }, 0);\n inititalized = true;\n return;\n }\n };\n\n initMinicolors();\n //initital call\n\n // Watch for changes to the directives options and then call init method again\n scope.$watch(getSettings, initMinicolors, true);\n }\n };\n}]);","/*globals angular, moment, jQuery */\n/*jslint vars:true */\n\n/**\n * @license angular-bootstrap-datetimepicker v0.3.0\n * (c) 2013 Knight Rider Consulting, Inc. http://www.knightrider.com\n * License: MIT\n */\n\n/**\n *\n * @author Dale \"Ducky\" Lotts\n * @since 2013-Jul-8\n */\n\nangular.module('ui.bootstrap.datetimepicker', [])\n .constant('dateTimePickerConfig', {\n dropdownSelector: null,\n minuteStep: 5,\n minView: 'minute',\n startView: 'day'\n })\n .directive('datetimepicker', ['dateTimePickerConfig', function (defaultConfig) {\n \"use strict\";\n\n var validateConfiguration = function (configuration) {\n var validOptions = ['startView', 'minView', 'minuteStep', 'dropdownSelector'];\n\n for (var prop in configuration) {\n if (configuration.hasOwnProperty(prop)) {\n if (validOptions.indexOf(prop) < 0) {\n throw (\"invalid option: \" + prop);\n }\n }\n }\n\n // Order of the elements in the validViews array is significant.\n var validViews = ['minute', 'hour', 'day', 'month', 'year'];\n\n if (validViews.indexOf(configuration.startView) < 0) {\n throw (\"invalid startView value: \" + configuration.startView);\n }\n\n if (validViews.indexOf(configuration.minView) < 0) {\n throw (\"invalid minView value: \" + configuration.minView);\n }\n\n if (validViews.indexOf(configuration.minView) > validViews.indexOf(configuration.startView)) {\n throw (\"startView must be greater than minView\");\n }\n\n if (!angular.isNumber(configuration.minuteStep)) {\n throw (\"minuteStep must be numeric\");\n }\n if (configuration.minuteStep <= 0 || configuration.minuteStep >= 60) {\n throw (\"minuteStep must be greater than zero and less than 60\");\n }\n if (configuration.dropdownSelector !== null && !angular.isString(configuration.dropdownSelector)) {\n throw (\"dropdownSelector must be a string\");\n }\n };\n\n return {\n restrict: 'E',\n require: 'ngModel',\n template: \"
      \" +\n \"\" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \" \" +\n \"
      {{ data.title }}
      {{ day }}
      \" +\n \" {{ dateValue.display }} \" +\n \"
      {{ dateValue.display }}
      \",\n scope: {\n ngModel: \"=\",\n onSetTime: \"&\"\n },\n replace: true,\n link: function (scope, element, attrs) {\n\n var directiveConfig = {};\n\n if (attrs.datetimepickerConfig) {\n directiveConfig = scope.$eval(attrs.datetimepickerConfig);\n }\n\n var configuration = {};\n\n angular.extend(configuration, defaultConfig, directiveConfig);\n\n validateConfiguration(configuration);\n\n var dataFactory = {\n year: function (unixDate) {\n var selectedDate = moment.utc(unixDate).startOf('year');\n // View starts one year before the decade starts and ends one year after the decade ends\n // i.e. passing in a date of 1/1/2013 will give a range of 2009 to 2020\n // Truncate the last digit from the current year and subtract 1 to get the start of the decade\n var startDecade = (parseInt(selectedDate.year() / 10, 10) * 10);\n var startDate = moment.utc(selectedDate).year(startDecade - 1).startOf('year');\n var activeYear = scope.ngModel ? moment(scope.ngModel).year() : 0;\n\n var result = {\n 'currentView': 'year',\n 'nextView': configuration.minView === 'year' ? 'setTime' : 'month',\n 'title': startDecade + '-' + (startDecade + 9),\n 'leftDate': moment.utc(startDate).subtract(9, 'year').valueOf(),\n 'rightDate': moment.utc(startDate).add(11, 'year').valueOf(),\n 'dates': []\n };\n\n for (var i = 0; i < 12; i++) {\n var yearMoment = moment.utc(startDate).add(i, 'years');\n var dateValue = {\n 'date': yearMoment.valueOf(),\n 'display': yearMoment.format('YYYY'),\n 'past': yearMoment.year() < startDecade,\n 'future': yearMoment.year() > startDecade + 9,\n 'active': yearMoment.year() === activeYear\n };\n\n result.dates.push(dateValue);\n }\n\n return result;\n },\n\n month: function (unixDate) {\n\n var startDate = moment.utc(unixDate).startOf('year');\n\n var activeDate = scope.ngModel ? moment(scope.ngModel).format('YYYY-MMM') : 0;\n\n var result = {\n 'previousView': 'year',\n 'currentView': 'month',\n 'nextView': configuration.minView === 'month' ? 'setTime' : 'day',\n 'currentDate': startDate.valueOf(),\n 'title': startDate.format('YYYY'),\n 'leftDate': moment.utc(startDate).subtract(1, 'year').valueOf(),\n 'rightDate': moment.utc(startDate).add(1, 'year').valueOf(),\n 'dates': []\n };\n\n for (var i = 0; i < 12; i++) {\n var monthMoment = moment.utc(startDate).add(i, 'months');\n var dateValue = {\n 'date': monthMoment.valueOf(),\n 'display': monthMoment.format('MMM'),\n 'active': monthMoment.format('YYYY-MMM') === activeDate\n };\n\n result.dates.push(dateValue);\n }\n\n return result;\n },\n\n day: function (unixDate) {\n\n var selectedDate = moment.utc(unixDate);\n var startOfMonth = moment.utc(selectedDate).startOf('month');\n var endOfMonth = moment.utc(selectedDate).endOf('month');\n\n var startDate = moment.utc(startOfMonth).subtract(Math.abs(startOfMonth.weekday()), 'days');\n\n var activeDate = scope.ngModel ? moment(scope.ngModel).format('YYYY-MMM-DD') : '';\n\n var result = {\n 'previousView': 'month',\n 'currentView': 'day',\n 'nextView': configuration.minView === 'day' ? 'setTime' : 'hour',\n 'currentDate': selectedDate.valueOf(),\n 'title': selectedDate.format('YYYY-MMM'),\n 'leftDate': moment.utc(startOfMonth).subtract(1, 'months').valueOf(),\n 'rightDate': moment.utc(startOfMonth).add(1, 'months').valueOf(),\n 'dayNames': [],\n 'weeks': []\n };\n\n\n for (var dayNumber = 0; dayNumber < 7; dayNumber++) {\n result.dayNames.push(moment.utc().weekday(dayNumber).format('dd'));\n }\n\n for (var i = 0; i < 6; i++) {\n var week = { dates: [] };\n for (var j = 0; j < 7; j++) {\n var monthMoment = moment.utc(startDate).add((i * 7) + j, 'days');\n var dateValue = {\n 'date': monthMoment.valueOf(),\n 'display': monthMoment.format('D'),\n 'active': monthMoment.format('YYYY-MMM-DD') === activeDate,\n 'past': monthMoment.isBefore(startOfMonth),\n 'future': monthMoment.isAfter(endOfMonth)\n };\n week.dates.push(dateValue);\n }\n result.weeks.push(week);\n }\n\n return result;\n },\n\n hour: function (unixDate) {\n var selectedDate = moment.utc(unixDate).hour(0).minute(0).second(0);\n\n var activeFormat = scope.ngModel ? moment(scope.ngModel).format('YYYY-MM-DD H') : '';\n\n var result = {\n 'previousView': 'day',\n 'currentView': 'hour',\n 'nextView': configuration.minView === 'hour' ? 'setTime' : 'minute',\n 'currentDate': selectedDate.valueOf(),\n 'title': selectedDate.format('ll'),\n 'leftDate': moment.utc(selectedDate).subtract(1, 'days').valueOf(),\n 'rightDate': moment.utc(selectedDate).add(1, 'days').valueOf(),\n 'dates': []\n };\n\n for (var i = 0; i < 24; i++) {\n var hourMoment = moment.utc(selectedDate).add(i, 'hours');\n var dateValue = {\n 'date': hourMoment.valueOf(),\n 'display': hourMoment.format('LT'),\n 'active': hourMoment.format('YYYY-MM-DD H') === activeFormat\n };\n\n result.dates.push(dateValue);\n }\n\n return result;\n },\n\n minute: function (unixDate) {\n var selectedDate = moment.utc(unixDate).minute(0).second(0);\n\n var activeFormat = scope.ngModel ? moment(scope.ngModel).format('YYYY-MM-DD H:mm') : '';\n\n var result = {\n 'previousView': 'hour',\n 'currentView': 'minute',\n 'nextView': 'setTime',\n 'currentDate': selectedDate.valueOf(),\n 'title': selectedDate.format('lll'),\n 'leftDate': moment.utc(selectedDate).subtract(1, 'hours').valueOf(),\n 'rightDate': moment.utc(selectedDate).add(1, 'hours').valueOf(),\n 'dates': []\n };\n\n var limit = 60 / configuration.minuteStep;\n\n for (var i = 0; i < limit; i++) {\n var hourMoment = moment.utc(selectedDate).add(i * configuration.minuteStep, 'minute');\n var dateValue = {\n 'date': hourMoment.valueOf(),\n 'display': hourMoment.format('LT'),\n 'active': hourMoment.format('YYYY-MM-DD H:mm') === activeFormat\n };\n\n result.dates.push(dateValue);\n }\n\n return result;\n },\n\n setTime: function (unixDate) {\n var tempDate = new Date(unixDate);\n var newDate = new Date(tempDate.getTime() + (tempDate.getTimezoneOffset() * 60000));\n\n scope.ngModel = newDate;\n\n if (configuration.dropdownSelector) {\n jQuery(configuration.dropdownSelector).dropdown('toggle');\n }\n\n scope.onSetTime({ newDate: newDate, oldDate: scope.ngModel });\n\n return dataFactory[configuration.startView](unixDate);\n }\n };\n\n var getUTCTime = function () {\n var tempDate = (scope.ngModel ? moment(scope.ngModel).toDate() : new Date());\n return tempDate.getTime() - (tempDate.getTimezoneOffset() * 60000);\n };\n\n scope.changeView = function (viewName, unixDate, event) {\n if (event) {\n event.stopPropagation();\n event.preventDefault();\n }\n\n if (viewName && (unixDate > -Infinity) && dataFactory[viewName]) {\n scope.data = dataFactory[viewName](unixDate);\n }\n };\n\n scope.changeView(configuration.startView, getUTCTime());\n\n scope.$watch('ngModel', function () {\n scope.changeView(scope.data.currentView, getUTCTime());\n });\n }\n };\n }]);","'use strict';\n\n/**\n * A directive for adding google places autocomplete to a text box\n * google places autocomplete info: https://developers.google.com/maps/documentation/javascript/places\n *\n * Usage:\n *\n * \n *\n * + ng-model - autocomplete textbox value\n *\n * + details - more detailed autocomplete result, includes address parts, latlng, etc. (Optional)\n *\n * + options - configuration for the autocomplete (Optional)\n *\n * + types: type, String, values can be 'geocode', 'establishment', '(regions)', or '(cities)'\n * + bounds: bounds, Google maps LatLngBounds Object, biases results to bounds, but may return results outside these bounds\n * + country: country String, ISO 3166-1 Alpha-2 compatible country code. examples; 'ca', 'us', 'gb'\n * + watchEnter: Boolean, true; on Enter select top autocomplete result. false(default); enter ends autocomplete\n *\n * example:\n *\n * options = {\n * types: '(cities)',\n * country: 'ca'\n * }\n**/\n\nangular.module(\"ngAutocomplete\", [])\n .directive('ngAutocomplete', function () {\n return {\n require: 'ngModel',\n scope: {\n ngModel: '=',\n options: '=?',\n details: '=?'\n },\n\n link: function (scope, element, attrs, controller) {\n\n //options for autocomplete\n var opts;\n var watchEnter = false;\n //convert options provided to opts\n var initOpts = function () {\n\n opts = {}\n if (scope.options) {\n\n if (scope.options.watchEnter !== true) {\n watchEnter = false;\n } else {\n watchEnter = true;\n }\n\n if (scope.options.types) {\n opts.types = []\n opts.types.push(scope.options.types);\n scope.gPlace.setTypes(opts.types);\n } else {\n scope.gPlace.setTypes([]);\n }\n\n if (scope.options.bounds) {\n opts.bounds = scope.options.bounds;\n scope.gPlace.setBounds(opts.bounds);\n } else {\n scope.gPlace.setBounds(null);\n }\n\n if (scope.options.country) {\n opts.componentRestrictions = {\n country: scope.options.country\n }\n scope.gPlace.setComponentRestrictions(opts.componentRestrictions);\n } else {\n scope.gPlace.setComponentRestrictions(null);\n }\n }\n }\n\n if (scope.gPlace == undefined) {\n scope.gPlace = new google.maps.places.Autocomplete(element[0], {});\n }\n google.maps.event.addListener(scope.gPlace, 'place_changed', function () {\n var result = scope.gPlace.getPlace();\n if (result !== undefined) {\n if (result.address_components !== undefined) {\n\n scope.$apply(function () {\n\n scope.details = result;\n\n controller.$setViewValue(element.val());\n });\n }\n else {\n if (watchEnter) {\n getPlace(result);\n }\n }\n }\n })\n\n //function to get retrieve the autocompletes first result using the AutocompleteService \n var getPlace = function (result) {\n var autocompleteService = new google.maps.places.AutocompleteService();\n if (result.name.length > 0) {\n autocompleteService.getPlacePredictions(\n {\n input: result.name,\n offset: result.name.length\n },\n function listentoresult(list, status) {\n if (list == null || list.length == 0) {\n\n scope.$apply(function () {\n scope.details = null;\n });\n\n } else {\n var placesService = new google.maps.places.PlacesService(element[0]);\n placesService.getDetails(\n { 'reference': list[0].reference },\n function detailsresult(detailsResult, placesServiceStatus) {\n\n if (placesServiceStatus == google.maps.GeocoderStatus.OK) {\n scope.$apply(function () {\n\n controller.$setViewValue(detailsResult.formatted_address);\n element.val(detailsResult.formatted_address);\n\n scope.details = detailsResult;\n\n //on focusout the value reverts, need to set it again.\n var watchFocusOut = element.on('focusout', function(event) {\n element.val(detailsResult.formatted_address);\n element.unbind('focusout');\n });\n\n });\n }\n }\n );\n }\n });\n }\n }\n\n controller.$render = function () {\n var location = controller.$viewValue;\n element.val(location);\n };\n\n //watch options provided to directive\n scope.watchOptions = function () {\n return scope.options;\n };\n scope.$watch(scope.watchOptions, function () {\n initOpts();\n }, true);\n\n }\n };\n });","/**\n * @license ng-bs-daterangepicker v0.0.1\n * (c) 2013 Luis Farzati http://github.com/luisfarzati/ng-bs-daterangepicker\n * License: MIT\n */\n(function (angular) {\n'use strict';\n\nangular.module('ngBootstrap', []).directive('input', ['$compile', '$parse', function ($compile, $parse) {\n\treturn {\n\t\trestrict: 'E',\n\t\trequire: '?ngModel',\n\t\tlink: function ($scope, $element, $attributes, ngModel) {\n\t\t\tif ($attributes.type !== 'daterange' || ngModel === null ) return;\n\n\t\t\tvar options = {};\n\t\t\toptions.format = $attributes.format || 'YYYY-MM-DD';\n\t\t\toptions.separator = $attributes.separator || ' - ';\n\n\t\t //Remove escape quotes\n\t\t var regex = new RegExp('\\\"','g');\n\t\t if ($attributes.minDate && typeof $attributes.minDate == 'string')\n\t\t $attributes.minDate = $attributes.minDate.replace(regex, '');\n\t\t if ($attributes.maxDate && typeof $attributes.minDate == 'string')\n\t\t $attributes.maxDate = $attributes.maxDate.replace(regex, '');\n\n\t\t\toptions.minDate = $attributes.minDate && moment($attributes.minDate);\n\t\t\toptions.maxDate = $attributes.maxDate && moment($attributes.maxDate);\n\t\t\toptions.dateLimit = $attributes.limit && moment.duration.apply(this, $attributes.limit.split(' ').map(function (elem, index) { return index === 0 && parseInt(elem, 10) || elem; }) );\n\t\t\toptions.ranges = $attributes.ranges && $parse($attributes.ranges)($scope);\n\t\t\toptions.locale = $attributes.locale && $parse($attributes.locale)($scope);\n\t\t\toptions.opens = $attributes.opens && $parse($attributes.opens)($scope);\n\n\t\t\toptions.singleDatePicker = $attributes.singleDatePicker && $parse($attributes.singleDatePicker)($scope);\n\t\t\toptions.timePicker = $attributes.timePicker && $parse($attributes.timePicker)($scope);\n\t\t\toptions.timePickerIncrement = $attributes.timePickerIncrement && $parse($attributes.timePickerIncrement)($scope);\n\t\t\toptions.timePicker12Hour = $attributes.timePicker12Hour && $parse($attributes.timePicker12Hour)($scope);\n\n\t\t\tfunction format(date) {\n\t\t\t\treturn date.format(options.format);\n\t\t\t}\n\n\t\t\tfunction formatted(dates) {\n\t\t\t\treturn [format(dates.startDate), format(dates.endDate)].join(options.separator);\n\t\t\t}\n\n\t\t\tngModel.$formatters.unshift(function (modelValue) {\n\t\t\t\tif (!modelValue) return '';\n\t\t\t\treturn modelValue;\n\t\t\t});\n\n\t\t\tngModel.$parsers.unshift(function (viewValue) {\n\t\t\t\treturn viewValue;\n\t\t\t});\n\n\t\t\tngModel.$render = function () {\n\t\t\t\tif (!ngModel.$viewValue || !ngModel.$viewValue.startDate) return;\n\t\t\t\t$element.val(formatted(ngModel.$viewValue));\n\t\t\t};\n\n\t\t\t$scope.$watch($attributes.ngModel, function (modelValue) {\n\t\t\t\tif (!modelValue || (!modelValue.startDate)) {\n\t\t\t\t\t//ngModel.$setViewValue({ startDate: moment().startOf('day'), endDate: moment().startOf('day') });\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\t$element.data('daterangepicker').startDate = modelValue.startDate;\n\t\t\t\t$element.data('daterangepicker').endDate = modelValue.endDate;\n\t\t\t\t$element.data('daterangepicker').updateView();\n\t\t\t\t$element.data('daterangepicker').updateCalendars();\n\t\t\t\t$element.data('daterangepicker').updateInputText();\n\t\t\t});\n\n\t\t\tvar proto=$(document.createElement('div')).daterangepicker().data('daterangepicker').constructor.prototype;\n\t\t\tif (!proto.baseClickDate)\n\t\t\t proto.baseClickDate = proto.clickDate;\n\n\t\t\tproto.clickDate = function (e) {\n\t\t\t var endDate = this.endDate;\n\t\t\t var cal = $(e.target).parents('.calendar');\n\t\t\t this.baseClickDate(e);\n\t\t\t if (cal.hasClass('left')) {\n\t\t\t this.startDate = this.startDate.hour(9);\n\t\t\t this.startDate = this.startDate.minute(0);\n\t\t\t }\n\t\t\t if (!cal.hasClass('left') || (cal.hasClass('left') && !this.endDate.isSame(endDate))) {\n\t\t\t this.endDate = this.endDate.hour(18);\n\t\t\t this.endDate = this.endDate.minute(0);\n\t\t\t }\n\t\t\t this.updateCalendars();\n\t\t\t};\n\n\t\t proto.updateInputText = function () {\n\t\t if (this.element.is('input') && !this.singleDatePicker) {\n\t\t var start = this.startDate.format(this.format);\n\t\t var end = this.endDate.format(this.format);\n\t\t end = (start != end) ? this.separator + end : \"\";\n\t\t this.element.val(start + end);\n\t\t } else if (this.element.is('input')) {\n\t\t this.element.val(this.endDate.format(this.format));\n\t\t }\n\t\t };\n\n\t\t\t$element.daterangepicker(options, function(start, end) {\n\t\t\t\t$scope.$apply(function () {\n\t\t\t\t\tngModel.$setViewValue({ startDate: start, endDate: end });\n\t\t\t\t\tngModel.$render();\n\t\t\t\t});\n\t\t\t});\n\n\t\t}\n\t};\n}]);\n\n})(angular);","/**\n * @license nya-bootstrap-select v1.2.6\n * Copyright 2014 nyasoft\n * Licensed under MIT license\n */\n\nangular.module('nya.bootstrap.select', [])\n .directive('nyaSelectpicker', ['$parse', function ($parse) {\n 'use strict';\n\n // NG_OPTIONS_REGEXP copy from angular.js select directive\n var NG_OPTIONS_REGEXP = /^\\s*([\\s\\S]+?)(?:\\s+as\\s+([\\s\\S]+?))?(?:\\s+group\\s+by\\s+([\\s\\S]+?))?\\s+for\\s+(?:([\\$\\w][\\$\\w]*)|(?:\\(\\s*([\\$\\w][\\$\\w]*)\\s*,\\s*([\\$\\w][\\$\\w]*)\\s*\\)))\\s+in\\s+([\\s\\S]+?)(?:\\s+track\\s+by\\s+([\\s\\S]+?))?$/;\n return {\n restrict: 'CA',\n scope: false,\n require: ['^ngModel', 'select'],\n\n link: function (scope, element, attrs, ctrls) {\n var optionsExp = attrs.ngOptions;\n var valuesFn, match, track, groupBy, valuePropertyName;\n if (optionsExp && (match = optionsExp.match(NG_OPTIONS_REGEXP))) {\n valuePropertyName = match[1].split('.')[1];\n groupBy = match[3];\n //console.log(optionsExp, groupBy);\n valuesFn = $parse(match[7]);\n track = match[8];\n }\n var ngCtrl = ctrls[0];\n var selectCtrl = ctrls[1];\n // prevent selectDirective render an unknownOption.\n selectCtrl.renderUnknownOption = angular.noop;\n var optionArray = [];\n\n // store data- attribute options of select\n var selectorOptions = {};\n var BS_ATTR = ['container', 'countSelectedText', 'dropupAuto', 'header', 'hideDisabled', 'selectedTextFormat', 'size', 'showSubtext', 'showIcon', 'showContent', 'style', 'title', 'width', 'disabled'];\n\n var checkSelectorOptionsEquality = function () {\n var isEqual = true;\n angular.forEach(BS_ATTR, function (attr) {\n isEqual = isEqual && attrs[attr] === selectorOptions[attr];\n });\n };\n\n var updateSelectorOptions = function () {\n angular.forEach(BS_ATTR, function (attr) {\n selectorOptions[attr] = attrs[attr];\n });\n\n return selectorOptions;\n };\n\n /**\n * Check option data attributes, text and value equality.\n * @param opt the option dom element\n * @param index the index of the option\n * @returns {boolean}\n */\n var checkOptionEquality = function (opt, index) {\n var isEqual = opt.value === optionArray[index].value && opt.text === optionArray[index].text;\n if (isEqual) {\n for (var i = 0; i < opt.attributes.length; i++) {\n if (opt.attributes[i].nodeName.indexOf('data-') !== -1) {\n if (optionArray[index].attributes[opt.attributes[i].nodeName] !== opt.attributes[i].nodeValue) {\n isEqual = false;\n break;\n }\n }\n }\n }\n return isEqual;\n };\n\n var resetDataProperties = function (opt) {\n var attributes = opt.attributes;\n for (var i = 0; i < attributes.length; i++) {\n if (attributes[i].nodeName.indexOf('data-') !== -1) {\n angular.element(opt).data(attributes[i].nodeName.substring(5, attributes[i].nodeName.length), attributes[i].value);\n }\n }\n };\n\n function optionDOMWatch() {\n // check every option if has changed.\n var optionElements = element.find('option');\n\n //if the first option has no value and label or value an value of ?, this must be generated by ngOptions directive. Remove it.\n if (!optionElements.eq(0).html() && (optionElements.eq(0).attr('value') === '?' || !optionElements.eq(0).attr('value'))) {\n // angular seams incorrectly remove the first element of the options. so we have to keep the ? element in the list\n // only remove this ? element when group by is provided.\n if (!!groupBy) {\n optionElements.eq(0).remove();\n }\n }\n\n if (optionElements.length !== optionArray.length) {\n optionArray = makeOptionArray(optionElements);\n buildSelector();\n } else {\n var hasChanged = false;\n optionElements.each(function (index, value) {\n if (!checkOptionEquality(value, index)) {\n // if check fails. reset all data properties.\n resetDataProperties(value);\n hasChanged = true;\n }\n });\n if (hasChanged) {\n buildSelector();\n }\n if (!checkSelectorOptionsEquality()) {\n updateSelectorOptions();\n element.selectpicker('refresh');\n }\n optionArray = makeOptionArray(optionElements);\n }\n }\n\n scope.$watch(function () {\n // Create an object to deep inspect if anything has changed.\n // This is slow, but not as slow as calling optionDOMWatch every $digest\n return {\n ngModel: ngCtrl.$viewValue,\n options: makeOptionArray(element.find('option')),\n selectors: updateSelectorOptions()\n };\n // If any of the above properties change, call optionDOMWatch.\n }, optionDOMWatch, true);\n\n var setValue = function (modelValue) {\n var collection = valuesFn(scope);\n if (angular.isArray(collection) && !angular.isArray(modelValue)) {\n // collection is array and single select mode\n var index = indexInArray(modelValue, collection);\n if (index > -1) {\n element.val(index).selectpicker('render');\n }\n } else if (angular.isArray(collection) && angular.isArray(modelValue)) {\n // collection is array and multiple select mode.\n var indexArray = [];\n for (var i = 0; i < modelValue.length; i++) {\n var indexOfOptions = indexInArray(modelValue[i], collection);\n if (indexOfOptions > -1) {\n indexArray.push(indexOfOptions);\n }\n }\n element.val(indexArray).selectpicker('render');\n } else if (!angular.isArray(collection) && !angular.isArray(modelValue)) {\n // collection is object and single select mode.\n var key = keyOfObject(modelValue, collection);\n if (key) {\n element.val(key).selectpicker('render');\n }\n } else if (!angular.isArray(collection) && angular.isArray(modelValue)) {\n // collection is object and multiple select mode.\n var keyArray = [];\n for (var j = 0; j < modelValue.length; j++) {\n var k = keyOfObject(modelValue[j], collection);\n if (k) {\n keyArray.push(k);\n }\n }\n element.val(keyArray).selectpicker('render');\n }\n };\n\n ngCtrl.$render = function () {\n // model -> view\n var data = element.data('selectpicker');\n if (data) {\n if (!!valuesFn && !track) {\n // transform value to index of options\n setValue(ngCtrl.$viewValue);\n } else {\n element.val(ngCtrl.$viewValue).selectpicker('render');\n }\n }\n };\n\n function indexInArray(value, array) {\n for (var i = 0; i < array.length; i++) {\n if (angular.equals(value, array[i][valuePropertyName])) {\n return i;\n }\n }\n return -1;\n }\n\n function keyOfObject(value, object) {\n var key = null;\n angular.forEach(object, function (v, k) {\n if (angular.equals(v, value)) {\n key = k;\n }\n });\n return key;\n }\n\n /**\n * Copy option value and text and data attributes to an array for future comparison.\n * @param optionElements the source option elements. a jquery objects' array.\n * @returns {Array} the copied array.\n */\n function makeOptionArray(optionElements) {\n var optionArray = [];\n optionElements.each(function (index, childNode) {\n var attributes = {};\n for (var i = 0; i < childNode.attributes.length; i++) {\n if (childNode.attributes[i].nodeName.indexOf('data-') !== -1) {\n attributes[childNode.attributes[i].nodeName] = childNode.attributes[i].nodeValue;\n }\n }\n optionArray.push({\n value: childNode.value,\n text: childNode.text,\n attributes: attributes\n });\n });\n return optionArray;\n }\n\n function buildSelector() {\n // build new selector. if previous select exists. remove previous data and DOM\n var oldSelectPicker = element.data('selectpicker');\n if (oldSelectPicker) {\n oldSelectPicker.$menu.parent().remove();\n oldSelectPicker.$newElement.remove();\n element.removeData('selectpicker');\n }\n element.selectpicker();\n if (!!valuesFn && !track) {\n setValue(ngCtrl.$modelValue);\n } else {\n element.val(ngCtrl.$modelValue).selectpicker('render');\n }\n\n }\n\n }\n };\n }]);","/**\n * Checklist-model\n * AngularJS directive for list of checkboxes\n */\n\nangular.module('checklist-model', [])\n.directive('checklistModel', ['$parse', '$compile', function ($parse, $compile) {\n // contains\n function contains(arr, item) {\n if (angular.isArray(arr)) {\n for (var i = 0; i < arr.length; i++) {\n if (angular.equals(arr[i], item)) {\n return true;\n }\n }\n }\n return false;\n }\n\n // add\n function add(arr, item) {\n arr = angular.isArray(arr) ? arr : [];\n for (var i = 0; i < arr.length; i++) {\n if (angular.equals(arr[i], item)) {\n return arr;\n }\n }\n arr.push(item);\n return arr;\n }\n\n // remove\n function remove(arr, item) {\n if (angular.isArray(arr)) {\n for (var i = 0; i < arr.length; i++) {\n if (angular.equals(arr[i], item)) {\n arr.splice(i, 1);\n break;\n }\n }\n }\n return arr;\n }\n\n // http://stackoverflow.com/a/19228302/1458162\n function postLinkFn(scope, elem, attrs) {\n // compile with `ng-model` pointing to `checked`\n $compile(elem)(scope);\n\n // getter / setter for original model\n var getter = $parse(attrs.checklistModel);\n var setter = getter.assign;\n\n // value added to list\n var value = $parse(attrs.checklistValue)(scope.$parent);\n\n // watch UI checked change\n scope.$watch('checked', function (newValue, oldValue) {\n if (newValue === oldValue) {\n return;\n }\n var current = getter(scope.$parent);\n if (newValue === true) {\n setter(scope.$parent, add(current, value));\n } else {\n setter(scope.$parent, remove(current, value));\n }\n });\n\n // watch original model change\n scope.$parent.$watch(attrs.checklistModel, function (newArr, oldArr) {\n scope.checked = contains(newArr, value);\n }, true);\n }\n\n return {\n restrict: 'A',\n priority: 1000,\n terminal: true,\n scope: true,\n compile: function (tElement, tAttrs) {\n if (tElement[0].tagName !== 'INPUT' || !tElement.attr('type', 'checkbox')) {\n throw 'checklist-model should be applied to `input[type=\"checkbox\"]`.';\n }\n\n if (!tAttrs.checklistValue) {\n throw 'You should provide `checklist-value`.';\n }\n\n // exclude recursion\n tElement.removeAttr('checklist-model');\n\n // local scope var storing individual checkbox model\n tElement.attr('ng-model', 'checked');\n\n return postLinkFn;\n }\n };\n}]);\n","/* =============================================================\n/*\n/*\t Angular Smooth Scroll 1.7.1\n/*\t Animates scrolling to elements, by David Oliveros.\n/*\n/* Callback hooks contributed by Ben Armston\n/* https://github.com/benarmston\n/*\n/*\t Easing support contributed by Willem Liu.\n/*\t https://github.com/willemliu\n/*\n/*\t Easing functions forked from Gaëtan Renaudeau.\n/*\t https://gist.github.com/gre/1650294\n/*\n/*\t Infinite loop bugs in iOS and Chrome (when zoomed) by Alex Guzman.\n/*\t https://github.com/alexguzman\n/*\n/*\t Influenced by Chris Ferdinandi\n/*\t https://github.com/cferdinandi\n/*\n/*\n/*\t Free to use under the MIT License.\n/*\n/* ============================================================= */\n\n(function () {\n 'use strict';\n\n var module = angular.module('smoothScroll', []);\n\n\n // Smooth scrolls the window to the provided element.\n //\n var smoothScroll = function (element, options) {\n options = options || {};\n\n // Options\n var duration = options.duration || 800,\n\t\t\toffset = options.offset || 0,\n\t\t\teasing = options.easing || 'easeInOutQuart',\n\t\t\tcallbackBefore = options.callbackBefore || function () { },\n\t\t\tcallbackAfter = options.callbackAfter || function () { };\n\n var getScrollLocation = function () {\n return window.pageYOffset ? window.pageYOffset : document.documentElement.scrollTop;\n };\n\n setTimeout(function () {\n var startLocation = getScrollLocation(),\n\t\t\t\ttimeLapsed = 0,\n\t\t\t\tpercentage, position;\n\n // Calculate the easing pattern\n var easingPattern = function (type, time) {\n if (type == 'easeInQuad') return time * time; // accelerating from zero velocity\n if (type == 'easeOutQuad') return time * (2 - time); // decelerating to zero velocity\n if (type == 'easeInOutQuad') return time < 0.5 ? 2 * time * time : -1 + (4 - 2 * time) * time; // acceleration until halfway, then deceleration\n if (type == 'easeInCubic') return time * time * time; // accelerating from zero velocity\n if (type == 'easeOutCubic') return (--time) * time * time + 1; // decelerating to zero velocity\n if (type == 'easeInOutCubic') return time < 0.5 ? 4 * time * time * time : (time - 1) * (2 * time - 2) * (2 * time - 2) + 1; // acceleration until halfway, then deceleration\n if (type == 'easeInQuart') return time * time * time * time; // accelerating from zero velocity\n if (type == 'easeOutQuart') return 1 - (--time) * time * time * time; // decelerating to zero velocity\n if (type == 'easeInOutQuart') return time < 0.5 ? 8 * time * time * time * time : 1 - 8 * (--time) * time * time * time; // acceleration until halfway, then deceleration\n if (type == 'easeInQuint') return time * time * time * time * time; // accelerating from zero velocity\n if (type == 'easeOutQuint') return 1 + (--time) * time * time * time * time; // decelerating to zero velocity\n if (type == 'easeInOutQuint') return time < 0.5 ? 16 * time * time * time * time * time : 1 + 16 * (--time) * time * time * time * time; // acceleration until halfway, then deceleration\n return time; // no easing, no acceleration\n };\n\n\n // Calculate how far to scroll\n var getEndLocation = function (element) {\n var location = 0;\n if (element.offsetParent) {\n do {\n location += element.offsetTop;\n element = element.offsetParent;\n } while (element);\n }\n location = Math.max(location - offset, 0);\n return location;\n };\n\n var endLocation = getEndLocation(element);\n var distance = endLocation - startLocation;\n\n\n // Stop the scrolling animation when the anchor is reached (or at the top/bottom of the page)\n var stopAnimation = function () {\n var currentLocation = getScrollLocation();\n if (position == endLocation || currentLocation == endLocation || ((window.innerHeight + currentLocation) >= document.body.scrollHeight)) {\n clearInterval(runAnimation);\n callbackAfter(element);\n }\n };\n\n\n // Scroll the page by an increment, and check if it's time to stop\n var animateScroll = function () {\n timeLapsed += 16;\n percentage = (timeLapsed / duration);\n percentage = (percentage > 1) ? 1 : percentage;\n position = startLocation + (distance * easingPattern(easing, percentage));\n window.scrollTo(0, position);\n stopAnimation();\n };\n\n\n // Init\n callbackBefore(element);\n var runAnimation = setInterval(animateScroll, 16);\n }, 0);\n };\n\n\n // Expose the library in a factory\n //\n module.factory('smoothScroll', function () {\n return smoothScroll;\n });\n\n\n // Scrolls the window to this element, optionally validating an expression\n //\n module.directive('smoothScroll', ['smoothScroll', function (smoothScroll) {\n return {\n restrict: 'A',\n scope: {\n callbackBefore: '&',\n callbackAfter: '&',\n },\n link: function ($scope, $elem, $attrs) {\n if (typeof $attrs.scrollIf === 'undefined' || $attrs.scrollIf === 'true') {\n setTimeout(function () {\n\n var callbackBefore = function (element) {\n if ($attrs.callbackBefore) {\n var exprHandler = $scope.callbackBefore({ element: element });\n if (typeof exprHandler === 'function') {\n exprHandler(element);\n }\n }\n };\n\n var callbackAfter = function (element) {\n if ($attrs.callbackAfter) {\n var exprHandler = $scope.callbackAfter({ element: element });\n if (typeof exprHandler === 'function') {\n exprHandler(element);\n }\n }\n };\n\n smoothScroll($elem[0], {\n duration: $attrs.duration,\n offset: $attrs.offset,\n easing: $attrs.easing,\n callbackBefore: callbackBefore,\n callbackAfter: callbackAfter\n });\n }, 0);\n }\n }\n };\n }]);\n\n\n // Scrolls to a specified element ID when this element is clicked\n //\n module.directive('scrollTo', ['smoothScroll', function (smoothScroll) {\n return {\n restrict: 'A',\n scope: {\n callbackBefore: '&',\n callbackAfter: '&',\n },\n link: function ($scope, $elem, $attrs) {\n var targetElement;\n\n $elem.on('click', function (e) {\n e.preventDefault();\n\n targetElement = document.getElementById($attrs.scrollTo);\n if (!targetElement) return;\n\n var callbackBefore = function (element) {\n if ($attrs.callbackBefore) {\n var exprHandler = $scope.callbackBefore({ element: element });\n if (typeof exprHandler === 'function') {\n exprHandler(element);\n }\n }\n };\n\n var callbackAfter = function (element) {\n if ($attrs.callbackAfter) {\n var exprHandler = $scope.callbackAfter({ element: element });\n if (typeof exprHandler === 'function') {\n exprHandler(element);\n }\n }\n };\n\n smoothScroll(targetElement, {\n duration: $attrs.duration,\n offset: $attrs.offset,\n easing: $attrs.easing,\n callbackBefore: callbackBefore,\n callbackAfter: callbackAfter\n });\n\n return false;\n });\n }\n };\n }]);\n\n}());","/*\n angular-file-upload v1.1.5\n https://github.com/nervgh/angular-file-upload\n*/\n(function(angular, factory) {\n if (typeof define === 'function' && define.amd) {\n define('angular-file-upload', ['angular'], function(angular) {\n return factory(angular);\n });\n } else {\n return factory(angular);\n }\n}(typeof angular === 'undefined' ? null : angular, function(angular) {\n\nvar module = angular.module('angularFileUpload', []);\n\n'use strict';\n\n/**\n * Classes\n *\n * FileUploader\n * FileUploader.FileLikeObject\n * FileUploader.FileItem\n * FileUploader.FileDirective\n * FileUploader.FileSelect\n * FileUploader.FileDrop\n * FileUploader.FileOver\n */\n\nmodule\n\n\n .value('fileUploaderOptions', {\n url: '/',\n alias: 'file',\n headers: {},\n queue: [],\n progress: 0,\n autoUpload: false,\n removeAfterUpload: false,\n method: 'POST',\n filters: [],\n formData: [],\n queueLimit: Number.MAX_VALUE,\n withCredentials: false\n })\n\n\n .factory('FileUploader', ['fileUploaderOptions', '$rootScope', '$http', '$window', '$compile',\n function(fileUploaderOptions, $rootScope, $http, $window, $compile) {\n /**\n * Creates an instance of FileUploader\n * @param {Object} [options]\n * @constructor\n */\n function FileUploader(options) {\n var settings = angular.copy(fileUploaderOptions);\n angular.extend(this, settings, options, {\n isUploading: false,\n _nextIndex: 0,\n _failFilterIndex: -1,\n _directives: {select: [], drop: [], over: []}\n });\n\n // add default filters\n this.filters.unshift({name: 'queueLimit', fn: this._queueLimitFilter});\n this.filters.unshift({name: 'folder', fn: this._folderFilter});\n }\n /**********************\n * PUBLIC\n **********************/\n /**\n * Checks a support the html5 uploader\n * @returns {Boolean}\n * @readonly\n */\n FileUploader.prototype.isHTML5 = !!($window.File && $window.FormData);\n /**\n * Adds items to the queue\n * @param {File|HTMLInputElement|Object|FileList|Array} files\n * @param {Object} [options]\n * @param {Array|String} filters\n */\n FileUploader.prototype.addToQueue = function(files, options, filters) {\n var list = this.isArrayLikeObject(files) ? files: [files];\n var arrayOfFilters = this._getFilters(filters);\n var count = this.queue.length;\n var addedFileItems = [];\n\n angular.forEach(list, function(some /*{File|HTMLInputElement|Object}*/) {\n var temp = new FileUploader.FileLikeObject(some);\n\n if (this._isValidFile(temp, arrayOfFilters, options)) {\n var fileItem = new FileUploader.FileItem(this, some, options);\n addedFileItems.push(fileItem);\n this.queue.push(fileItem);\n this._onAfterAddingFile(fileItem);\n } else {\n var filter = this.filters[this._failFilterIndex];\n this._onWhenAddingFileFailed(temp, filter, options);\n }\n }, this);\n\n if(this.queue.length !== count) {\n this._onAfterAddingAll(addedFileItems);\n this.progress = this._getTotalProgress();\n }\n\n this._render();\n if (this.autoUpload) this.uploadAll();\n };\n /**\n * Remove items from the queue. Remove last: index = -1\n * @param {FileItem|Number} value\n */\n FileUploader.prototype.removeFromQueue = function(value) {\n var index = this.getIndexOfItem(value);\n var item = this.queue[index];\n if (item.isUploading) item.cancel();\n this.queue.splice(index, 1);\n item._destroy();\n this.progress = this._getTotalProgress();\n };\n /**\n * Clears the queue\n */\n FileUploader.prototype.clearQueue = function() {\n while(this.queue.length) {\n this.queue[0].remove();\n }\n this.progress = 0;\n };\n /**\n * Uploads a item from the queue\n * @param {FileItem|Number} value\n */\n FileUploader.prototype.uploadItem = function(value) {\n var index = this.getIndexOfItem(value);\n var item = this.queue[index];\n var transport = this.isHTML5 ? '_xhrTransport' : '_iframeTransport';\n\n item._prepareToUploading();\n if(this.isUploading) return;\n\n this.isUploading = true;\n this[transport](item);\n };\n /**\n * Cancels uploading of item from the queue\n * @param {FileItem|Number} value\n */\n FileUploader.prototype.cancelItem = function(value) {\n var index = this.getIndexOfItem(value);\n var item = this.queue[index];\n var prop = this.isHTML5 ? '_xhr' : '_form';\n if (item && item.isUploading) item[prop].abort();\n };\n /**\n * Uploads all not uploaded items of queue\n */\n FileUploader.prototype.uploadAll = function() {\n var items = this.getNotUploadedItems().filter(function(item) {\n return !item.isUploading;\n });\n if (!items.length) return;\n\n angular.forEach(items, function(item) {\n item._prepareToUploading();\n });\n items[0].upload();\n };\n /**\n * Cancels all uploads\n */\n FileUploader.prototype.cancelAll = function() {\n var items = this.getNotUploadedItems();\n angular.forEach(items, function(item) {\n item.cancel();\n });\n };\n /**\n * Returns \"true\" if value an instance of File\n * @param {*} value\n * @returns {Boolean}\n * @private\n */\n FileUploader.prototype.isFile = function(value) {\n var fn = $window.File;\n return (fn && value instanceof fn);\n };\n /**\n * Returns \"true\" if value an instance of FileLikeObject\n * @param {*} value\n * @returns {Boolean}\n * @private\n */\n FileUploader.prototype.isFileLikeObject = function(value) {\n return value instanceof FileUploader.FileLikeObject;\n };\n /**\n * Returns \"true\" if value is array like object\n * @param {*} value\n * @returns {Boolean}\n */\n FileUploader.prototype.isArrayLikeObject = function(value) {\n return (angular.isObject(value) && 'length' in value);\n };\n /**\n * Returns a index of item from the queue\n * @param {Item|Number} value\n * @returns {Number}\n */\n FileUploader.prototype.getIndexOfItem = function(value) {\n return angular.isNumber(value) ? value : this.queue.indexOf(value);\n };\n /**\n * Returns not uploaded items\n * @returns {Array}\n */\n FileUploader.prototype.getNotUploadedItems = function() {\n return this.queue.filter(function(item) {\n return !item.isUploaded;\n });\n };\n /**\n * Returns items ready for upload\n * @returns {Array}\n */\n FileUploader.prototype.getReadyItems = function() {\n return this.queue\n .filter(function(item) {\n return (item.isReady && !item.isUploading);\n })\n .sort(function(item1, item2) {\n return item1.index - item2.index;\n });\n };\n /**\n * Destroys instance of FileUploader\n */\n FileUploader.prototype.destroy = function() {\n angular.forEach(this._directives, function(key) {\n angular.forEach(this._directives[key], function(object) {\n object.destroy();\n }, this);\n }, this);\n };\n /**\n * Callback\n * @param {Array} fileItems\n */\n FileUploader.prototype.onAfterAddingAll = function(fileItems) {};\n /**\n * Callback\n * @param {FileItem} fileItem\n */\n FileUploader.prototype.onAfterAddingFile = function(fileItem) {};\n /**\n * Callback\n * @param {File|Object} item\n * @param {Object} filter\n * @param {Object} options\n * @private\n */\n FileUploader.prototype.onWhenAddingFileFailed = function(item, filter, options) {};\n /**\n * Callback\n * @param {FileItem} fileItem\n */\n FileUploader.prototype.onBeforeUploadItem = function(fileItem) {};\n /**\n * Callback\n * @param {FileItem} fileItem\n * @param {Number} progress\n */\n FileUploader.prototype.onProgressItem = function(fileItem, progress) {};\n /**\n * Callback\n * @param {Number} progress\n */\n FileUploader.prototype.onProgressAll = function(progress) {};\n /**\n * Callback\n * @param {FileItem} item\n * @param {*} response\n * @param {Number} status\n * @param {Object} headers\n */\n FileUploader.prototype.onSuccessItem = function(item, response, status, headers) {};\n /**\n * Callback\n * @param {FileItem} item\n * @param {*} response\n * @param {Number} status\n * @param {Object} headers\n */\n FileUploader.prototype.onErrorItem = function(item, response, status, headers) {};\n /**\n * Callback\n * @param {FileItem} item\n * @param {*} response\n * @param {Number} status\n * @param {Object} headers\n */\n FileUploader.prototype.onCancelItem = function(item, response, status, headers) {};\n /**\n * Callback\n * @param {FileItem} item\n * @param {*} response\n * @param {Number} status\n * @param {Object} headers\n */\n FileUploader.prototype.onCompleteItem = function(item, response, status, headers) {};\n /**\n * Callback\n */\n FileUploader.prototype.onCompleteAll = function() {};\n /**********************\n * PRIVATE\n **********************/\n /**\n * Returns the total progress\n * @param {Number} [value]\n * @returns {Number}\n * @private\n */\n FileUploader.prototype._getTotalProgress = function(value) {\n if(this.removeAfterUpload) return value || 0;\n\n var notUploaded = this.getNotUploadedItems().length;\n var uploaded = notUploaded ? this.queue.length - notUploaded : this.queue.length;\n var ratio = 100 / this.queue.length;\n var current = (value || 0) * ratio / 100;\n\n return Math.round(uploaded * ratio + current);\n };\n /**\n * Returns array of filters\n * @param {Array|String} filters\n * @returns {Array}\n * @private\n */\n FileUploader.prototype._getFilters = function(filters) {\n if (angular.isUndefined(filters)) return this.filters;\n if (angular.isArray(filters)) return filters;\n var names = filters.match(/[^\\s,]+/g);\n return this.filters.filter(function(filter) {\n return names.indexOf(filter.name) !== -1;\n }, this);\n };\n /**\n * Updates html\n * @private\n */\n FileUploader.prototype._render = function() {\n if (!$rootScope.$$phase) $rootScope.$apply();\n };\n /**\n * Returns \"true\" if item is a file (not folder)\n * @param {File|FileLikeObject} item\n * @returns {Boolean}\n * @private\n */\n FileUploader.prototype._folderFilter = function(item) {\n return !!(item.size || item.type);\n };\n /**\n * Returns \"true\" if the limit has not been reached\n * @returns {Boolean}\n * @private\n */\n FileUploader.prototype._queueLimitFilter = function() {\n return this.queue.length < this.queueLimit;\n };\n /**\n * Returns \"true\" if file pass all filters\n * @param {File|Object} file\n * @param {Array} filters\n * @param {Object} options\n * @returns {Boolean}\n * @private\n */\n FileUploader.prototype._isValidFile = function(file, filters, options) {\n this._failFilterIndex = -1;\n return !filters.length ? true : filters.every(function(filter) {\n this._failFilterIndex++;\n return filter.fn.call(this, file, options);\n }, this);\n };\n /**\n * Checks whether upload successful\n * @param {Number} status\n * @returns {Boolean}\n * @private\n */\n FileUploader.prototype._isSuccessCode = function(status) {\n return (status >= 200 && status < 300) || status === 304;\n };\n /**\n * Transforms the server response\n * @param {*} response\n * @param {Object} headers\n * @returns {*}\n * @private\n */\n FileUploader.prototype._transformResponse = function(response, headers) {\n var headersGetter = this._headersGetter(headers);\n angular.forEach($http.defaults.transformResponse, function(transformFn) {\n response = transformFn(response, headersGetter);\n });\n return response;\n };\n /**\n * Parsed response headers\n * @param headers\n * @returns {Object}\n * @see https://github.com/angular/angular.js/blob/master/src/ng/http.js\n * @private\n */\n FileUploader.prototype._parseHeaders = function(headers) {\n var parsed = {}, key, val, i;\n\n if (!headers) return parsed;\n\n angular.forEach(headers.split('\\n'), function(line) {\n i = line.indexOf(':');\n key = line.slice(0, i).trim().toLowerCase();\n val = line.slice(i + 1).trim();\n\n if (key) {\n parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;\n }\n });\n\n return parsed;\n };\n /**\n * Returns function that returns headers\n * @param {Object} parsedHeaders\n * @returns {Function}\n * @private\n */\n FileUploader.prototype._headersGetter = function(parsedHeaders) {\n return function(name) {\n if (name) {\n return parsedHeaders[name.toLowerCase()] || null;\n }\n return parsedHeaders;\n };\n };\n /**\n * The XMLHttpRequest transport\n * @param {FileItem} item\n * @private\n */\n FileUploader.prototype._xhrTransport = function(item) {\n var xhr = item._xhr = new XMLHttpRequest();\n var form = new FormData();\n var that = this;\n\n that._onBeforeUploadItem(item);\n\n angular.forEach(item.formData, function(obj) {\n angular.forEach(obj, function(value, key) {\n form.append(key, value);\n });\n });\n\n form.append(item.alias, item._file, item.file.name);\n\n xhr.upload.onprogress = function(event) {\n var progress = Math.round(event.lengthComputable ? event.loaded * 100 / event.total : 0);\n that._onProgressItem(item, progress);\n };\n\n xhr.onload = function() {\n var headers = that._parseHeaders(xhr.getAllResponseHeaders());\n var response = that._transformResponse(xhr.response, headers);\n var gist = that._isSuccessCode(xhr.status) ? 'Success' : 'Error';\n var method = '_on' + gist + 'Item';\n that[method](item, response, xhr.status, headers);\n that._onCompleteItem(item, response, xhr.status, headers);\n };\n\n xhr.onerror = function() {\n var headers = that._parseHeaders(xhr.getAllResponseHeaders());\n var response = that._transformResponse(xhr.response, headers);\n that._onErrorItem(item, response, xhr.status, headers);\n that._onCompleteItem(item, response, xhr.status, headers);\n };\n\n xhr.onabort = function() {\n var headers = that._parseHeaders(xhr.getAllResponseHeaders());\n var response = that._transformResponse(xhr.response, headers);\n that._onCancelItem(item, response, xhr.status, headers);\n that._onCompleteItem(item, response, xhr.status, headers);\n };\n\n xhr.open(item.method, item.url, true);\n\n xhr.withCredentials = item.withCredentials;\n\n angular.forEach(item.headers, function(value, name) {\n xhr.setRequestHeader(name, value);\n });\n\n xhr.send(form);\n this._render();\n };\n /**\n * The IFrame transport\n * @param {FileItem} item\n * @private\n */\n FileUploader.prototype._iframeTransport = function(item) {\n var form = angular.element('
      ');\n var iframe = angular.element('