code_text
stringlengths 604
999k
| repo_name
stringlengths 4
100
| file_path
stringlengths 4
873
| language
stringclasses 23
values | license
stringclasses 15
values | size
int32 1.02k
999k
|
---|---|---|---|---|---|
.yui3-skin-sam .yui3-scrollview-scrollbar {
-webkit-transform: translate3d(0, 0, 0);
-moz-transform: translate(0, 0);
}
.yui3-skin-sam .yui3-scrollview-scrollbar .yui3-scrollview-first,
.yui3-skin-sam .yui3-scrollview-scrollbar .yui3-scrollview-middle,
.yui3-skin-sam .yui3-scrollview-scrollbar .yui3-scrollview-last {
border-radius:3px;
-webkit-border-radius: 3px;
-moz-border-radius: 3px;
background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAABCAYAAAD9yd/wAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAABJJREFUeNpiZGBgSGPAAgACDAAIkABoFyloZQAAAABJRU5ErkJggg==);
}
.yui3-skin-sam .yui3-scrollview-scrollbar .yui3-scrollview-first,
.yui3-skin-sam .yui3-scrollview-scrollbar .yui3-scrollview-last {
border-bottom-right-radius:0;
border-bottom-left-radius:0;
-webkit-border-bottom-right-radius:0;
-webkit-border-bottom-left-radius:0;
-moz-border-radius-bottomright:0;
-moz-border-radius-bottomleft:0;
}
.yui3-skin-sam .yui3-scrollview-scrollbar .yui3-scrollview-last {
border-radius:0;
border-bottom-right-radius:3px;
border-bottom-left-radius:3px;
-webkit-border-radius:0;
-webkit-border-bottom-right-radius:3px;
-webkit-border-bottom-left-radius:3px;
-webkit-transform: translate3d(0, 0, 0);
-moz-border-radius:0;
-moz-border-radius-bottomright:3px;
-moz-border-radius-bottomleft:3px;
-moz-transform: translate(0, 0);
}
.yui3-skin-sam .yui3-scrollview-scrollbar .yui3-scrollview-middle {
border-radius:0;
-webkit-border-radius: 0;
-moz-border-radius: 0;
-webkit-transform: translate3d(0,0,0) scaleY(1);
-webkit-transform-origin-y: 0;
-moz-transform: translate(0,0) scaleY(1);
-moz-transform-origin: 0 0;
}
.yui3-skin-sam .yui3-scrollview-scrollbar-horiz .yui3-scrollview-first,
.yui3-skin-sam .yui3-scrollview-scrollbar-horiz .yui3-scrollview-last {
border-top-right-radius: 0;
border-bottom-left-radius: 3px;
-webkit-border-top-right-radius: 0;
-webkit-border-bottom-left-radius: 3px;
-moz-border-radius-topright: 0;
-moz-border-radius-bottomleft: 3px;
}
.yui3-skin-sam .yui3-scrollview-scrollbar-horiz .yui3-scrollview-last {
border-bottom-left-radius: 0;
border-top-right-radius: 3px;
-webkit-border-bottom-left-radius: 0;
-webkit-border-top-right-radius: 3px;
-moz-border-radius-bottomleft: 0;
-moz-border-radius-topright: 3px;
}
.yui3-skin-sam .yui3-scrollview-scrollbar-horiz .yui3-scrollview-middle {
-webkit-transform: translate3d(0,0,0) scaleX(1);
-webkit-transform-origin: 0 0;
-moz-transform: translate(0,0) scaleX(1);
-moz-transform-origin: 0 0;
}
.yui3-skin-sam .yui3-scrollview-scrollbar-vert-basic .yui3-scrollview-child,
.yui3-skin-sam .yui3-scrollview-scrollbar-horiz-basic .yui3-scrollview-child {
background-color: #aaa;
background-image: none;
} | tonytlwu/cdnjs | ajax/libs/yui/3.7.0pr2/scrollview-scrollbars/assets/skins/sam/scrollview-scrollbars-skin.css | CSS | mit | 2,928 |
import os
import gettext as gettext_module
from django import http
from django.conf import settings
from django.utils import importlib
from django.utils.translation import check_for_language, activate, to_locale, get_language
from django.utils.text import javascript_quote
from django.utils.encoding import smart_unicode
from django.utils.formats import get_format_modules, get_format
def set_language(request):
"""
Redirect to a given url while setting the chosen language in the
session or cookie. The url and the language code need to be
specified in the request parameters.
Since this view changes how the user will see the rest of the site, it must
only be accessed as a POST request. If called as a GET request, it will
redirect to the page in the request (the 'next' parameter) without changing
any state.
"""
next = request.REQUEST.get('next', None)
if not next:
next = request.META.get('HTTP_REFERER', None)
if not next:
next = '/'
response = http.HttpResponseRedirect(next)
if request.method == 'POST':
lang_code = request.POST.get('language', None)
if lang_code and check_for_language(lang_code):
if hasattr(request, 'session'):
request.session['django_language'] = lang_code
else:
response.set_cookie(settings.LANGUAGE_COOKIE_NAME, lang_code)
return response
def get_formats():
"""
Returns all formats strings required for i18n to work
"""
FORMAT_SETTINGS = (
'DATE_FORMAT', 'DATETIME_FORMAT', 'TIME_FORMAT',
'YEAR_MONTH_FORMAT', 'MONTH_DAY_FORMAT', 'SHORT_DATE_FORMAT',
'SHORT_DATETIME_FORMAT', 'FIRST_DAY_OF_WEEK', 'DECIMAL_SEPARATOR',
'THOUSAND_SEPARATOR', 'NUMBER_GROUPING',
'DATE_INPUT_FORMATS', 'TIME_INPUT_FORMATS', 'DATETIME_INPUT_FORMATS'
)
result = {}
for module in [settings] + get_format_modules(reverse=True):
for attr in FORMAT_SETTINGS:
result[attr] = get_format(attr)
src = []
for k, v in result.items():
if isinstance(v, (basestring, int)):
src.append("formats['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(smart_unicode(v))))
elif isinstance(v, (tuple, list)):
v = [javascript_quote(smart_unicode(value)) for value in v]
src.append("formats['%s'] = ['%s'];\n" % (javascript_quote(k), "', '".join(v)))
return ''.join(src)
NullSource = """
/* gettext identity library */
function gettext(msgid) { return msgid; }
function ngettext(singular, plural, count) { return (count == 1) ? singular : plural; }
function gettext_noop(msgid) { return msgid; }
function pgettext(context, msgid) { return msgid; }
function npgettext(context, singular, plural, count) { return (count == 1) ? singular : plural; }
"""
LibHead = """
/* gettext library */
var catalog = new Array();
"""
LibFoot = """
function gettext(msgid) {
var value = catalog[msgid];
if (typeof(value) == 'undefined') {
return msgid;
} else {
return (typeof(value) == 'string') ? value : value[0];
}
}
function ngettext(singular, plural, count) {
value = catalog[singular];
if (typeof(value) == 'undefined') {
return (count == 1) ? singular : plural;
} else {
return value[pluralidx(count)];
}
}
function gettext_noop(msgid) { return msgid; }
function pgettext(context, msgid) {
var value = gettext(context + '\x04' + msgid);
if (value.indexOf('\x04') != -1) {
value = msgid;
}
return value;
}
function npgettext(context, singular, plural, count) {
var value = ngettext(context + '\x04' + singular, context + '\x04' + plural, count);
if (value.indexOf('\x04') != -1) {
value = ngettext(singular, plural, count);
}
return value;
}
"""
LibFormatHead = """
/* formatting library */
var formats = new Array();
"""
LibFormatFoot = """
function get_format(format_type) {
var value = formats[format_type];
if (typeof(value) == 'undefined') {
return msgid;
} else {
return value;
}
}
"""
SimplePlural = """
function pluralidx(count) { return (count == 1) ? 0 : 1; }
"""
InterPolate = r"""
function interpolate(fmt, obj, named) {
if (named) {
return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
} else {
return fmt.replace(/%s/g, function(match){return String(obj.shift())});
}
}
"""
PluralIdx = r"""
function pluralidx(n) {
var v=%s;
if (typeof(v) == 'boolean') {
return v ? 1 : 0;
} else {
return v;
}
}
"""
def null_javascript_catalog(request, domain=None, packages=None):
"""
Returns "identity" versions of the JavaScript i18n functions -- i.e.,
versions that don't actually do anything.
"""
src = [NullSource, InterPolate, LibFormatHead, get_formats(), LibFormatFoot]
return http.HttpResponse(''.join(src), 'text/javascript')
def javascript_catalog(request, domain='djangojs', packages=None):
"""
Returns the selected language catalog as a javascript library.
Receives the list of packages to check for translations in the
packages parameter either from an infodict or as a +-delimited
string from the request. Default is 'django.conf'.
Additionally you can override the gettext domain for this view,
but usually you don't want to do that, as JavaScript messages
go to the djangojs domain. But this might be needed if you
deliver your JavaScript source from Django templates.
"""
if request.GET:
if 'language' in request.GET:
if check_for_language(request.GET['language']):
activate(request.GET['language'])
if packages is None:
packages = ['django.conf']
if isinstance(packages, basestring):
packages = packages.split('+')
packages = [p for p in packages if p == 'django.conf' or p in settings.INSTALLED_APPS]
default_locale = to_locale(settings.LANGUAGE_CODE)
locale = to_locale(get_language())
t = {}
paths = []
en_selected = locale.startswith('en')
en_catalog_missing = True
# paths of requested packages
for package in packages:
p = importlib.import_module(package)
path = os.path.join(os.path.dirname(p.__file__), 'locale')
paths.append(path)
# add the filesystem paths listed in the LOCALE_PATHS setting
paths.extend(list(reversed(settings.LOCALE_PATHS)))
# first load all english languages files for defaults
for path in paths:
try:
catalog = gettext_module.translation(domain, path, ['en'])
t.update(catalog._catalog)
except IOError:
pass
else:
# 'en' is the selected language and at least one of the packages
# listed in `packages` has an 'en' catalog
if en_selected:
en_catalog_missing = False
# next load the settings.LANGUAGE_CODE translations if it isn't english
if default_locale != 'en':
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [default_locale])
except IOError:
catalog = None
if catalog is not None:
t.update(catalog._catalog)
# last load the currently selected language, if it isn't identical to the default.
if locale != default_locale:
# If the currently selected language is English but it doesn't have a
# translation catalog (presumably due to being the language translated
# from) then a wrong language catalog might have been loaded in the
# previous step. It needs to be discarded.
if en_selected and en_catalog_missing:
t = {}
else:
locale_t = {}
for path in paths:
try:
catalog = gettext_module.translation(domain, path, [locale])
except IOError:
catalog = None
if catalog is not None:
locale_t.update(catalog._catalog)
if locale_t:
t = locale_t
src = [LibHead]
plural = None
if '' in t:
for l in t[''].split('\n'):
if l.startswith('Plural-Forms:'):
plural = l.split(':',1)[1].strip()
if plural is not None:
# this should actually be a compiled function of a typical plural-form:
# Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
plural = [el.strip() for el in plural.split(';') if el.strip().startswith('plural=')][0].split('=',1)[1]
src.append(PluralIdx % plural)
else:
src.append(SimplePlural)
csrc = []
pdict = {}
for k, v in t.items():
if k == '':
continue
if isinstance(k, basestring):
csrc.append("catalog['%s'] = '%s';\n" % (javascript_quote(k), javascript_quote(v)))
elif isinstance(k, tuple):
if k[0] not in pdict:
pdict[k[0]] = k[1]
else:
pdict[k[0]] = max(k[1], pdict[k[0]])
csrc.append("catalog['%s'][%d] = '%s';\n" % (javascript_quote(k[0]), k[1], javascript_quote(v)))
else:
raise TypeError(k)
csrc.sort()
for k, v in pdict.items():
src.append("catalog['%s'] = [%s];\n" % (javascript_quote(k), ','.join(["''"]*(v+1))))
src.extend(csrc)
src.append(LibFoot)
src.append(InterPolate)
src.append(LibFormatHead)
src.append(get_formats())
src.append(LibFormatFoot)
src = ''.join(src)
return http.HttpResponse(src, 'text/javascript')
| joeyjojo/django_offline | src/django/views/i18n.py | Python | mit | 9,673 |
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule CallbackQueue
*/
'use strict';
var PooledClass = require('PooledClass');
var assign = require('Object.assign');
var invariant = require('invariant');
/**
* A specialized pseudo-event module to help keep track of components waiting to
* be notified when their DOM representations are available for use.
*
* This implements `PooledClass`, so you should never need to instantiate this.
* Instead, use `CallbackQueue.getPooled()`.
*
* @class ReactMountReady
* @implements PooledClass
* @internal
*/
function CallbackQueue() {
this._callbacks = null;
this._contexts = null;
}
assign(CallbackQueue.prototype, {
/**
* Enqueues a callback to be invoked when `notifyAll` is invoked.
*
* @param {function} callback Invoked when `notifyAll` is invoked.
* @param {?object} context Context to call `callback` with.
* @internal
*/
enqueue: function(callback, context) {
this._callbacks = this._callbacks || [];
this._contexts = this._contexts || [];
this._callbacks.push(callback);
this._contexts.push(context);
},
/**
* Invokes all enqueued callbacks and clears the queue. This is invoked after
* the DOM representation of a component has been created or updated.
*
* @internal
*/
notifyAll: function() {
var callbacks = this._callbacks;
var contexts = this._contexts;
if (callbacks) {
invariant(
callbacks.length === contexts.length,
'Mismatched list of contexts in callback queue'
);
this._callbacks = null;
this._contexts = null;
for (var i = 0, l = callbacks.length; i < l; i++) {
callbacks[i].call(contexts[i]);
}
callbacks.length = 0;
contexts.length = 0;
}
},
/**
* Resets the internal queue.
*
* @internal
*/
reset: function() {
this._callbacks = null;
this._contexts = null;
},
/**
* `PooledClass` looks for this.
*/
destructor: function() {
this.reset();
}
});
PooledClass.addPoolingTo(CallbackQueue);
module.exports = CallbackQueue;
| yousefmoazzam/ZebraWithFlux | node_modules/reactify/node_modules/react-tools/src/utils/CallbackQueue.js | JavaScript | mit | 2,369 |
define("ace/snippets/sh",["require","exports","module"],function(e,t,n){"use strict";t.snippetText='# Shebang. Executing bash via /usr/bin/env makes scripts more portable.\nsnippet #!\n #!/usr/bin/env bash\n \nsnippet if\n if [[ ${1:condition} ]]; then\n ${2:#statements}\n fi\nsnippet elif\n elif [[ ${1:condition} ]]; then\n ${2:#statements}\nsnippet for\n for (( ${2:i} = 0; $2 < ${1:count}; $2++ )); do\n ${3:#statements}\n done\nsnippet fori\n for ${1:needle} in ${2:haystack} ; do\n ${3:#statements}\n done\nsnippet wh\n while [[ ${1:condition} ]]; do\n ${2:#statements}\n done\nsnippet until\n until [[ ${1:condition} ]]; do\n ${2:#statements}\n done\nsnippet case\n case ${1:word} in\n ${2:pattern})\n ${3};;\n esac\nsnippet go \n while getopts \'${1:o}\' ${2:opts} \n do \n case $$2 in\n ${3:o0})\n ${4:#staments};;\n esac\n done\n# Set SCRIPT_DIR variable to directory script is located.\nsnippet sdir\n SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"\n# getopt\nsnippet getopt\n __ScriptVersion="${1:version}"\n\n #=== FUNCTION ================================================================\n # NAME: usage\n # DESCRIPTION: Display usage information.\n #===============================================================================\n function usage ()\n {\n cat <<- EOT\n\n Usage : $${0:0} [options] [--] \n\n Options: \n -h|help Display this message\n -v|version Display script version\n\n EOT\n } # ---------- end of function usage ----------\n\n #-----------------------------------------------------------------------\n # Handle command line arguments\n #-----------------------------------------------------------------------\n\n while getopts ":hv" opt\n do\n case $opt in\n\n h|help ) usage; exit 0 ;;\n\n v|version ) echo "$${0:0} -- Version $__ScriptVersion"; exit 0 ;;\n\n \\? ) echo -e "\\n Option does not exist : $OPTARG\\n"\n usage; exit 1 ;;\n\n esac # --- end of case ---\n done\n shift $(($OPTIND-1))\n\n',t.scope="sh"}) | iwdmb/cdnjs | ajax/libs/ace/1.2.3/snippets/sh.js | JavaScript | mit | 2,051 |
(function() {
CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
var prev = old && old != CodeMirror.Init;
if (val && !prev) {
cm.on("focus", onFocus);
cm.on("blur", onBlur);
cm.on("change", onChange);
onChange(cm);
} else if (!val && prev) {
cm.off("focus", onFocus);
cm.off("blur", onBlur);
cm.off("change", onChange);
clearPlaceholder(cm);
var wrapper = cm.getWrapperElement();
wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
}
if (val && !cm.hasFocus()) onBlur(cm);
});
function clearPlaceholder(cm) {
if (cm.state.placeholder) {
cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
cm.state.placeholder = null;
}
}
function setPlaceholder(cm) {
clearPlaceholder(cm);
var elt = cm.state.placeholder = document.createElement("pre");
elt.style.cssText = "height: 0; overflow: visible";
elt.className = "CodeMirror-placeholder";
elt.appendChild(document.createTextNode(cm.getOption("placeholder")));
cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
}
function onFocus(cm) {
clearPlaceholder(cm);
}
function onBlur(cm) {
if (isEmpty(cm)) setPlaceholder(cm);
}
function onChange(cm) {
var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
if (cm.hasFocus()) return;
if (empty) setPlaceholder(cm);
else clearPlaceholder(cm);
}
function isEmpty(cm) {
return (cm.lineCount() === 1) && (cm.getLine(0) === "");
}
})();
| visualjeff/cdnjs | ajax/libs/codemirror/3.17.0/addon/display/placeholder.js | JavaScript | mit | 1,695 |
window.FlashCanvasOptions=window.FlashCanvasOptions||{},webshims.$.extend(FlashCanvasOptions,{swfPath:webshims.cfg.basePath+"FlashCanvas/"}),window.ActiveXObject&&!window.CanvasRenderingContext2D&&function(i,j,z){function D(a){this.code=a,this.message=R[a]}function S(a){this.width=a}function v(a){this.id=a.C++}function k(a){this.G=a,this.id=a.C++}function m(a,b){this.canvas=a,this.B=b,this.d=b.id.slice(8),this.D(),this.C=0,this.f=this.u="";var c=this;setInterval(function(){0===o[c.d]&&c.e()},30)}function A(){if("complete"===j.readyState){j.detachEvent(E,A);for(var a=j.getElementsByTagName(r),b=0,c=a.length;c>b;++b)B.initElement(a[b])}}function F(){var a=event.srcElement,b=a.parentNode;a.blur(),b.focus()}function G(){var a=event.propertyName;if("width"===a||"height"===a){var b=event.srcElement,c=b[a],d=parseInt(c,10);(isNaN(d)||0>d)&&(d="width"===a?300:150),c===d?(b.style[a]=d+"px",b.getContext("2d").I(b.width,b.height)):b[a]=d}}function H(){i.detachEvent(I,H);for(var a in s){var b,c=s[a],d=c.firstChild;for(b in d)"function"==typeof d[b]&&(d[b]=l);for(b in c)"function"==typeof c[b]&&(c[b]=l);d.detachEvent(J,F),c.detachEvent(K,G)}i[L]=l,i[M]=l,i[N]=l,i[C]=l,i[O]=l}function T(){var a=j.getElementsByTagName("script"),a=a[a.length-1];return j.documentMode>=8?a.src:a.getAttribute("src",4)}function t(a){return(""+a).replace(/&/g,"&").replace(/</g,"<")}function U(a){return a.toLowerCase()}function h(a){throw new D(a)}function P(a){var b=parseInt(a.width,10),c=parseInt(a.height,10);(isNaN(b)||0>b)&&(b=300),(isNaN(c)||0>c)&&(c=150),a.width=b,a.height=c}var l=null,r="canvas",L="CanvasRenderingContext2D",M="CanvasGradient",N="CanvasPattern",C="FlashCanvas",O="G_vmlCanvasManager",J="onfocus",K="onpropertychange",E="onreadystatechange",I="onunload",w=((i[C+"Options"]||{}).swfPath||T().replace(/[^\/]+$/,""))+"flashcanvas.swf",e=new function(a){for(var b=0,c=a.length;c>b;b++)this[a[b]]=b}("toDataURL,save,restore,scale,rotate,translate,transform,setTransform,globalAlpha,globalCompositeOperation,strokeStyle,fillStyle,createLinearGradient,createRadialGradient,createPattern,lineWidth,lineCap,lineJoin,miterLimit,shadowOffsetX,shadowOffsetY,shadowBlur,shadowColor,clearRect,fillRect,strokeRect,beginPath,closePath,moveTo,lineTo,quadraticCurveTo,bezierCurveTo,arcTo,rect,arc,fill,stroke,clip,isPointInPath,font,textAlign,textBaseline,fillText,strokeText,measureText,drawImage,createImageData,getImageData,putImageData,addColorStop,direction,resize".split(",")),u={},p={},o={},x={},s={},y={};m.prototype={save:function(){this.b(),this.c(),this.n(),this.m(),this.z(),this.w(),this.F.push([this.g,this.h,this.A,this.v,this.k,this.i,this.j,this.l,this.q,this.r,this.o,this.p,this.f,this.s,this.t]),this.a.push(e.save)},restore:function(){var a=this.F;a.length&&(a=a.pop(),this.globalAlpha=a[0],this.globalCompositeOperation=a[1],this.strokeStyle=a[2],this.fillStyle=a[3],this.lineWidth=a[4],this.lineCap=a[5],this.lineJoin=a[6],this.miterLimit=a[7],this.shadowOffsetX=a[8],this.shadowOffsetY=a[9],this.shadowBlur=a[10],this.shadowColor=a[11],this.font=a[12],this.textAlign=a[13],this.textBaseline=a[14]),this.a.push(e.restore)},scale:function(a,b){this.a.push(e.scale,a,b)},rotate:function(a){this.a.push(e.rotate,a)},translate:function(a,b){this.a.push(e.translate,a,b)},transform:function(a,b,c,d,f,g){this.a.push(e.transform,a,b,c,d,f,g)},setTransform:function(a,b,c,d,f,g){this.a.push(e.setTransform,a,b,c,d,f,g)},b:function(){var a=this.a;this.g!==this.globalAlpha&&(this.g=this.globalAlpha,a.push(e.globalAlpha,this.g)),this.h!==this.globalCompositeOperation&&(this.h=this.globalCompositeOperation,a.push(e.globalCompositeOperation,this.h))},n:function(){if(this.A!==this.strokeStyle){var a=this.A=this.strokeStyle;if("string"!=typeof a){if(!(a instanceof k||a instanceof v))return;a=a.id}this.a.push(e.strokeStyle,a)}},m:function(){if(this.v!==this.fillStyle){var a=this.v=this.fillStyle;if("string"!=typeof a){if(!(a instanceof k||a instanceof v))return;a=a.id}this.a.push(e.fillStyle,a)}},createLinearGradient:function(a,b,c,d){return!(isFinite(a)&&isFinite(b)&&isFinite(c)&&isFinite(d)||!h(9)),this.a.push(e.createLinearGradient,a,b,c,d),new k(this)},createRadialGradient:function(a,b,c,d,f,g){return!(isFinite(a)&&isFinite(b)&&isFinite(c)&&isFinite(d)&&isFinite(f)&&isFinite(g)||!h(9)),(0>c||0>g)&&h(1),this.a.push(e.createRadialGradient,a,b,c,d,f,g),new k(this)},createPattern:function(a,b){a||h(17);var c,d=a.tagName,f=this.d;if(d)if(d=d.toLowerCase(),"img"===d)c=a.getAttribute("src",2);else{if(d===r||"video"===d)return;h(17)}else a.src?c=a.src:h(17);return"repeat"===b||"no-repeat"===b||"repeat-x"===b||"repeat-y"===b||""===b||b===l||h(12),this.a.push(e.createPattern,t(c),b),!p[f][c]&&u[f]&&(this.e(),++o[f],p[f][c]=!0),new v(this)},z:function(){var a=this.a;this.k!==this.lineWidth&&(this.k=this.lineWidth,a.push(e.lineWidth,this.k)),this.i!==this.lineCap&&(this.i=this.lineCap,a.push(e.lineCap,this.i)),this.j!==this.lineJoin&&(this.j=this.lineJoin,a.push(e.lineJoin,this.j)),this.l!==this.miterLimit&&(this.l=this.miterLimit,a.push(e.miterLimit,this.l))},c:function(){var a=this.a;this.q!==this.shadowOffsetX&&(this.q=this.shadowOffsetX,a.push(e.shadowOffsetX,this.q)),this.r!==this.shadowOffsetY&&(this.r=this.shadowOffsetY,a.push(e.shadowOffsetY,this.r)),this.o!==this.shadowBlur&&(this.o=this.shadowBlur,a.push(e.shadowBlur,this.o)),this.p!==this.shadowColor&&(this.p=this.shadowColor,a.push(e.shadowColor,this.p))},clearRect:function(a,b,c,d){this.a.push(e.clearRect,a,b,c,d)},fillRect:function(a,b,c,d){this.b(),this.c(),this.m(),this.a.push(e.fillRect,a,b,c,d)},strokeRect:function(a,b,c,d){this.b(),this.c(),this.n(),this.z(),this.a.push(e.strokeRect,a,b,c,d)},beginPath:function(){this.a.push(e.beginPath)},closePath:function(){this.a.push(e.closePath)},moveTo:function(a,b){this.a.push(e.moveTo,a,b)},lineTo:function(a,b){this.a.push(e.lineTo,a,b)},quadraticCurveTo:function(a,b,c,d){this.a.push(e.quadraticCurveTo,a,b,c,d)},bezierCurveTo:function(a,b,c,d,f,g){this.a.push(e.bezierCurveTo,a,b,c,d,f,g)},arcTo:function(a,b,c,d,f){0>f&&isFinite(f)&&h(1),this.a.push(e.arcTo,a,b,c,d,f)},rect:function(a,b,c,d){this.a.push(e.rect,a,b,c,d)},arc:function(a,b,c,d,f,g){0>c&&isFinite(c)&&h(1),this.a.push(e.arc,a,b,c,d,f,g?1:0)},fill:function(){this.b(),this.c(),this.m(),this.a.push(e.fill)},stroke:function(){this.b(),this.c(),this.n(),this.z(),this.a.push(e.stroke)},clip:function(){this.a.push(e.clip)},w:function(){var a=this.a;if(this.f!==this.font)try{var b=y[this.d];b.style.font=this.f=this.font;var c=b.currentStyle;a.push(e.font,[c.fontStyle,c.fontWeight,b.offsetHeight,c.fontFamily].join(" "))}catch(d){}this.s!==this.textAlign&&(this.s=this.textAlign,a.push(e.textAlign,this.s)),this.t!==this.textBaseline&&(this.t=this.textBaseline,a.push(e.textBaseline,this.t)),this.u!==this.canvas.currentStyle.direction&&(this.u=this.canvas.currentStyle.direction,a.push(e.direction,this.u))},fillText:function(a,b,c,d){this.b(),this.m(),this.c(),this.w(),this.a.push(e.fillText,t(a),b,c,d===z?1/0:d)},strokeText:function(a,b,c,d){this.b(),this.n(),this.c(),this.w(),this.a.push(e.strokeText,t(a),b,c,d===z?1/0:d)},measureText:function(a){var b=y[this.d];try{b.style.font=this.font}catch(c){}return b.innerText=(""+a).replace(/[ \n\f\r]/g," "),new S(b.offsetWidth)},drawImage:function(a,b,c,d,f,g,i,j,k){a||h(17);var l,m=a.tagName,n=arguments.length,q=this.d;if(m)if(m=m.toLowerCase(),"img"===m)l=a.getAttribute("src",2);else{if(m===r||"video"===m)return;h(17)}else a.src?l=a.src:h(17);if(this.b(),this.c(),l=t(l),3===n)this.a.push(e.drawImage,n,l,b,c);else if(5===n)this.a.push(e.drawImage,n,l,b,c,d,f);else{if(9!==n)return;(0===d||0===f)&&h(1),this.a.push(e.drawImage,n,l,b,c,d,f,g,i,j,k)}!p[q][l]&&u[q]&&(this.e(),++o[q],p[q][l]=!0)},loadImage:function(a,b,c){var d,f=a.tagName,g=this.d;f?"img"===f.toLowerCase()&&(d=a.getAttribute("src",2)):a.src&&(d=a.src),d&&!p[g][d]&&((b||c)&&(x[g][d]=[a,b,c]),this.a.push(e.drawImage,1,t(d)),u[g]&&(this.e(),++o[g],p[g][d]=!0))},D:function(){this.globalAlpha=this.g=1,this.globalCompositeOperation=this.h="source-over",this.fillStyle=this.v=this.strokeStyle=this.A="#000000",this.lineWidth=this.k=1,this.lineCap=this.i="butt",this.lineJoin=this.j="miter",this.miterLimit=this.l=10,this.shadowBlur=this.o=this.shadowOffsetY=this.r=this.shadowOffsetX=this.q=0,this.shadowColor=this.p="rgba(0, 0, 0, 0.0)",this.font=this.f="10px sans-serif",this.textAlign=this.s="start",this.textBaseline=this.t="alphabetic",this.a=[],this.F=[]},H:function(){var a=this.a;return this.a=[],a},e:function(){var a=this.H();return a.length>0?eval(this.B.CallFunction('<invoke name="executeCommand" returntype="javascript"><arguments><string>'+a.join("�")+"</string></arguments></invoke>")):void 0},I:function(a,b){this.e(),this.D(),a>0&&(this.B.width=a),b>0&&(this.B.height=b),this.a.push(e.resize,a,b)}},k.prototype={addColorStop:function(a,b){(isNaN(a)||0>a||a>1)&&h(1),this.G.a.push(e.addColorStop,this.id,a,b)}},D.prototype=Error();var R={1:"INDEX_SIZE_ERR",9:"NOT_SUPPORTED_ERR",11:"INVALID_STATE_ERR",12:"SYNTAX_ERR",17:"TYPE_MISMATCH_ERR",18:"SECURITY_ERR"},B={initElement:function(a){if(a.getContext)return a;var b=Math.random().toString(36).slice(2)||"0",c="external"+b;u[b]=!1,p[b]={},o[b]=1,x[b]={},P(a),a.innerHTML='<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="'+location.protocol+'//fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="100%" height="100%" id="'+c+'"><param name="allowScriptAccess" value="always"><param name="flashvars" value="id='+c+'"><param name="wmode" value="transparent"></object><span style="margin:0;padding:0;border:0;display:inline-block;position:static;height:1em;overflow:visible;white-space:nowrap"></span>',s[b]=a;var d=a.firstChild;y[b]=a.lastChild;var f=j.body.contains;if(f(a))d.movie=w;else var g=setInterval(function(){f(a)&&(clearInterval(g),d.movie=w)},0);"BackCompat"!==j.compatMode&&i.XMLHttpRequest||(y[b].style.overflow="hidden");var h=new m(a,d);return a.getContext=function(a){return"2d"===a?h:l},a.toDataURL=function(a,b){return"image/jpeg"===(""+a).replace(/[A-Z]+/g,U)?h.a.push(e.toDataURL,a,"number"==typeof b?b:""):h.a.push(e.toDataURL,a),h.e()},d.attachEvent(J,F),a},saveImage:function(a,b){a.firstChild.saveImage(b)},setOptions:function(){},trigger:function(a,b){s[a].fireEvent("on"+b)},unlock:function(a,b,c){var d,e,f;o[a]&&--o[a],b===z?(d=s[a],b=d.firstChild,P(d),e=d.width,c=d.height,d.style.width=e+"px",d.style.height=c+"px",e>0&&(b.width=e),c>0&&(b.height=c),b.resize(e,c),d.attachEvent(K,G),u[a]=!0,"function"==typeof d.onload&&setTimeout(function(){d.onload()},0)):(f=x[a][b])&&(e=f[0],c=f[1+c],delete x[a][b],"function"==typeof c&&c.call(e))}};if(j.createElement(r),j.createStyleSheet().cssText=r+"{display:inline-block;overflow:hidden;width:300px;height:150px}","complete"===j.readyState?A():j.attachEvent(E,A),i.attachEvent(I,H),0===w.indexOf(location.protocol+"//"+location.host+"/")){var Q=new ActiveXObject("Microsoft.XMLHTTP");Q.open("GET",w,!1),Q.send(l)}i[L]=m,i[M]=k,i[N]=v,i[C]=B,i[O]={init:function(){},init_:function(){},initElement:B.initElement},keep=[m.measureText,m.loadImage]}(window,document),function(a){webshims.addReady(function(b,c){b==a&&window.G_vmlCanvasManager&&G_vmlCanvasManager.init_&&G_vmlCanvasManager.init_(a),webshims.$("canvas",b).add(c.filter("canvas")).each(function(){var a=this.getContext;!a&&window.G_vmlCanvasManager&&G_vmlCanvasManager.initElement(this)})}),webshims.isReady("canvas",!0)}(document); | jessepollak/cdnjs | ajax/libs/webshim/1.14.6/minified/shims/FlashCanvas/flashcanvas.js | JavaScript | mit | 11,537 |
/**
* Easy to use Wizard library for AngularJS
* @version v0.4.2 - 2015-04-03 * @link https://github.com/mgonto/angular-wizard
* @author Martin Gontovnikas <martin@gon.to>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
function wizardButtonDirective(a){angular.module("mgo-angular-wizard").directive(a,function(){return{restrict:"A",replace:!1,require:"^wizard",link:function(b,c,d,e){c.on("click",function(c){c.preventDefault(),b.$apply(function(){b.$eval(d[a]),e[a.replace("wz","").toLowerCase()]()})})}}})}angular.module("templates-angularwizard",["step.html","wizard.html"]),angular.module("step.html",[]).run(["$templateCache",function(a){a.put("step.html",'<section ng-show="selected" ng-class="{current: selected, done: completed}" class="step" ng-transclude>\n</section>')}]),angular.module("wizard.html",[]).run(["$templateCache",function(a){a.put("wizard.html",'<div>\n <div class="steps" ng-transclude></div>\n <ul class="steps-indicator steps-{{steps.length}}" ng-if="!hideIndicators">\n <li ng-class="{default: !step.completed && !step.selected, current: step.selected && !step.completed, done: step.completed && !step.selected, editing: step.selected && step.completed}" ng-repeat="step in steps">\n <a ng-click="goTo(step)">{{step.title || step.wzTitle}}</a>\n </li>\n </ul>\n</div>\n')}]),angular.module("mgo-angular-wizard",["templates-angularwizard"]),angular.module("mgo-angular-wizard").directive("wzStep",function(){return{restrict:"EA",replace:!0,transclude:!0,scope:{wzTitle:"@",title:"@",canenter:"=",canexit:"="},require:"^wizard",templateUrl:function(a,b){return b.template||"step.html"},link:function(a,b,c,d){a.title=a.title||a.wzTitle,d.addStep(a)}}}),angular.module("mgo-angular-wizard").directive("wizard",function(){return{restrict:"EA",replace:!0,transclude:!0,scope:{currentStep:"=",onFinish:"&",hideIndicators:"=",editMode:"=",name:"@"},templateUrl:function(a,b){return b.template||"wizard.html"},controller:["$scope","$element","$log","WizardHandler",function(a,b,c,d){function e(){_.each(a.steps,function(a){a.selected=!1}),a.selectedStep=null}var f=!0;d.addWizard(a.name||d.defaultName,this),a.$on("$destroy",function(){d.removeWizard(a.name||d.defaultName)}),a.steps=[],a.context={},a.$watch("currentStep",function(b){if(b){var c=a.selectedStep.title||a.selectedStep.wzTitle;a.selectedStep&&c!==a.currentStep&&a.goTo(_.findWhere(a.steps,{title:a.currentStep}))}}),a.$watch("[editMode, steps.length]",function(){var b=a.editMode;_.isUndefined(b)||_.isNull(b)||b&&_.each(a.steps,function(a){a.completed=!0})},!0),this.addStep=function(b){a.steps.push(b),1===a.steps.length&&a.goTo(a.steps[0])},this.context=a.context,a.getStepNumber=function(b){return _.indexOf(a.steps,b)+1},a.goTo=function(b){if(f)e(),a.selectedStep=b,_.isUndefined(a.currentStep)||(a.currentStep=b.title||b.wzTitle),b.selected=!0,a.$emit("wizard:stepChanged",{step:b,index:_.indexOf(a.steps,b)}),f=!1;else{var c,d=!1,g=!1;if(a.currentStepNumber()>0?c=a.currentStepNumber()-1:0===a.currentStepNumber()&&(c=0),("undefined"==typeof a.steps[c].canexit||a.steps[c].canexit(a.context)===!0)&&(d=!0),a.getStepNumber(b)<a.currentStepNumber()&&(d=!0),(d&&void 0===b.canenter||d&&b.canenter(a.context)===!0)&&(g=!0),!d||!g)return;e(),a.selectedStep=b,_.isUndefined(a.currentStep)||(a.currentStep=b.title||b.wzTitle),b.selected=!0,a.$emit("wizard:stepChanged",{step:b,index:_.indexOf(a.steps,b)})}},a.currentStepNumber=function(){return _.indexOf(a.steps,a.selectedStep)+1},this.currentStepNumber=function(){return a.currentStepNumber()},this.next=function(b){var c=_.indexOf(a.steps,a.selectedStep);if(angular.isFunction(b)){if(!b())return;c===a.steps.length-1?this.finish():a.goTo(a.steps[c+1])}b||(a.selectedStep.completed=!0),c===a.steps.length-1?this.finish():a.goTo(a.steps[c+1])},this.goTo=function(b){var c;c=_.isNumber(b)?a.steps[b]:_.findWhere(a.steps,{title:b}),a.goTo(c)},this.finish=function(){a.onFinish&&a.onFinish()},this.cancel=this.previous=function(){var b=_.indexOf(a.steps,a.selectedStep);if(0===b)throw new Error("Can't go back. It's already in step 0");a.goTo(a.steps[b-1])}}]}}),wizardButtonDirective("wzNext"),wizardButtonDirective("wzPrevious"),wizardButtonDirective("wzFinish"),wizardButtonDirective("wzCancel"),angular.module("mgo-angular-wizard").factory("WizardHandler",function(){var a={},b={};return a.defaultName="defaultWizard",a.addWizard=function(a,c){b[a]=c},a.removeWizard=function(a){delete b[a]},a.wizard=function(c){var d=c;return c||(d=a.defaultName),b[d]},a}); | jessepollak/cdnjs | ajax/libs/angular-wizard/0.4.3/angular-wizard.min.js | JavaScript | mit | 4,549 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Form;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
/**
* @author Bernhard Schussek <bschussek@gmail.com>
*/
abstract class AbstractType implements FormTypeInterface
{
/**
* @var array
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3.
*/
private $extensions = array();
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
}
/**
* {@inheritdoc}
*/
public function buildView(FormView $view, FormInterface $form, array $options)
{
}
/**
* {@inheritdoc}
*/
public function finishView(FormView $view, FormInterface $form, array $options)
{
}
/**
* {@inheritdoc}
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$defaults = $this->getDefaultOptions(array());
$allowedTypes = $this->getAllowedOptionValues(array());
if (!empty($defaults)) {
trigger_error('getDefaultOptions() is deprecated since version 2.1 and will be removed in 2.3. Use setDefaultOptions() instead.', E_USER_DEPRECATED);
$resolver->setDefaults($defaults);
}
if (!empty($allowedTypes)) {
trigger_error('getAllowedOptionValues() is deprecated since version 2.1 and will be removed in 2.3. Use setDefaultOptions() instead.', E_USER_DEPRECATED);
$resolver->addAllowedValues($allowedTypes);
}
}
/**
* Returns the default options for this type.
*
* @param array $options Unsupported as of Symfony 2.1.
*
* @return array The default options
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3.
* Use {@link setDefaultOptions()} instead.
*/
public function getDefaultOptions(array $options)
{
return array();
}
/**
* Returns the allowed option values for each option (if any).
*
* @param array $options Unsupported as of Symfony 2.1.
*
* @return array The allowed option values
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3.
* Use {@link setDefaultOptions()} instead.
*/
public function getAllowedOptionValues(array $options)
{
return array();
}
/**
* {@inheritdoc}
*/
public function getParent()
{
return 'form';
}
/**
* Sets the extensions for this type.
*
* @param FormTypeExtensionInterface[] $extensions An array of FormTypeExtensionInterface
*
* @throws Exception\UnexpectedTypeException if any extension does not implement FormTypeExtensionInterface
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3.
*/
public function setExtensions(array $extensions)
{
trigger_error('setExtensions() is deprecated since version 2.1 and will be removed in 2.3.', E_USER_DEPRECATED);
$this->extensions = $extensions;
}
/**
* Returns the extensions associated with this type.
*
* @return FormTypeExtensionInterface[] An array of FormTypeExtensionInterface
*
* @deprecated Deprecated since version 2.1, to be removed in 2.3. Use
* {@link ResolvedFormTypeInterface::getTypeExtensions()} instead.
*/
public function getExtensions()
{
trigger_error('getExtensions() is deprecated since version 2.1 and will be removed in 2.3. Use ResolvedFormTypeInterface::getTypeExtensions instead.', E_USER_DEPRECATED);
return $this->extensions;
}
}
| elliot/symfony | src/Symfony/Component/Form/AbstractType.php | PHP | mit | 3,897 |
import baseOrderBy from './_baseOrderBy.js';
import isArray from './isArray.js';
/**
* This method is like `_.sortBy` except that it allows specifying the sort
* orders of the iteratees to sort by. If `orders` is unspecified, all values
* are sorted in ascending order. Otherwise, specify an order of "desc" for
* descending or "asc" for ascending sort order of corresponding values.
*
* @static
* @memberOf _
* @since 4.0.0
* @category Collection
* @param {Array|Object} collection The collection to iterate over.
* @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
* The iteratees to sort by.
* @param {string[]} [orders] The sort orders of `iteratees`.
* @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
* @returns {Array} Returns the new sorted array.
* @example
*
* var users = [
* { 'user': 'fred', 'age': 48 },
* { 'user': 'barney', 'age': 34 },
* { 'user': 'fred', 'age': 40 },
* { 'user': 'barney', 'age': 36 }
* ];
*
* // Sort by `user` in ascending order and by `age` in descending order.
* _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
* // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
*/
function orderBy(collection, iteratees, orders, guard) {
if (collection == null) {
return [];
}
if (!isArray(iteratees)) {
iteratees = iteratees == null ? [] : [iteratees];
}
orders = guard ? undefined : orders;
if (!isArray(orders)) {
orders = orders == null ? [] : [orders];
}
return baseOrderBy(collection, iteratees, orders);
}
export default orderBy;
| TheeSweeney/ComplexReactReduxMiddlewareReview | node_modules/lodash-es/orderBy.js | JavaScript | mit | 1,618 |
/*! UIkit 2.24.0 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
/* ========================================================================
Component: Slidenav
========================================================================== */
/*
* 1. Required for `a` elements
* 2. Dimension
* 3. Style
*/
.uk-slidenav {
/* 1 */
display: inline-block;
/* 2 */
box-sizing: border-box;
width: 60px;
height: 60px;
/* 3 */
line-height: 60px;
color: rgba(50, 50, 50, 0.4);
font-size: 60px;
text-align: center;
}
/*
* Hover
* 1. Apply hover style also to focus state
* 2. Remove default focus style
* 3. Required for `a` elements
* 4. Style
*/
.uk-slidenav:hover,
.uk-slidenav:focus {
/* 2 */
outline: none;
/* 3 */
text-decoration: none;
/* 4 */
color: rgba(50, 50, 50, 0.7);
cursor: pointer;
}
/* Active */
.uk-slidenav:active {
color: rgba(50, 50, 50, 0.9);
}
/*
* Icons
*/
.uk-slidenav-previous:before {
content: "\f104";
font-family: FontAwesome;
}
.uk-slidenav-next:before {
content: "\f105";
font-family: FontAwesome;
}
/* Sub-object: `uk-slidenav-position`
========================================================================== */
/*
* Create position context
*/
.uk-slidenav-position {
position: relative;
}
/*
* Center vertically
*/
.uk-slidenav-position .uk-slidenav {
display: none;
position: absolute;
top: 50%;
z-index: 1;
margin-top: -30px;
}
.uk-slidenav-position:hover .uk-slidenav {
display: block;
}
.uk-slidenav-position .uk-slidenav-previous {
left: 20px;
}
.uk-slidenav-position .uk-slidenav-next {
right: 20px;
}
/* Modifier: `uk-slidenav-contrast`
========================================================================== */
.uk-slidenav-contrast {
color: rgba(255, 255, 255, 0.5);
}
/*
* Hover
* 1. Apply hover style also to focus state
*/
.uk-slidenav-contrast:hover,
.uk-slidenav-contrast:focus {
color: rgba(255, 255, 255, 0.7);
}
/* Active */
.uk-slidenav-contrast:active {
color: rgba(255, 255, 255, 0.9);
}
| dlueth/cdnjs | ajax/libs/uikit/2.24.0/css/components/slidenav.almost-flat.css | CSS | mit | 2,043 |
/**
* Auxiliar utilities for UI Modules
* @module Ink.UI.Common_1
* @version 1
*/
Ink.createModule('Ink.UI.Common', '1', ['Ink.Dom.Element_1', 'Ink.Net.Ajax_1','Ink.Dom.Css_1','Ink.Dom.Selector_1','Ink.Util.Url_1'], function(InkElement, Ajax,Css,Selector,Url) {
'use strict';
var nothing = {} /* a marker, for reference comparison. */;
var keys = Object.keys || function (obj) {
var ret = [];
for (var k in obj) if (obj.hasOwnProperty(k)) {
ret.push(k);
}
return ret;
};
var es6WeakMapSupport = 'WeakMap' in window;
var instances = es6WeakMapSupport ? new WeakMap() : null;
var domRegistry = {
get: function get(el) {
return es6WeakMapSupport ?
instances.get(el) :
el.__InkInstances;
},
set: function set(el, thing) {
if (es6WeakMapSupport) {
instances.set(el, thing);
} else {
el.__InkInstances = thing;
}
}
};
/**
* @namespace Ink.UI.Common_1
*/
var Common = {
/**
* Supported Ink Layouts
*
* @property Layouts
* @type Object
* @readOnly
*/
Layouts: {
TINY: 'tiny',
SMALL: 'small',
MEDIUM: 'medium',
LARGE: 'large',
XLARGE: 'xlarge'
},
/**
* Checks if an item is a valid DOM Element.
*
* @method isDOMElement
* @static
* @param {Mixed} o The object to be checked.
* @return {Boolean} True if it's a valid DOM Element.
* @example
* var el = Ink.s('#element');
* if( Ink.UI.Common.isDOMElement( el ) === true ){
* // It is a DOM Element.
* } else {
* // It is NOT a DOM Element.
* }
*/
isDOMElement: InkElement.isDOMElement,
/**
* Checks if an item is a valid integer.
*
* @method isInteger
* @static
* @param {Mixed} n The value to be checked.
* @return {Boolean} True if it's a valid integer.
* @example
* var value = 1;
* if( Ink.UI.Common.isInteger( value ) === true ){
* // It is an integer.
* } else {
* // It is NOT an integer.
* }
*/
isInteger: function(n) {
return (typeof n === 'number' && n % 1 === 0);
},
/**
* Gets a DOM Element.
*
* @method elOrSelector
* @static
* @param {DOMElement|String} elOrSelector DOM Element or CSS Selector
* @param {String} fieldName The name of the field. Commonly used for debugging.
* @return {DOMElement} Returns the DOMElement passed or the first result of the CSS Selector. Otherwise it throws an exception.
* @example
* // In case there are several .myInput, it will retrieve the first found
* var el = Ink.UI.Common.elOrSelector('.myInput','My Input');
*/
elOrSelector: function(elOrSelector, fieldName) {
if (!this.isDOMElement(elOrSelector)) {
var t = Selector.select(elOrSelector);
if (t.length === 0) {
Ink.warn(fieldName + ' must either be a DOM Element or a selector expression!\nThe script element must also be after the DOM Element itself.');
return null;
}
return t[0];
}
return elOrSelector;
},
/**
* Alias for `elOrSelector` but returns an array of elements.
*
* @method elsOrSelector
*
* @static
* @param {DOMElement|String} elOrSelector DOM Element or CSS Selector
* @param {String} fieldName The name of the field. Commonly used for debugging.
* @return {DOMElement} Returns the DOMElement passed or the first result of the CSS Selector. Otherwise it throws an exception.
* @param {Boolean} required Flag to accept an empty array as output.
* @return {Array} The selected DOM Elements.
* @example
* var elements = Ink.UI.Common.elsOrSelector('input.my-inputs', 'My Input');
*/
elsOrSelector: function(elsOrSelector, fieldName, required) {
var ret;
if (typeof elsOrSelector === 'string') {
ret = Selector.select(elsOrSelector);
} else if (Common.isDOMElement(elsOrSelector)) {
ret = [elsOrSelector];
} else if (elsOrSelector && typeof elsOrSelector === 'object' && typeof elsOrSelector.length === 'number') {
ret = elsOrSelector;
}
if (ret && ret.length) {
return ret;
} else {
if (required) {
throw new TypeError(fieldName + ' must either be a DOM Element, an Array of elements, or a selector expression!\nThe script element must also be after the DOM Element itself.');
} else {
return [];
}
}
},
/**
* Gets options an object and element's metadata.
*
* The element's data attributes take precedence. Values from the element's data-atrributes are coerced into the required type.
*
* @method options
*
* @param {Object} [fieldId] Name to be used in debugging features.
* @param {Object} defaults Object with the options' types and defaults.
* @param {Object} overrides Options to override the defaults. Usually passed when instantiating an UI module.
* @param {DOMElement} [element] Element with data-attributes
*
* @example
*
* this._options = Ink.UI.Common.options('MyComponent', {
* 'anobject': ['Object', null], // Defaults to null
* 'target': ['Element', null],
* 'stuff': ['Number', 0.1],
* 'stuff2': ['Integer', 0],
* 'doKickFlip': ['Boolean', false],
* 'targets': ['Elements'], // Required option since no default was given
* 'onClick': ['Function', null]
* }, options || {}, elm)
*
* @example
*
* ### Note about booleans
*
* Here is how options are read from the markup
* data-attributes, for several values`data-a-boolean`.
*
* Options considered true:
*
* - `data-a-boolean="true"`
* - (Every other value which is not on the list below.)
*
* Options considered false:
*
* - `data-a-boolean="false"`
* - `data-a-boolean=""`
* - `data-a-boolean`
*
* Options which go to default:
*
* - (no attribute). When `data-a-boolean` is ommitted, the
* option is not considered true nor false, and as such
* defaults to what is in the `defaults` argument.
*
**/
options: function (fieldId, defaults, overrides, element) {
if (typeof fieldId !== 'string') {
element = overrides;
overrides = defaults;
defaults = fieldId;
fieldId = '';
}
overrides = overrides || {};
var out = {};
var dataAttrs = element ? InkElement.data(element) : {};
var fromDataAttrs;
var type;
var lType;
var defaultVal;
var invalidStr = function (str) {
if (fieldId) { str = fieldId + ': "' + ('' + str).replace(/"/, '\\"') + '"'; }
return str;
};
var quote = function (str) {
return '"' + ('' + str).replace(/"/, '\\"') + '"';
};
var invalidThrow = function (str) {
throw new Error(invalidStr(str));
};
var invalid = function (str) {
Ink.error(invalidStr(str) + '. Ignoring option.');
};
function optionValue(key) {
type = defaults[key][0];
lType = type.toLowerCase();
defaultVal = defaults[key].length === 2 ? defaults[key][1] : nothing;
if (!type) {
invalidThrow('Ink.UI.Common.options: Always specify a type!');
}
if (!(lType in Common._coerce_funcs)) {
invalidThrow('Ink.UI.Common.options: ' + defaults[key][0] + ' is not a valid type. Use one of ' + keys(Common._coerce_funcs).join(', '));
}
if (!defaults[key].length || defaults[key].length > 2) {
invalidThrow('the "defaults" argument must be an object mapping option names to [typestring, optional] arrays.');
}
if (key in dataAttrs) {
fromDataAttrs = Common._coerce_from_string(lType, dataAttrs[key], key, fieldId);
// (above can return `nothing`)
} else {
fromDataAttrs = nothing;
}
if (fromDataAttrs !== nothing) {
if (!Common._options_validate(fromDataAttrs, lType)) {
invalid('(' + key + ' option) Invalid ' + lType + ' ' + quote(fromDataAttrs));
return defaultVal;
} else {
return fromDataAttrs;
}
} else if (key in overrides) {
return overrides[key];
} else if (defaultVal !== nothing) {
return defaultVal;
} else {
invalidThrow('Option ' + key + ' is required!');
}
}
for (var key in defaults) {
if (defaults.hasOwnProperty(key)) {
out[key] = optionValue(key);
}
}
return out;
},
_coerce_from_string: function (type, val, paramName, fieldId) {
if (type in Common._coerce_funcs) {
return Common._coerce_funcs[type](val, paramName, fieldId);
} else {
return val;
}
},
_options_validate: function (val, type) {
if (type in Common._options_validate_types) {
return Common._options_validate_types[type].call(Common, val);
} else {
// 'object' options cannot be passed through data-attributes.
// Json you say? Not any good to embed in HTML.
return false;
}
},
_coerce_funcs: (function () {
var ret = {
element: function (val) {
return Common.elOrSelector(val, '');
},
elements: function (val) {
return Common.elsOrSelector(val, '', false /*not required, so don't throw an exception now*/);
},
object: function (val) { return val; },
number: function (val) { return parseFloat(val); },
'boolean': function (val) {
return !(val === 'false' || val === '' || val === null);
},
string: function (val) { return val; },
'function': function (val, paramName, fieldId) {
Ink.error(fieldId + ': You cannot specify the option "' + paramName + '" through data-attributes because it\'s a function');
return nothing;
}
};
ret['float'] = ret.integer = ret.number;
return ret;
}()),
_options_validate_types: (function () {
var types = {
string: function (val) {
return typeof val === 'string';
},
number: function (val) {
return typeof val === 'number' && !isNaN(val) && isFinite(val);
},
integer: function (val) {
return val === Math.round(val);
},
element: function (val) {
return Common.isDOMElement(val);
},
elements: function (val) {
return val && typeof val === 'object' && typeof val.length === 'number' && val.length;
},
'boolean': function (val) {
return typeof val === 'boolean';
},
object: function () { return true; }
};
types['float'] = types.number;
return types;
}()),
/**
* Deep copy (clone) an object.
* Note: The object cannot have referece loops.
*
* @method clone
* @static
* @param {Object} o The object to be cloned/copied.
* @return {Object} Returns the result of the clone/copy.
* @example
* var originalObj = {
* key1: 'value1',
* key2: 'value2',
* key3: 'value3'
* };
* var cloneObj = Ink.UI.Common.clone( originalObj );
*/
clone: function(o) {
try {
return JSON.parse( JSON.stringify(o) );
} catch (ex) {
throw new Error('Given object cannot have loops!');
}
},
/**
* Gets an element's one-base index relative to its parent.
*
* @method childIndex
* @static
* @param {DOMElement} childEl Valid DOM Element.
* @return {Number} Numerical position of an element relatively to its parent.
* @example
* <!-- Imagine the following HTML: -->
* <ul>
* <li>One</li>
* <li>Two</li>
* <li id="test">Three</li>
* <li>Four</li>
* </ul>
*
* <script>
* var testLi = Ink.s('#test');
* Ink.UI.Common.childIndex( testLi ); // Returned value: 3
* </script>
*/
childIndex: function(childEl) {
if( Common.isDOMElement(childEl) ){
var els = Selector.select('> *', childEl.parentNode);
for (var i = 0, f = els.length; i < f; ++i) {
if (els[i] === childEl) {
return i;
}
}
}
throw 'not found!';
},
/**
* AJAX JSON request shortcut method
* It provides a more convenient way to do an AJAX request and expect a JSON response.It also offers a callback option, as third parameter, for better async handling.
*
* @method ajaxJSON
* @static
* @async
* @param {String} endpoint Valid URL to be used as target by the request.
* @param {Object} params This field is used in the thrown Exception to identify the parameter.
* @param {Function} cb Callback for the request.
* @example
* // In case there are several .myInput, it will retrieve the first found
* var el = Ink.UI.Common.elOrSelector('.myInput','My Input');
*/
ajaxJSON: function(endpoint, params, cb) {
new Ajax(
endpoint,
{
evalJS: 'force',
method: 'POST',
parameters: params,
onSuccess: function( r) {
try {
r = r.responseJSON;
if (r.status !== 'ok') {
throw 'server error: ' + r.message;
}
cb(null, r);
} catch (ex) {
cb(ex);
}
},
onFailure: function() {
cb('communication failure');
}
}
);
},
/**
* Gets the current Ink layout.
*
* @method currentLayout
* @static
* @return {String} A string representation of the current layout name.
* @example
* var inkLayout = Ink.UI.Common.currentLayout();
* if (inkLayout === 'small') {
* // ...
* }
*/
currentLayout: function() {
var i, f, k, v, el, detectorEl = Selector.select('#ink-layout-detector')[0];
if (!detectorEl) {
detectorEl = document.createElement('div');
detectorEl.id = 'ink-layout-detector';
for (k in this.Layouts) {
if (this.Layouts.hasOwnProperty(k)) {
v = this.Layouts[k];
el = document.createElement('div');
el.className = 'show-' + v + ' hide-all';
el.setAttribute('data-ink-layout', v);
detectorEl.appendChild(el);
}
}
document.body.appendChild(detectorEl);
}
for (i = 0, f = detectorEl.children.length; i < f; ++i) {
el = detectorEl.children[i];
if (Css.getStyle(el, 'display') === 'block') {
return el.getAttribute('data-ink-layout');
}
}
return 'large';
},
/**
* Sets the location's hash (window.location.hash).
*
* @method hashSet
* @static
* @param {Object} o Object with the info to be placed in the location's hash.
* @example
* // It will set the location's hash like: <url>#key1=value1&key2=value2&key3=value3
* Ink.UI.Common.hashSet({
* key1: 'value1',
* key2: 'value2',
* key3: 'value3'
* });
*/
hashSet: function(o) {
if (typeof o !== 'object') { throw new TypeError('o should be an object!'); }
var hashParams = Url.getAnchorString();
hashParams = Ink.extendObj(hashParams, o);
window.location.hash = Url.genQueryString('', hashParams).substring(1);
},
/**
* Removes children nodes from a given object.
* This method was initially created to help solve a problem in Internet Explorer(s) that occurred when trying to set the innerHTML of some specific elements like 'table'.
*
* @method cleanChildren
* @static
* @param {DOMElement} parentEl Valid DOM Element
* @example
* <!-- Imagine the following HTML: -->
* <ul id="myUl">
* <li>One</li>
* <li>Two</li>
* <li>Three</li>
* <li>Four</li>
* </ul>
*
* <script>
* Ink.UI.Common.cleanChildren( Ink.s( '#myUl' ) );
* </script>
*
* <!-- After running it, the HTML changes to: -->
* <ul id="myUl"></ul>
*/
cleanChildren: function(parentEl) {
if( !Common.isDOMElement(parentEl) ){
throw 'Please provide a valid DOMElement';
}
var prevEl, el = parentEl.lastChild;
while (el) {
prevEl = el.previousSibling;
parentEl.removeChild(el);
el = prevEl;
}
},
/**
* Stores the id and/or classes of an element in an object.
*
* @method storeIdAndClasses
* @static
* @param {DOMElement} fromEl Valid DOM Element to get the id and classes from.
* @param {Object} inObj Object where the id and classes will be saved.
* @example
* <div id="myDiv" class="aClass"></div>
*
* <script>
* var storageObj = {};
* Ink.UI.Common.storeIdAndClasses( Ink.s('#myDiv'), storageObj );
* // storageObj changes to:
* {
* _id: 'myDiv',
* _classes: 'aClass'
* }
* </script>
*/
storeIdAndClasses: function(fromEl, inObj) {
if( !Common.isDOMElement(fromEl) ){
throw 'Please provide a valid DOMElement as first parameter';
}
var id = fromEl.id;
if (id) {
inObj._id = id;
}
var classes = fromEl.className;
if (classes) {
inObj._classes = classes;
}
},
/**
* Sets the id and className properties of an element based
*
* @method restoreIdAndClasses
* @static
* @param {DOMElement} toEl Valid DOM Element to set the id and classes on.
* @param {Object} inObj Object where the id and classes to be set are. This method uses the same format as the one given in `storeIdAndClasses`
* @example
* <div></div>
*
* <script>
* var storageObj = {
* _id: 'myDiv',
* _classes: 'aClass'
* };
*
* Ink.UI.Common.storeIdAndClasses( Ink.s('div'), storageObj );
* </script>
*
* <!-- After the code runs the div element changes to: -->
* <div id="myDiv" class="aClass"></div>
*/
restoreIdAndClasses: function(toEl, inObj) {
if( !Common.isDOMElement(toEl) ){
throw 'Please provide a valid DOMElement as first parameter';
}
if (inObj._id && toEl.id !== inObj._id) {
toEl.id = inObj._id;
}
if (inObj._classes && toEl.className.indexOf(inObj._classes) === -1) {
if (toEl.className) { toEl.className += ' ' + inObj._classes; }
else { toEl.className = inObj._classes; }
}
if (inObj._instanceId && !toEl.getAttribute('data-instance')) {
toEl.setAttribute('data-instance', inObj._instanceId);
}
},
_warnDoubleInstantiation: function (elm, newInstance) {
var instances = Common.getInstance(elm);
if (getName(newInstance) === '') { return; }
if (!instances) { return; }
var nameWithoutVersion = getName(newInstance);
if (!nameWithoutVersion) { return; }
for (var i = 0, len = instances.length; i < len; i++) {
if (nameWithoutVersion === getName(instances[i])) {
// Yes, I am using + to concatenate and , to split
// arguments.
//
// Elements can't be concatenated with strings, but if
// they are passed in an argument, modern debuggers will
// pretty-print them and make it easy to find them in the
// element inspector.
//
// On the other hand, if strings are passed as different
// arguments, they get pretty printed. And the pretty
// print of a string has quotes around it.
//
// If some day people find out that strings are not
// just text and they start preserving contextual
// information, then by all means change this to a
// regular concatenation.
//
// But they won't. So don't change this.
Ink.warn('Creating more than one ' + nameWithoutVersion + '.',
'(Was creating a ' + nameWithoutVersion + ' on:', elm, ').');
return false;
}
}
function getName(thing) {
return ((thing.constructor && (thing.constructor._name)) ||
thing._name ||
'').replace(/_.*?$/, '');
}
return true;
},
/**
* Saves a component's instance reference for later retrieval.
*
* @method registerInstance
* @static
* @param {Object} inst Object that holds the instance.
* @param {DOMElement} el DOM Element to associate with the object.
*/
registerInstance: function(inst, el) {
if (!inst) { return; }
if (!Common.isDOMElement(el)) { throw new TypeError('Ink.UI.Common.registerInstance: The element passed in is not a DOM element!'); }
// [todo] this belongs in the BaseUIComponent's initialization
if (Common._warnDoubleInstantiation(el, inst) === false) {
return false;
}
var instances = domRegistry.get(el);
if (!instances) {
instances = [];
domRegistry.set(el, instances);
}
instances.push(inst);
return true;
},
/**
* Deletes an instance with a given id.
*
* @method unregisterInstance
* @static
* @param {String} id Id of the instance to be destroyed.
*/
unregisterInstance: function(inst) {
if (!inst || !inst._element) { return; }
var instances = domRegistry.get(inst._element);
for (var i = 0, len = instances.length; i < len; i++) {
if (instances[i] === inst) {
instances.splice(i, 1);
}
}
},
/**
* Gets an UI instance from an element or instance id.
*
* @method getInstance
* @static
* @param {String|DOMElement} el DOM Element from which we want the instances.
* @return {Object|Array} Returns an instance or a collection of instances.
*/
getInstance: function(el, UIComponent) {
el = Common.elOrSelector(el);
var instances = domRegistry.get(el);
if (!instances) {
instances = [];
}
if (typeof UIComponent !== 'function') {
return instances;
}
for (var i = 0, len = instances.length; i < len; i++) {
if (instances[i] instanceof UIComponent) {
return instances[i];
}
}
return null;
},
/**
* Gets an instance based on a selector.
*
* @method getInstanceFromSelector
* @static
* @param {String} selector CSS selector to get the instances from.
* @return {Object|Array} Returns an instance or a collection of instances.
*/
getInstanceFromSelector: function(selector) {
return Common.getInstance(Common.elOrSelector(selector));
},
/**
* Gets all the instance ids
*
* @method getInstanceIds
* @static
* @return {Array} Collection of instance ids
*/
getInstanceIds: function() {
var res = [];
for (var id in instances) {
if (instances.hasOwnProperty(id)) {
res.push( id );
}
}
return res;
},
/**
* Gets all the instances
*
* @method getInstances
* @static
* @return {Array} Collection of existing instances.
*/
getInstances: function() {
var res = [];
for (var id in instances) {
if (instances.hasOwnProperty(id)) {
res.push( instances[id] );
}
}
return res;
},
/**
* Boilerplate method to destroy a component.
* Components should copy this method as its destroy method and modify it.
*
* @method destroyComponent
* @static
*/
destroyComponent: function() {
Common.unregisterInstance(this);
this._element.parentNode.removeChild(this._element);
}
};
/**
* Ink UI Base Class
**/
function warnStub() {
/* jshint validthis: true */
if (!this || this === window || typeof this.constructor !== 'function') { return; }
Ink.warn('You called a method on an incorrectly instantiated ' + this.constructor._name + ' component. Check the warnings above to see what went wrong.');
}
function stub(prototype, obj) {
for (var k in prototype) if (prototype.hasOwnProperty(k)) {
if (k === 'constructor') { continue; }
if (typeof obj[k] === 'function') {
obj[k] = warnStub;
}
}
}
/**
* Ink UI Base Class
*
* You don't use this class directly, or inherit from it directly.
*
* See createUIComponent() (in this module) for how to create a UI component and inherit from this. It's not plain old JS inheritance, for several reasons.
*
* @class Ink.UI.Common.BaseUIComponent
* @constructor
*
* @param element
* @param options
**/
function BaseUIComponent(element, options) {
var constructor = this.constructor;
var _name = constructor._name;
if (!this || this === window) {
throw new Error('Use "new InkComponent()" instead of "InkComponent()"');
}
if (this && !(this instanceof BaseUIComponent)) {
throw new Error('You forgot to call Ink.UI.Common.createUIComponent() on this module!');
}
if (!element && !constructor._componentOptions.elementIsOptional) {
Ink.error(new Error(_name + ': You need to pass an element or a selector as the first argument to "new ' + _name + '()"'));
return;
} else {
this._element = Common.elsOrSelector(element,
_name + ': An element with the selector "' + element + '" was not found!')[0];
}
if (!this._element && !constructor._componentOptions.elementIsOptional) {
isValidInstance = false;
Ink.error(new Error(element + ' does not match an element on the page. You need to pass a valid selector to "new ' + _name + '".'));
}
// TODO Change Common.options's signature? the below looks better, more manageable
// var options = Common.options({
// element: this._element,
// modName: constructor._name,
// options: constructor._optionDefinition,
// defaults: constructor._globalDefaults
// });
this._options = Common.options(_name, constructor._optionDefinition, options, this._element);
var isValidInstance = BaseUIComponent._validateInstance(this) === true;
if (isValidInstance && typeof this._init === 'function') {
try {
this._init.apply(this, arguments);
} catch(e) {
isValidInstance = false;
Ink.error(e);
}
}
if (!isValidInstance) {
BaseUIComponent._stubInstance(this, constructor, _name);
} else if (this._element) {
Common.registerInstance(this, this._element);
}
}
/**
* Calls the `instance`'s _validate() method so it can validate itself.
*
* Returns false if the method exists, was called, but no Error was returned or thrown.
*
* @method _validateInstance
* @private
*/
BaseUIComponent._validateInstance = function (instance) {
var err;
if (typeof instance._validate !== 'function') { return true; }
try {
err = instance._validate();
} catch (e) {
err = e;
}
if (err instanceof Error) {
instance._validationError = err;
return false;
}
return true;
};
/**
* Replaces every method in the instance with stub functions which just call Ink.warn().
*
* This avoids breaking the page when there are errors.
*
* @method _stubInstance
* @param instance
* @param constructor
* @param name
* @private
*/
BaseUIComponent._stubInstance = function (instance, constructor, name) {
stub(constructor.prototype, instance);
stub(BaseUIComponent.prototype, instance);
Ink.warn(name + ' was not correctly created. ' + (instance._validationError || ''));
};
// TODO BaseUIComponent.setGlobalOptions = function () {}
// TODO BaseUIComponent.createMany = function (selector) {}
BaseUIComponent.getInstance = function (elOrSelector) {
elOrSelector = Common.elOrSelector(elOrSelector);
return Common.getInstance(elOrSelector, this /* get instance by constructor */);
};
Ink.extendObj(BaseUIComponent.prototype, {
/**
* Get an UI component's option's value.
*
* @method getOption
* @param name
*
* @return The option value, or undefined if nothing is found.
*
* @example
*
* var myUIComponent = new Modal('#element', { trigger: '#trigger' }); // or anything else inheriting BaseUIComponent
* myUIComponent.getOption('trigger'); // -> The trigger element (not the selector string, mind you)
*
**/
getOption: function (name) {
if (this.constructor && !(name in this.constructor._optionDefinition)) {
Ink.error('"' + name + '" is not an option for ' + this.constructor._name);
return undefined;
}
return this._options[name];
},
/**
* Sets an option's value
*
* @method getOption
* @param name
* @param value
*
* @example
*
* var myUIComponent = new Modal(...);
* myUIComponent.setOption('trigger', '#some-element');
**/
setOption: function (name, value) {
if (this.constructor && !(name in this.constructor._optionDefinition)) {
Ink.error('"' + name + ' is not an option for ' + this.constructor._name);
return;
}
this._options[name] = value;
},
/**
* Get the element associated with an UI component (IE the one you used in the constructor)
*
* @method getElement
* @return {Element} The component's element.
*
* @example
* var myUIComponent = new Modal('#element'); // or anything else inheriting BaseUIComponent
* myUIComponent.getElement(); // -> The '#element' (not the selector string, mind you).
*
**/
getElement: function () {
return this._element;
}
});
Common.BaseUIComponent = BaseUIComponent;
/**
* @method createUIComponent
* @param theConstructor UI component constructor. It should have an _init function in its prototype, an _optionDefinition object, and a _name property indicating its name.
* @param options
* @param [options.elementIsOptional=false] Whether the element argument is optional (For example, when the component might work on existing markup or create its own).
**/
Common.createUIComponent = function createUIComponent(theConstructor, options) {
theConstructor._componentOptions = options || {};
function assert(test, msg) {
if (!test) {
throw new Error('Ink.UI_1.createUIComponent: ' + msg);
}
}
function assertProp(prop, propType, message) {
var propVal = theConstructor[prop];
// Check that the property was passed
assert(typeof propVal !== 'undefined',
theConstructor + ' doesn\'t have a "' + prop + '" property. ' + message);
// Check that its type is correct
assert(propType && typeof propVal === propType,
'typeof ' + theConstructor + '.' + prop + ' is not "' + propType + '". ' + message);
}
assert(typeof theConstructor === 'function',
'constructor argument is not a function!');
assertProp('_name', 'string', 'This property is used for error ' +
'messages. Set it to the full module path and version (Ink.My.Module_1).');
assertProp('_optionDefinition', 'object', 'This property contains the ' +
'option names, types and defaults. See Ink.UI.Common.options() for reference.');
// Extend the instance methods and props
var _oldProto = theConstructor.prototype;
if (typeof Object.create === 'function') {
theConstructor.prototype = Object.create(BaseUIComponent.prototype);
} else {
theConstructor.prototype = (function hideF() {
function F() {}
F.prototype = BaseUIComponent.prototype;
return new F();
}());
}
Ink.extendObj(theConstructor.prototype, _oldProto);
theConstructor.prototype.constructor = theConstructor;
// Extend static methods
Ink.extendObj(theConstructor, BaseUIComponent);
};
return Common;
});
| kave/cdnjs | ajax/libs/ink/3.0.5/js/ink.common.js | JavaScript | mit | 38,459 |
.dropzone,.dropzone *,.dropzone-previews,.dropzone-previews *{-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.dropzone{position:relative;border:1px solid rgba(0,0,0,0.08);background:rgba(0,0,0,0.02);padding:1em}.dropzone.dz-clickable{cursor:pointer}.dropzone.dz-clickable .dz-message,.dropzone.dz-clickable .dz-message span{cursor:pointer}.dropzone.dz-clickable *{cursor:default}.dropzone .dz-message{opacity:1;-ms-filter:none;filter:none}.dropzone.dz-drag-hover{border-color:rgba(0,0,0,0.15);background:rgba(0,0,0,0.04)}.dropzone.dz-started .dz-message{display:none}.dropzone .dz-preview,.dropzone-previews .dz-preview{background:rgba(255,255,255,0.8);position:relative;display:inline-block;margin:17px;vertical-align:top;border:1px solid #acacac;padding:6px 6px 6px 6px}.dropzone .dz-preview.dz-file-preview [data-dz-thumbnail],.dropzone-previews .dz-preview.dz-file-preview [data-dz-thumbnail]{display:none}.dropzone .dz-preview .dz-details,.dropzone-previews .dz-preview .dz-details{width:100px;height:100px;position:relative;background:#ebebeb;padding:5px;margin-bottom:22px}.dropzone .dz-preview .dz-details .dz-filename,.dropzone-previews .dz-preview .dz-details .dz-filename{overflow:hidden;height:100%}.dropzone .dz-preview .dz-details img,.dropzone-previews .dz-preview .dz-details img{position:absolute;top:0;left:0;width:100px;height:100px}.dropzone .dz-preview .dz-details .dz-size,.dropzone-previews .dz-preview .dz-details .dz-size{position:absolute;bottom:-28px;left:3px;height:28px;line-height:28px}.dropzone .dz-preview.dz-error .dz-error-mark,.dropzone-previews .dz-preview.dz-error .dz-error-mark{display:block}.dropzone .dz-preview.dz-success .dz-success-mark,.dropzone-previews .dz-preview.dz-success .dz-success-mark{display:block}.dropzone .dz-preview:hover .dz-details img,.dropzone-previews .dz-preview:hover .dz-details img{display:none}.dropzone .dz-preview .dz-success-mark,.dropzone-previews .dz-preview .dz-success-mark,.dropzone .dz-preview .dz-error-mark,.dropzone-previews .dz-preview .dz-error-mark{display:none;position:absolute;width:40px;height:40px;font-size:30px;text-align:center;right:-10px;top:-10px}.dropzone .dz-preview .dz-success-mark,.dropzone-previews .dz-preview .dz-success-mark{color:#8cc657}.dropzone .dz-preview .dz-error-mark,.dropzone-previews .dz-preview .dz-error-mark{color:#ee162d}.dropzone .dz-preview .dz-progress,.dropzone-previews .dz-preview .dz-progress{position:absolute;top:100px;left:6px;right:6px;height:6px;background:#d7d7d7;display:none}.dropzone .dz-preview .dz-progress .dz-upload,.dropzone-previews .dz-preview .dz-progress .dz-upload{position:absolute;top:0;bottom:0;left:0;width:0;background-color:#8cc657}.dropzone .dz-preview.dz-processing .dz-progress,.dropzone-previews .dz-preview.dz-processing .dz-progress{display:block}.dropzone .dz-preview .dz-error-message,.dropzone-previews .dz-preview .dz-error-message{display:none;position:absolute;top:-5px;left:-20px;background:rgba(245,245,245,0.8);padding:8px 10px;color:#800;min-width:140px;max-width:500px;z-index:500}.dropzone .dz-preview:hover.dz-error .dz-error-message,.dropzone-previews .dz-preview:hover.dz-error .dz-error-message{display:block} | ahocevar/cdnjs | ajax/libs/dropzone/3.7.1/css/basic.min.css | CSS | mit | 3,215 |
// moment.js language configuration
// language : latvian (lv)
// author : Kristaps Karlsons : https://github.com/skakri
var units = {
'mm': 'minūti_minūtes_minūte_minūtes',
'hh': 'stundu_stundas_stunda_stundas',
'dd': 'dienu_dienas_diena_dienas',
'MM': 'mēnesi_mēnešus_mēnesis_mēneši',
'yy': 'gadu_gadus_gads_gadi'
};
function format(word, number, withoutSuffix) {
var forms = word.split('_');
if (withoutSuffix) {
return number % 10 === 1 && number !== 11 ? forms[2] : forms[3];
} else {
return number % 10 === 1 && number !== 11 ? forms[0] : forms[1];
}
}
function relativeTimeWithPlural(number, withoutSuffix, key) {
return number + ' ' + format(units[key], number, withoutSuffix);
}
require('../moment').lang('lv', {
months : "janvāris_februāris_marts_aprīlis_maijs_jūnijs_jūlijs_augusts_septembris_oktobris_novembris_decembris".split("_"),
monthsShort : "jan_feb_mar_apr_mai_jūn_jūl_aug_sep_okt_nov_dec".split("_"),
weekdays : "svētdiena_pirmdiena_otrdiena_trešdiena_ceturtdiena_piektdiena_sestdiena".split("_"),
weekdaysShort : "Sv_P_O_T_C_Pk_S".split("_"),
weekdaysMin : "Sv_P_O_T_C_Pk_S".split("_"),
longDateFormat : {
LT : "HH:mm",
L : "DD.MM.YYYY",
LL : "YYYY. [gada] D. MMMM",
LLL : "YYYY. [gada] D. MMMM, LT",
LLLL : "YYYY. [gada] D. MMMM, dddd, LT"
},
calendar : {
sameDay : '[Šodien pulksten] LT',
nextDay : '[Rīt pulksten] LT',
nextWeek : 'dddd [pulksten] LT',
lastDay : '[Vakar pulksten] LT',
lastWeek : '[Pagājušā] dddd [pulksten] LT',
sameElse : 'L'
},
relativeTime : {
future : "%s vēlāk",
past : "%s agrāk",
s : "dažas sekundes",
m : "minūti",
mm : relativeTimeWithPlural,
h : "stundu",
hh : relativeTimeWithPlural,
d : "dienu",
dd : relativeTimeWithPlural,
M : "mēnesi",
MM : relativeTimeWithPlural,
y : "gadu",
yy : relativeTimeWithPlural
},
ordinal : '%d.',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
| pwnall/cdnjs | ajax/libs/moment.js/2.1.0/lang/lv.js | JavaScript | mit | 2,274 |
.jstree-node,.jstree-children,.jstree-container-ul{display:block;margin:0;padding:0;list-style-type:none;list-style-image:none}.jstree-node{white-space:nowrap}.jstree-anchor{display:inline-block;color:#000;white-space:nowrap;padding:0 4px 0 1px;margin:0;vertical-align:top}.jstree-anchor:focus{outline:0}.jstree-anchor,.jstree-anchor:link,.jstree-anchor:visited,.jstree-anchor:hover,.jstree-anchor:active{text-decoration:none;color:inherit}.jstree-icon{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-icon:empty{display:inline-block;text-decoration:none;margin:0;padding:0;vertical-align:top;text-align:center}.jstree-ocl{cursor:pointer}.jstree-leaf>.jstree-ocl{cursor:default}.jstree .jstree-open>.jstree-children{display:block}.jstree .jstree-closed>.jstree-children,.jstree .jstree-leaf>.jstree-children{display:none}.jstree-anchor>.jstree-themeicon{margin-right:2px}.jstree-no-icons .jstree-themeicon,.jstree-anchor>.jstree-themeicon-hidden{display:none}.jstree-rtl .jstree-anchor{padding:0 1px 0 4px}.jstree-rtl .jstree-anchor>.jstree-themeicon{margin-left:2px;margin-right:0}.jstree-rtl .jstree-node{margin-left:0}.jstree-rtl .jstree-container-ul>.jstree-node{margin-right:0}.jstree-wholerow-ul{position:relative;display:inline-block;min-width:100%}.jstree-wholerow-ul .jstree-leaf>.jstree-ocl{cursor:pointer}.jstree-wholerow-ul .jstree-anchor,.jstree-wholerow-ul .jstree-icon{position:relative}.jstree-wholerow-ul .jstree-wholerow{width:100%;cursor:pointer;position:absolute;left:0;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.vakata-context{display:none}.vakata-context,.vakata-context ul{margin:0;padding:2px;position:absolute;background:#f5f5f5;border:1px solid #979797;box-shadow:2px 2px 2px #999}.vakata-context ul{list-style:none;left:100%;margin-top:-2.7em;margin-left:-4px}.vakata-context .vakata-context-right ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context li{list-style:none;display:inline}.vakata-context li>a{display:block;padding:0 2em;text-decoration:none;width:auto;color:#000;white-space:nowrap;line-height:2.4em;text-shadow:1px 1px 0 #fff;border-radius:1px}.vakata-context li>a:hover{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context li>a.vakata-context-parent{background-image:url(data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAIORI4JlrqN1oMSnmmZDQUAOw==);background-position:right center;background-repeat:no-repeat}.vakata-context li>a:focus{outline:0}.vakata-context .vakata-context-hover>a{position:relative;background-color:#e8eff7;box-shadow:0 0 2px #0a6aa1}.vakata-context .vakata-context-separator>a,.vakata-context .vakata-context-separator>a:hover{background:#fff;border:0;border-top:1px solid #e2e3e3;height:1px;min-height:1px;max-height:1px;padding:0;margin:0 0 0 2.4em;border-left:1px solid #e0e0e0;text-shadow:0 0 0 transparent;box-shadow:0 0 0 transparent;border-radius:0}.vakata-context .vakata-contextmenu-disabled a,.vakata-context .vakata-contextmenu-disabled a:hover{color:silver;background-color:transparent;border:0;box-shadow:0 0 0}.vakata-context li>a>i{text-decoration:none;display:inline-block;width:2.4em;height:2.4em;background:0 0;margin:0 0 0 -2em;vertical-align:top;text-align:center;line-height:2.4em}.vakata-context li>a>i:empty{width:2.4em;line-height:2.4em}.vakata-context li>a .vakata-contextmenu-sep{display:inline-block;width:1px;height:2.4em;background:#fff;margin:0 .5em 0 0;border-left:1px solid #e2e3e3}.vakata-context .vakata-contextmenu-shortcut{font-size:.8em;color:silver;opacity:.5;display:none}.vakata-context-rtl ul{left:auto;right:100%;margin-left:auto;margin-right:-4px}.vakata-context-rtl li>a.vakata-context-parent{background-image:url(data:image/gif;base64,R0lGODlhCwAHAIAAACgoKP///yH5BAEAAAEALAAAAAALAAcAAAINjI+AC7rWHIsPtmoxLAA7);background-position:left center;background-repeat:no-repeat}.vakata-context-rtl .vakata-context-separator>a{margin:0 2.4em 0 0;border-left:0;border-right:1px solid #e2e3e3}.vakata-context-rtl .vakata-context-left ul{right:auto;left:100%;margin-left:-4px;margin-right:auto}.vakata-context-rtl li>a>i{margin:0 -2em 0 0}.vakata-context-rtl li>a .vakata-contextmenu-sep{margin:0 0 0 .5em;border-left-color:#fff;background:#e2e3e3}#jstree-marker{position:absolute;top:0;left:0;margin:-5px 0 0 0;padding:0;border-right:0;border-top:5px solid transparent;border-bottom:5px solid transparent;border-left:5px solid;width:0;height:0;font-size:0;line-height:0}#jstree-dnd{line-height:16px;margin:0;padding:4px}#jstree-dnd .jstree-icon,#jstree-dnd .jstree-copy{display:inline-block;text-decoration:none;margin:0 2px 0 0;padding:0;width:16px;height:16px}#jstree-dnd .jstree-ok{background:green}#jstree-dnd .jstree-er{background:red}#jstree-dnd .jstree-copy{margin:0 2px}.jstree-default-dark .jstree-node,.jstree-default-dark .jstree-icon{background-repeat:no-repeat;background-color:transparent}.jstree-default-dark .jstree-anchor,.jstree-default-dark .jstree-wholerow{transition:background-color .15s,box-shadow .15s}.jstree-default-dark .jstree-hovered{background:#555;border-radius:2px;box-shadow:inset 0 0 1px #555}.jstree-default-dark .jstree-clicked{background:#5fa2db;border-radius:2px;box-shadow:inset 0 0 1px #666}.jstree-default-dark .jstree-no-icons .jstree-anchor>.jstree-themeicon{display:none}.jstree-default-dark .jstree-disabled{background:0 0;color:#666}.jstree-default-dark .jstree-disabled.jstree-hovered{background:0 0;box-shadow:none}.jstree-default-dark .jstree-disabled.jstree-clicked{background:#333}.jstree-default-dark .jstree-disabled>.jstree-icon{opacity:.8;filter:url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'jstree-grayscale\'><feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/></filter></svg>#jstree-grayscale");filter:gray;-webkit-filter:grayscale(100%)}.jstree-default-dark .jstree-search{font-style:italic;color:#fff;font-weight:700}.jstree-default-dark .jstree-no-checkboxes .jstree-checkbox{display:none!important}.jstree-default-dark.jstree-checkbox-no-clicked .jstree-clicked{background:0 0;box-shadow:none}.jstree-default-dark.jstree-checkbox-no-clicked .jstree-clicked.jstree-hovered{background:#555}.jstree-default-dark.jstree-checkbox-no-clicked>.jstree-wholerow-ul .jstree-wholerow-clicked{background:0 0}.jstree-default-dark.jstree-checkbox-no-clicked>.jstree-wholerow-ul .jstree-wholerow-clicked.jstree-wholerow-hovered{background:#555}.jstree-default-dark>.jstree-striped{min-width:100%;display:inline-block;background:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAkCAMAAAB/qqA+AAAABlBMVEUAAAAAAAClZ7nPAAAAAnRSTlMNAMM9s3UAAAAXSURBVHjajcEBAQAAAIKg/H/aCQZ70AUBjAATb6YPDgAAAABJRU5ErkJggg==) left top repeat}.jstree-default-dark>.jstree-wholerow-ul .jstree-hovered,.jstree-default-dark>.jstree-wholerow-ul .jstree-clicked{background:0 0;box-shadow:none;border-radius:0}.jstree-default-dark .jstree-wholerow{-moz-box-sizing:border-box;-webkit-box-sizing:border-box;box-sizing:border-box}.jstree-default-dark .jstree-wholerow-hovered{background:#555}.jstree-default-dark .jstree-wholerow-clicked{background:#5fa2db;background:-webkit-linear-gradient(top,#5fa2db 0,#5fa2db 100%);background:linear-gradient(to bottom,#5fa2db 0,#5fa2db 100%)}.jstree-default-dark .jstree-node{min-height:24px;line-height:24px;margin-left:24px;min-width:24px}.jstree-default-dark .jstree-anchor{line-height:24px;height:24px}.jstree-default-dark .jstree-icon{width:24px;height:24px;line-height:24px}.jstree-default-dark .jstree-icon:empty{width:24px;height:24px;line-height:24px}.jstree-default-dark.jstree-rtl .jstree-node{margin-right:24px}.jstree-default-dark .jstree-wholerow{height:24px}.jstree-default-dark .jstree-node,.jstree-default-dark .jstree-icon{background-image:url(32px.png)}.jstree-default-dark .jstree-node{background-position:-292px -4px;background-repeat:repeat-y}.jstree-default-dark .jstree-last{background:0 0}.jstree-default-dark .jstree-open>.jstree-ocl{background-position:-132px -4px}.jstree-default-dark .jstree-closed>.jstree-ocl{background-position:-100px -4px}.jstree-default-dark .jstree-leaf>.jstree-ocl{background-position:-68px -4px}.jstree-default-dark .jstree-themeicon{background-position:-260px -4px}.jstree-default-dark>.jstree-no-dots .jstree-node,.jstree-default-dark>.jstree-no-dots .jstree-leaf>.jstree-ocl{background:0 0}.jstree-default-dark>.jstree-no-dots .jstree-open>.jstree-ocl{background-position:-36px -4px}.jstree-default-dark>.jstree-no-dots .jstree-closed>.jstree-ocl{background-position:-4px -4px}.jstree-default-dark .jstree-disabled{background:0 0}.jstree-default-dark .jstree-disabled.jstree-hovered{background:0 0}.jstree-default-dark .jstree-disabled.jstree-clicked{background:#efefef}.jstree-default-dark .jstree-checkbox{background-position:-164px -4px}.jstree-default-dark .jstree-checkbox:hover{background-position:-164px -36px}.jstree-default-dark.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox,.jstree-default-dark .jstree-checked>.jstree-checkbox{background-position:-228px -4px}.jstree-default-dark.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox:hover,.jstree-default-dark .jstree-checked>.jstree-checkbox:hover{background-position:-228px -36px}.jstree-default-dark .jstree-anchor>.jstree-undetermined{background-position:-196px -4px}.jstree-default-dark .jstree-anchor>.jstree-undetermined:hover{background-position:-196px -36px}.jstree-default-dark>.jstree-striped{background-size:auto 48px}.jstree-default-dark.jstree-rtl .jstree-node{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAACAQMAAAB49I5GAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMOBgAAGAAJMwQHdQAAAABJRU5ErkJggg==);background-position:100% 1px;background-repeat:repeat-y}.jstree-default-dark.jstree-rtl .jstree-last{background:0 0}.jstree-default-dark.jstree-rtl .jstree-open>.jstree-ocl{background-position:-132px -36px}.jstree-default-dark.jstree-rtl .jstree-closed>.jstree-ocl{background-position:-100px -36px}.jstree-default-dark.jstree-rtl .jstree-leaf>.jstree-ocl{background-position:-68px -36px}.jstree-default-dark.jstree-rtl>.jstree-no-dots .jstree-node,.jstree-default-dark.jstree-rtl>.jstree-no-dots .jstree-leaf>.jstree-ocl{background:0 0}.jstree-default-dark.jstree-rtl>.jstree-no-dots .jstree-open>.jstree-ocl{background-position:-36px -36px}.jstree-default-dark.jstree-rtl>.jstree-no-dots .jstree-closed>.jstree-ocl{background-position:-4px -36px}.jstree-default-dark .jstree-themeicon-custom{background-color:transparent;background-image:none;background-position:0 0}.jstree-default-dark>.jstree-container-ul .jstree-loading>.jstree-ocl{background:url(throbber.gif) center center no-repeat}.jstree-default-dark .jstree-file{background:url(32px.png) -100px -68px no-repeat}.jstree-default-dark .jstree-folder{background:url(32px.png) -260px -4px no-repeat}.jstree-default-dark>.jstree-container-ul>.jstree-node{margin-left:0;margin-right:0}#jstree-dnd.jstree-default-dark{line-height:24px;padding:0 4px}#jstree-dnd.jstree-default-dark .jstree-ok,#jstree-dnd.jstree-default-dark .jstree-er{background-image:url(32px.png);background-repeat:no-repeat;background-color:transparent}#jstree-dnd.jstree-default-dark i{background:0 0;width:24px;height:24px;line-height:24px}#jstree-dnd.jstree-default-dark .jstree-ok{background-position:-4px -68px}#jstree-dnd.jstree-default-dark .jstree-er{background-position:-36px -68px}.jstree-default-dark.jstree-rtl .jstree-node{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAACAQMAAAB49I5GAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMOBgAAGAAJMwQHdQAAAABJRU5ErkJggg==)}.jstree-default-dark.jstree-rtl .jstree-last{background:0 0}.jstree-default-dark-small .jstree-node{min-height:18px;line-height:18px;margin-left:18px;min-width:18px}.jstree-default-dark-small .jstree-anchor{line-height:18px;height:18px}.jstree-default-dark-small .jstree-icon{width:18px;height:18px;line-height:18px}.jstree-default-dark-small .jstree-icon:empty{width:18px;height:18px;line-height:18px}.jstree-default-dark-small.jstree-rtl .jstree-node{margin-right:18px}.jstree-default-dark-small .jstree-wholerow{height:18px}.jstree-default-dark-small .jstree-node,.jstree-default-dark-small .jstree-icon{background-image:url(32px.png)}.jstree-default-dark-small .jstree-node{background-position:-295px -7px;background-repeat:repeat-y}.jstree-default-dark-small .jstree-last{background:0 0}.jstree-default-dark-small .jstree-open>.jstree-ocl{background-position:-135px -7px}.jstree-default-dark-small .jstree-closed>.jstree-ocl{background-position:-103px -7px}.jstree-default-dark-small .jstree-leaf>.jstree-ocl{background-position:-71px -7px}.jstree-default-dark-small .jstree-themeicon{background-position:-263px -7px}.jstree-default-dark-small>.jstree-no-dots .jstree-node,.jstree-default-dark-small>.jstree-no-dots .jstree-leaf>.jstree-ocl{background:0 0}.jstree-default-dark-small>.jstree-no-dots .jstree-open>.jstree-ocl{background-position:-39px -7px}.jstree-default-dark-small>.jstree-no-dots .jstree-closed>.jstree-ocl{background-position:-7px -7px}.jstree-default-dark-small .jstree-disabled{background:0 0}.jstree-default-dark-small .jstree-disabled.jstree-hovered{background:0 0}.jstree-default-dark-small .jstree-disabled.jstree-clicked{background:#efefef}.jstree-default-dark-small .jstree-checkbox{background-position:-167px -7px}.jstree-default-dark-small .jstree-checkbox:hover{background-position:-167px -39px}.jstree-default-dark-small.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox,.jstree-default-dark-small .jstree-checked>.jstree-checkbox{background-position:-231px -7px}.jstree-default-dark-small.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox:hover,.jstree-default-dark-small .jstree-checked>.jstree-checkbox:hover{background-position:-231px -39px}.jstree-default-dark-small .jstree-anchor>.jstree-undetermined{background-position:-199px -7px}.jstree-default-dark-small .jstree-anchor>.jstree-undetermined:hover{background-position:-199px -39px}.jstree-default-dark-small>.jstree-striped{background-size:auto 36px}.jstree-default-dark-small.jstree-rtl .jstree-node{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAACAQMAAAB49I5GAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMOBgAAGAAJMwQHdQAAAABJRU5ErkJggg==);background-position:100% 1px;background-repeat:repeat-y}.jstree-default-dark-small.jstree-rtl .jstree-last{background:0 0}.jstree-default-dark-small.jstree-rtl .jstree-open>.jstree-ocl{background-position:-135px -39px}.jstree-default-dark-small.jstree-rtl .jstree-closed>.jstree-ocl{background-position:-103px -39px}.jstree-default-dark-small.jstree-rtl .jstree-leaf>.jstree-ocl{background-position:-71px -39px}.jstree-default-dark-small.jstree-rtl>.jstree-no-dots .jstree-node,.jstree-default-dark-small.jstree-rtl>.jstree-no-dots .jstree-leaf>.jstree-ocl{background:0 0}.jstree-default-dark-small.jstree-rtl>.jstree-no-dots .jstree-open>.jstree-ocl{background-position:-39px -39px}.jstree-default-dark-small.jstree-rtl>.jstree-no-dots .jstree-closed>.jstree-ocl{background-position:-7px -39px}.jstree-default-dark-small .jstree-themeicon-custom{background-color:transparent;background-image:none;background-position:0 0}.jstree-default-dark-small>.jstree-container-ul .jstree-loading>.jstree-ocl{background:url(throbber.gif) center center no-repeat}.jstree-default-dark-small .jstree-file{background:url(32px.png) -103px -71px no-repeat}.jstree-default-dark-small .jstree-folder{background:url(32px.png) -263px -7px no-repeat}.jstree-default-dark-small>.jstree-container-ul>.jstree-node{margin-left:0;margin-right:0}#jstree-dnd.jstree-default-dark-small{line-height:18px;padding:0 4px}#jstree-dnd.jstree-default-dark-small .jstree-ok,#jstree-dnd.jstree-default-dark-small .jstree-er{background-image:url(32px.png);background-repeat:no-repeat;background-color:transparent}#jstree-dnd.jstree-default-dark-small i{background:0 0;width:18px;height:18px;line-height:18px}#jstree-dnd.jstree-default-dark-small .jstree-ok{background-position:-7px -71px}#jstree-dnd.jstree-default-dark-small .jstree-er{background-position:-39px -71px}.jstree-default-dark-small.jstree-rtl .jstree-node{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAACAQMAAABv1h6PAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMHBgAAiABBI4gz9AAAAABJRU5ErkJggg==)}.jstree-default-dark-small.jstree-rtl .jstree-last{background:0 0}.jstree-default-dark-large .jstree-node{min-height:32px;line-height:32px;margin-left:32px;min-width:32px}.jstree-default-dark-large .jstree-anchor{line-height:32px;height:32px}.jstree-default-dark-large .jstree-icon{width:32px;height:32px;line-height:32px}.jstree-default-dark-large .jstree-icon:empty{width:32px;height:32px;line-height:32px}.jstree-default-dark-large.jstree-rtl .jstree-node{margin-right:32px}.jstree-default-dark-large .jstree-wholerow{height:32px}.jstree-default-dark-large .jstree-node,.jstree-default-dark-large .jstree-icon{background-image:url(32px.png)}.jstree-default-dark-large .jstree-node{background-position:-288px 0;background-repeat:repeat-y}.jstree-default-dark-large .jstree-last{background:0 0}.jstree-default-dark-large .jstree-open>.jstree-ocl{background-position:-128px 0}.jstree-default-dark-large .jstree-closed>.jstree-ocl{background-position:-96px 0}.jstree-default-dark-large .jstree-leaf>.jstree-ocl{background-position:-64px 0}.jstree-default-dark-large .jstree-themeicon{background-position:-256px 0}.jstree-default-dark-large>.jstree-no-dots .jstree-node,.jstree-default-dark-large>.jstree-no-dots .jstree-leaf>.jstree-ocl{background:0 0}.jstree-default-dark-large>.jstree-no-dots .jstree-open>.jstree-ocl{background-position:-32px 0}.jstree-default-dark-large>.jstree-no-dots .jstree-closed>.jstree-ocl{background-position:0 0}.jstree-default-dark-large .jstree-disabled{background:0 0}.jstree-default-dark-large .jstree-disabled.jstree-hovered{background:0 0}.jstree-default-dark-large .jstree-disabled.jstree-clicked{background:#efefef}.jstree-default-dark-large .jstree-checkbox{background-position:-160px 0}.jstree-default-dark-large .jstree-checkbox:hover{background-position:-160px -32px}.jstree-default-dark-large.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox,.jstree-default-dark-large .jstree-checked>.jstree-checkbox{background-position:-224px 0}.jstree-default-dark-large.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox:hover,.jstree-default-dark-large .jstree-checked>.jstree-checkbox:hover{background-position:-224px -32px}.jstree-default-dark-large .jstree-anchor>.jstree-undetermined{background-position:-192px 0}.jstree-default-dark-large .jstree-anchor>.jstree-undetermined:hover{background-position:-192px -32px}.jstree-default-dark-large>.jstree-striped{background-size:auto 64px}.jstree-default-dark-large.jstree-rtl .jstree-node{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAACAQMAAAB49I5GAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMOBgAAGAAJMwQHdQAAAABJRU5ErkJggg==);background-position:100% 1px;background-repeat:repeat-y}.jstree-default-dark-large.jstree-rtl .jstree-last{background:0 0}.jstree-default-dark-large.jstree-rtl .jstree-open>.jstree-ocl{background-position:-128px -32px}.jstree-default-dark-large.jstree-rtl .jstree-closed>.jstree-ocl{background-position:-96px -32px}.jstree-default-dark-large.jstree-rtl .jstree-leaf>.jstree-ocl{background-position:-64px -32px}.jstree-default-dark-large.jstree-rtl>.jstree-no-dots .jstree-node,.jstree-default-dark-large.jstree-rtl>.jstree-no-dots .jstree-leaf>.jstree-ocl{background:0 0}.jstree-default-dark-large.jstree-rtl>.jstree-no-dots .jstree-open>.jstree-ocl{background-position:-32px -32px}.jstree-default-dark-large.jstree-rtl>.jstree-no-dots .jstree-closed>.jstree-ocl{background-position:0 -32px}.jstree-default-dark-large .jstree-themeicon-custom{background-color:transparent;background-image:none;background-position:0 0}.jstree-default-dark-large>.jstree-container-ul .jstree-loading>.jstree-ocl{background:url(throbber.gif) center center no-repeat}.jstree-default-dark-large .jstree-file{background:url(32px.png) -96px -64px no-repeat}.jstree-default-dark-large .jstree-folder{background:url(32px.png) -256px 0 no-repeat}.jstree-default-dark-large>.jstree-container-ul>.jstree-node{margin-left:0;margin-right:0}#jstree-dnd.jstree-default-dark-large{line-height:32px;padding:0 4px}#jstree-dnd.jstree-default-dark-large .jstree-ok,#jstree-dnd.jstree-default-dark-large .jstree-er{background-image:url(32px.png);background-repeat:no-repeat;background-color:transparent}#jstree-dnd.jstree-default-dark-large i{background:0 0;width:32px;height:32px;line-height:32px}#jstree-dnd.jstree-default-dark-large .jstree-ok{background-position:0 -64px}#jstree-dnd.jstree-default-dark-large .jstree-er{background-position:-32px -64px}.jstree-default-dark-large.jstree-rtl .jstree-node{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAACAQMAAAAD0EyKAAAABlBMVEUAAAAdHRvEkCwcAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjgIIGBgABCgCBvVLXcAAAAABJRU5ErkJggg==)}.jstree-default-dark-large.jstree-rtl .jstree-last{background:0 0}@media (max-width:768px){#jstree-dnd.jstree-dnd-responsive{line-height:40px;font-weight:700;font-size:1.1em;text-shadow:1px 1px #fff}#jstree-dnd.jstree-dnd-responsive>i{background:0 0;width:40px;height:40px}#jstree-dnd.jstree-dnd-responsive>.jstree-ok{background-image:url(40px.png);background-position:0 -200px;background-size:120px 240px}#jstree-dnd.jstree-dnd-responsive>.jstree-er{background-image:url(40px.png);background-position:-40px -200px;background-size:120px 240px}#jstree-marker.jstree-dnd-responsive{border-left-width:10px;border-top-width:10px;border-bottom-width:10px;margin-top:-10px}}@media (max-width:768px){.jstree-default-dark-responsive .jstree-icon{background-image:url(40px.png)}.jstree-default-dark-responsive .jstree-node,.jstree-default-dark-responsive .jstree-leaf>.jstree-ocl{background:0 0}.jstree-default-dark-responsive .jstree-node{min-height:40px;line-height:40px;margin-left:40px;min-width:40px;white-space:nowrap}.jstree-default-dark-responsive .jstree-anchor{line-height:40px;height:40px}.jstree-default-dark-responsive .jstree-icon,.jstree-default-dark-responsive .jstree-icon:empty{width:40px;height:40px;line-height:40px}.jstree-default-dark-responsive>.jstree-container-ul>.jstree-node{margin-left:0}.jstree-default-dark-responsive.jstree-rtl .jstree-node{margin-left:0;margin-right:40px}.jstree-default-dark-responsive.jstree-rtl .jstree-container-ul>.jstree-node{margin-right:0}.jstree-default-dark-responsive .jstree-ocl,.jstree-default-dark-responsive .jstree-themeicon,.jstree-default-dark-responsive .jstree-checkbox{background-size:120px 240px}.jstree-default-dark-responsive .jstree-leaf>.jstree-ocl{background:0 0}.jstree-default-dark-responsive .jstree-open>.jstree-ocl{background-position:0 0!important}.jstree-default-dark-responsive .jstree-closed>.jstree-ocl{background-position:0 -40px!important}.jstree-default-dark-responsive.jstree-rtl .jstree-closed>.jstree-ocl{background-position:-40px 0!important}.jstree-default-dark-responsive .jstree-themeicon{background-position:-40px -40px}.jstree-default-dark-responsive .jstree-checkbox,.jstree-default-dark-responsive .jstree-checkbox:hover{background-position:-40px -80px}.jstree-default-dark-responsive.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox,.jstree-default-dark-responsive.jstree-checkbox-selection .jstree-clicked>.jstree-checkbox:hover,.jstree-default-dark-responsive .jstree-checked>.jstree-checkbox,.jstree-default-dark-responsive .jstree-checked>.jstree-checkbox:hover{background-position:0 -80px}.jstree-default-dark-responsive .jstree-anchor>.jstree-undetermined,.jstree-default-dark-responsive .jstree-anchor>.jstree-undetermined:hover{background-position:0 -120px}.jstree-default-dark-responsive .jstree-anchor{font-weight:700;font-size:1.1em;text-shadow:1px 1px #fff}.jstree-default-dark-responsive>.jstree-striped{background:0 0}.jstree-default-dark-responsive .jstree-wholerow{border-top:1px solid #666;border-bottom:1px solid #000;background:#333;height:40px}.jstree-default-dark-responsive .jstree-wholerow-hovered{background:#555}.jstree-default-dark-responsive .jstree-wholerow-clicked{background:#5fa2db}.jstree-default-dark-responsive .jstree-children .jstree-last>.jstree-wholerow{box-shadow:inset 0 -6px 3px -5px #111}.jstree-default-dark-responsive .jstree-children .jstree-open>.jstree-wholerow{box-shadow:inset 0 6px 3px -5px #111;border-top:0}.jstree-default-dark-responsive .jstree-children .jstree-open+.jstree-open{box-shadow:none}.jstree-default-dark-responsive .jstree-node,.jstree-default-dark-responsive .jstree-icon,.jstree-default-dark-responsive .jstree-node>.jstree-ocl,.jstree-default-dark-responsive .jstree-themeicon,.jstree-default-dark-responsive .jstree-checkbox{background-image:url(40px.png);background-size:120px 240px}.jstree-default-dark-responsive .jstree-node{background-position:-80px 0;background-repeat:repeat-y}.jstree-default-dark-responsive .jstree-last{background:0 0}.jstree-default-dark-responsive .jstree-leaf>.jstree-ocl{background-position:-40px -120px}.jstree-default-dark-responsive .jstree-last>.jstree-ocl{background-position:-40px -160px}.jstree-default-dark-responsive .jstree-themeicon-custom{background-color:transparent;background-image:none;background-position:0 0}.jstree-default-dark-responsive .jstree-file{background:url(40px.png) 0 -160px no-repeat;background-size:120px 240px}.jstree-default-dark-responsive .jstree-folder{background:url(40px.png) -40px -40px no-repeat;background-size:120px 240px}.jstree-default-dark-responsive>.jstree-container-ul>.jstree-node{margin-left:0;margin-right:0}}.jstree-default-dark{background:#333}.jstree-default-dark .jstree-anchor{color:#999;text-shadow:1px 1px 0 rgba(0,0,0,.5)}.jstree-default-dark .jstree-clicked,.jstree-default-dark .jstree-checked{color:#fff}.jstree-default-dark .jstree-hovered{color:#fff}#jstree-marker.jstree-default-dark{border-left-color:#999;background:0 0}.jstree-default-dark .jstree-anchor>.jstree-icon{opacity:.75}.jstree-default-dark .jstree-clicked>.jstree-icon,.jstree-default-dark .jstree-hovered>.jstree-icon,.jstree-default-dark .jstree-checked>.jstree-icon{opacity:1}.jstree-default-dark.jstree-rtl .jstree-node{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAACAQMAAAB49I5GAAAABlBMVEUAAACZmZl+9SADAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMOBgAAGAAJMwQHdQAAAABJRU5ErkJggg==)}.jstree-default-dark.jstree-rtl .jstree-last{background:0 0}.jstree-default-dark-small.jstree-rtl .jstree-node{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABIAAAACAQMAAABv1h6PAAAABlBMVEUAAACZmZl+9SADAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjAAMHBgAAiABBI4gz9AAAAABJRU5ErkJggg==)}.jstree-default-dark-small.jstree-rtl .jstree-last{background:0 0}.jstree-default-dark-large.jstree-rtl .jstree-node{background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAACAQMAAAAD0EyKAAAABlBMVEUAAACZmZl+9SADAAAAAXRSTlMAQObYZgAAAAxJREFUCNdjgIIGBgABCgCBvVLXcAAAAABJRU5ErkJggg==)}.jstree-default-dark-large.jstree-rtl .jstree-last{background:0 0} | kalkidanf/cdnjs | ajax/libs/jstree/3.1.0/themes/default-dark/style.min.css | CSS | mit | 27,354 |
this.D = this.D || {};
(function () {
'use strict';
var AllGithubEmoji = ['+1', '100', '1234', '8ball', 'a', 'ab', 'abc', 'abcd',
'accept', 'aerial_tramway', 'airplane', 'alarm_clock', 'alien', 'ambulance',
'anchor', 'angel', 'anger', 'angry', 'anguished', 'ant', 'apple', 'aquarius',
'aries', 'arrow_backward', 'arrow_double_down', 'arrow_double_up', 'arrow_down',
'arrow_down_small', 'arrow_forward', 'arrow_heading_down', 'arrow_heading_up',
'arrow_left', 'arrow_lower_left', 'arrow_lower_right', 'arrow_right',
'arrow_right_hook', 'arrow_up', 'arrow_up_down', 'arrow_up_small', 'arrow_upper_left',
'arrow_upper_right', 'arrows_clockwise', 'arrows_counterclockwise', 'art',
'articulated_lorry', 'astonished', 'athletic_shoe', 'atm', 'b', 'baby', 'baby_bottle',
'baby_chick', 'baby_symbol', 'back', 'baggage_claim', 'balloon', 'ballot_box_with_check',
'bamboo', 'banana', 'bangbang', 'bank', 'bar_chart', 'barber', 'baseball', 'basketball',
'bath', 'bathtub', 'battery', 'bear', 'bee', 'beer', 'beers', 'beetle', 'beginner',
'bell', 'bento', 'bicyclist', 'bike', 'bikini', 'bird', 'birthday', 'black_circle',
'black_joker', 'black_large_square', 'black_medium_small_square', 'black_medium_square',
'black_nib', 'black_small_square', 'black_square_button', 'blossom', 'blowfish',
'blue_book', 'blue_car', 'blue_heart', 'blush', 'boar', 'boat', 'bomb', 'book',
'bookmark', 'bookmark_tabs', 'books', 'boom', 'boot', 'bouquet', 'bow', 'bowling',
'bowtie', 'boy', 'bread', 'bride_with_veil', 'bridge_at_night', 'briefcase',
'broken_heart', 'bug', 'bulb', 'bullettrain_front', 'bullettrain_side', 'bus',
'busstop', 'bust_in_silhouette', 'busts_in_silhouette', 'cactus', 'cake', 'calendar',
'calling', 'camel', 'camera', 'cancer', 'candy', 'capital_abcd', 'capricorn', 'car',
'card_index', 'carousel_horse', 'cat', 'cat2', 'cd', 'chart', 'chart_with_downwards_trend',
'chart_with_upwards_trend', 'checkered_flag', 'cherries', 'cherry_blossom', 'chestnut',
'chicken', 'children_crossing', 'chocolate_bar', 'christmas_tree', 'church', 'cinema',
'circus_tent', 'city_sunrise', 'city_sunset', 'cl', 'clap', 'clapper', 'clipboard',
'clock1', 'clock10', 'clock1030', 'clock11', 'clock1130', 'clock12', 'clock1230',
'clock130', 'clock2', 'clock230', 'clock3', 'clock330', 'clock4', 'clock430',
'clock5', 'clock530', 'clock6', 'clock630', 'clock7', 'clock730', 'clock8', 'clock830',
'clock9', 'clock930', 'closed_book', 'closed_lock_with_key', 'closed_umbrella',
'cloud', 'clubs', 'cn', 'cocktail', 'coffee', 'cold_sweat', 'collision', 'computer',
'confetti_ball', 'confounded', 'confused', 'congratulations', 'construction',
'construction_worker', 'convenience_store', 'cookie', 'cool', 'cop', 'copyright',
'corn', 'couple', 'couple_with_heart', 'couplekiss', 'cow', 'cow2', 'credit_card',
'crescent_moon', 'crocodile', 'crossed_flags', 'crown', 'cry', 'crying_cat_face',
'crystal_ball', 'cupid', 'curly_loop', 'currency_exchange', 'curry', 'custard',
'customs', 'cyclone', 'dancer', 'dancers', 'dango', 'dart', 'dash', 'date', 'de',
'deciduous_tree', 'department_store', 'diamond_shape_with_a_dot_inside', 'diamonds',
'disappointed', 'disappointed_relieved', 'dizzy', 'dizzy_face', 'do_not_litter',
'dog', 'dog2', 'dollar', 'dolls', 'dolphin', 'door', 'doughnut', 'dragon',
'dragon_face', 'dress', 'dromedary_camel', 'droplet', 'dvd', 'e-mail', 'ear',
'ear_of_rice', 'earth_africa', 'earth_americas', 'earth_asia', 'egg', 'eggplant',
'eight', 'eight_pointed_black_star', 'eight_spoked_asterisk', 'electric_plug',
'elephant', 'email', 'end', 'envelope', 'envelope_with_arrow', 'es', 'euro',
'european_castle', 'european_post_office', 'evergreen_tree', 'exclamation',
'expressionless', 'eyeglasses', 'eyes', 'facepunch', 'factory', 'fallen_leaf',
'family', 'fast_forward', 'fax', 'fearful', 'feelsgood', 'feet', 'ferris_wheel',
'file_folder', 'finnadie', 'fire', 'fire_engine', 'fireworks', 'first_quarter_moon',
'first_quarter_moon_with_face', 'fish', 'fish_cake', 'fishing_pole_and_fish',
'fist', 'five', 'flags', 'flashlight', 'flipper', 'floppy_disk', 'flower_playing_cards',
'flushed', 'foggy', 'football', 'footprints', 'fork_and_knife', 'fountain',
'four', 'four_leaf_clover', 'fr', 'free', 'fried_shrimp', 'fries', 'frog',
'frowning', 'fu', 'fuelpump', 'full_moon', 'full_moon_with_face', 'game_die',
'gb', 'gem', 'gemini', 'ghost', 'gift', 'gift_heart', 'girl', 'globe_with_meridians',
'goat', 'goberserk', 'godmode', 'golf', 'grapes', 'green_apple', 'green_book',
'green_heart', 'grey_exclamation', 'grey_question', 'grimacing', 'grin',
'grinning', 'guardsman', 'guitar', 'gun', 'haircut', 'hamburger', 'hammer',
'hamster', 'hand', 'handbag', 'hankey', 'hash', 'hatched_chick', 'hatching_chick',
'headphones', 'hear_no_evil', 'heart', 'heart_decoration', 'heart_eyes',
'heart_eyes_cat', 'heartbeat', 'heartpulse', 'hearts', 'heavy_check_mark',
'heavy_division_sign', 'heavy_dollar_sign', 'heavy_exclamation_mark', 'heavy_minus_sign',
'heavy_multiplication_x', 'heavy_plus_sign', 'helicopter', 'herb', 'hibiscus',
'high_brightness', 'high_heel', 'hocho', 'honey_pot', 'honeybee', 'horse',
'horse_racing', 'hospital', 'hotel', 'hotsprings', 'hourglass', 'hourglass_flowing_sand',
'house', 'house_with_garden', 'hurtrealbad', 'hushed', 'ice_cream', 'icecream',
'id', 'ideograph_advantage', 'imp', 'inbox_tray', 'incoming_envelope',
'information_desk_person', 'information_source', 'innocent', 'interrobang',
'iphone', 'it', 'izakaya_lantern', 'jack_o_lantern', 'japan', 'japanese_castle',
'japanese_goblin', 'japanese_ogre', 'jeans', 'joy', 'joy_cat', 'jp', 'key',
'keycap_ten', 'kimono', 'kiss', 'kissing', 'kissing_cat', 'kissing_closed_eyes',
'kissing_heart', 'kissing_smiling_eyes', 'koala', 'koko', 'kr', 'lantern',
'large_blue_circle', 'large_blue_diamond', 'large_orange_diamond', 'last_quarter_moon',
'last_quarter_moon_with_face', 'laughing', 'leaves', 'ledger', 'left_luggage',
'left_right_arrow', 'leftwards_arrow_with_hook', 'lemon', 'leo', 'leopard',
'libra', 'light_rail', 'link', 'lips', 'lipstick', 'lock', 'lock_with_ink_pen',
'lollipop', 'loop', 'loud_sound', 'loudspeaker', 'love_hotel', 'love_letter',
'low_brightness', 'm', 'mag', 'mag_right', 'mahjong', 'mailbox', 'mailbox_closed',
'mailbox_with_mail', 'mailbox_with_no_mail', 'man', 'man_with_gua_pi_mao',
'man_with_turban', 'mans_shoe', 'maple_leaf', 'mask', 'massage', 'meat_on_bone',
'mega', 'melon', 'memo', 'mens', 'metal', 'metro', 'microphone', 'microscope',
'milky_way', 'minibus', 'minidisc', 'mobile_phone_off', 'money_with_wings',
'moneybag', 'monkey', 'monkey_face', 'monorail', 'moon', 'mortar_board', 'mount_fuji',
'mountain_bicyclist', 'mountain_cableway', 'mountain_railway', 'mouse', 'mouse2',
'movie_camera', 'moyai', 'muscle', 'mushroom', 'musical_keyboard', 'musical_note',
'musical_score', 'mute', 'nail_care', 'name_badge', 'neckbeard', 'necktie',
'negative_squared_cross_mark', 'neutral_face', 'new', 'new_moon', 'new_moon_with_face',
'newspaper', 'ng', 'night_with_stars', 'nine', 'no_bell', 'no_bicycles', 'no_entry',
'no_entry_sign', 'no_good', 'no_mobile_phones', 'no_mouth', 'no_pedestrians',
'no_smoking', 'non-potable_water', 'nose', 'notebook', 'notebook_with_decorative_cover',
'notes', 'nut_and_bolt', 'o', 'o2', 'ocean', 'octocat', 'octopus', 'oden', 'office',
'ok', 'ok_hand', 'ok_woman', 'older_man', 'older_woman', 'on', 'oncoming_automobile',
'oncoming_bus', 'oncoming_police_car', 'oncoming_taxi', 'one', 'open_book',
'open_file_folder', 'open_hands', 'open_mouth', 'ophiuchus', 'orange_book',
'outbox_tray', 'ox', 'package', 'page_facing_up', 'page_with_curl', 'pager',
'palm_tree', 'panda_face', 'paperclip', 'parking', 'part_alternation_mark',
'partly_sunny', 'passport_control', 'paw_prints', 'peach', 'pear', 'pencil',
'pencil2', 'penguin', 'pensive', 'performing_arts', 'persevere', 'person_frowning',
'person_with_blond_hair', 'person_with_pouting_face', 'phone', 'pig', 'pig2',
'pig_nose', 'pill', 'pineapple', 'pisces', 'pizza', 'point_down', 'point_left',
'point_right', 'point_up', 'point_up_2', 'police_car', 'poodle', 'poop',
'post_office', 'postal_horn', 'postbox', 'potable_water', 'pouch', 'poultry_leg',
'pound', 'pouting_cat', 'pray', 'princess', 'punch', 'purple_heart', 'purse',
'pushpin', 'put_litter_in_its_place', 'question', 'rabbit', 'rabbit2', 'racehorse',
'radio', 'radio_button', 'rage', 'rage1', 'rage2', 'rage3', 'rage4', 'railway_car',
'rainbow', 'raised_hand', 'raised_hands', 'raising_hand', 'ram', 'ramen', 'rat',
'recycle', 'red_car', 'red_circle', 'registered', 'relaxed', 'relieved', 'repeat',
'repeat_one', 'restroom', 'revolving_hearts', 'rewind', 'ribbon', 'rice',
'rice_ball', 'rice_cracker', 'rice_scene', 'ring', 'rocket', 'roller_coaster',
'rooster', 'rose', 'rotating_light', 'round_pushpin', 'rowboat', 'ru', 'rugby_football',
'runner', 'running', 'running_shirt_with_sash', 'sa', 'sagittarius', 'sailboat',
'sake', 'sandal', 'santa', 'satellite', 'satisfied', 'saxophone', 'school',
'school_satchel', 'scissors', 'scorpius', 'scream', 'scream_cat', 'scroll',
'seat', 'secret', 'see_no_evil', 'seedling', 'seven', 'shaved_ice', 'sheep',
'shell', 'ship', 'shipit', 'shirt', 'shit', 'shoe', 'shower', 'signal_strength',
'six', 'six_pointed_star', 'ski', 'skull', 'sleeping', 'sleepy', 'slot_machine',
'small_blue_diamond', 'small_orange_diamond', 'small_red_triangle',
'small_red_triangle_down', 'smile', 'smile_cat', 'smiley', 'smiley_cat',
'smiling_imp', 'smirk', 'smirk_cat', 'smoking', 'snail', 'snake', 'snowboarder',
'snowflake', 'snowman', 'sob', 'soccer', 'soon', 'sos', 'sound', 'space_invader',
'spades', 'spaghetti', 'sparkle', 'sparkler', 'sparkles', 'sparkling_heart',
'speak_no_evil', 'speaker', 'speech_balloon', 'speedboat', 'squirrel', 'star',
'star2', 'stars', 'station', 'statue_of_liberty', 'steam_locomotive', 'stew',
'straight_ruler', 'strawberry', 'stuck_out_tongue', 'stuck_out_tongue_closed_eyes',
'stuck_out_tongue_winking_eye', 'sun_with_face', 'sunflower', 'sunglasses',
'sunny', 'sunrise', 'sunrise_over_mountains', 'surfer', 'sushi', 'suspect',
'suspension_railway', 'sweat', 'sweat_drops', 'sweat_smile', 'sweet_potato',
'swimmer', 'symbols', 'syringe', 'tada', 'tanabata_tree', 'tangerine', 'taurus',
'taxi', 'tea', 'telephone', 'telephone_receiver', 'telescope', 'tennis', 'tent',
'thought_balloon', 'three', 'thumbsdown', 'thumbsup', 'ticket', 'tiger', 'tiger2',
'tired_face', 'tm', 'toilet', 'tokyo_tower', 'tomato', 'tongue', 'top', 'tophat',
'tractor', 'traffic_light', 'train', 'train2', 'tram', 'triangular_flag_on_post',
'triangular_ruler', 'trident', 'triumph', 'trolleybus', 'trollface', 'trophy',
'tropical_drink', 'tropical_fish', 'truck', 'trumpet', 'tshirt', 'tulip',
'turtle', 'tv', 'twisted_rightwards_arrows', 'two', 'two_hearts', 'two_men_holding_hands',
'two_women_holding_hands', 'u5272', 'u5408', 'u55b6', 'u6307', 'u6708', 'u6709',
'u6e80', 'u7121', 'u7533', 'u7981', 'u7a7a', 'uk', 'umbrella', 'unamused',
'underage', 'unlock', 'up', 'us', 'v', 'vertical_traffic_light', 'vhs',
'vibration_mode', 'video_camera', 'video_game', 'violin', 'virgo', 'volcano',
'vs', 'walking', 'waning_crescent_moon', 'waning_gibbous_moon', 'warning',
'watch', 'water_buffalo', 'watermelon', 'wave', 'wavy_dash', 'waxing_crescent_moon',
'waxing_gibbous_moon', 'wc', 'weary', 'wedding', 'whale', 'whale2', 'wheelchair',
'white_check_mark', 'white_circle', 'white_flower', 'white_large_square',
'white_medium_small_square', 'white_medium_square', 'white_small_square',
'white_square_button', 'wind_chime', 'wine_glass', 'wink', 'wolf', 'woman',
'womans_clothes', 'womans_hat', 'womens', 'worried', 'wrench', 'x', 'yellow_heart',
'yen', 'yum', 'zap', 'zero', 'zzz'];
// emoji from All-Github-Emoji-Icons
// https://github.com/scotch-io/All-Github-Emoji-Icons
window.emojify = function (match, $1) {
return AllGithubEmoji.indexOf($1) === -1
? match
: '<img class="emoji" src="https://assets-cdn.github.com/images/icons/emoji/' + $1 + '.png" alt="' + $1 + '" />'
};
}());
| jdh8/cdnjs | ajax/libs/docsify/3.4.0/plugins/emoji.js | JavaScript | mit | 12,253 |
var _ = require("lodash");
/**
* @constructor
*/
var EasyExtender = function (plugins, hooks) {
this.plugins = {};
this.pluginOptions = {};
this.returnValues = {};
this.hooks = hooks;
this.defaultPlugins = plugins;
return this;
};
/**
* @returns {EasyExtender}
*/
EasyExtender.prototype.init = function () {
if (this.defaultPlugins) {
var required = Object.keys(this.defaultPlugins);
required.forEach(function (name) {
if (_.isUndefined(this.plugins[name])) {
this.plugins[name] = this.defaultPlugins[name];
}
}, this);
}
return this;
};
/**
* Call the '.plugin()' method of all registered plugins
*/
EasyExtender.prototype.initUserPlugins = function () {
var args = _.toArray(arguments);
var userPlugins = _.difference(Object.keys(this.plugins), Object.keys(this.defaultPlugins));
if (userPlugins.length) {
userPlugins.forEach(function (plugin) {
var pluginOptions = {};
if (this.pluginOptions) {
pluginOptions = this.pluginOptions[plugin];
}
this.returnValues[plugin].push({
value: this.get(plugin).apply(null, [pluginOptions].concat(args))
});
if (!_.isUndefined(pluginOptions) && !_.isUndefined(pluginOptions.enabled)) {
if (pluginOptions.enabled) {
this.enablePlugin(plugin);
} else {
this.disablePlugin(plugin);
}
} else {
this.enablePlugin(plugin);
}
}, this);
}
};
/**
* Wrap a module in East Extender pattern
* @param module
* @param localName
*/
EasyExtender.prototype.wrap = function (module, localName) {
this.registerPlugin({
"plugin:name": localName,
"plugin": function () {
return module;
}
});
};
/**
* @param {String} name
* @returns {Function|Boolean}
*/
EasyExtender.prototype.get = function (name) {
if (!_.isUndefined(this.plugins[name])) {
return this.plugins[name].plugin || false;
}
return false;
};
/**
* @param {Object} module
* @param {Object} [opts]
* @param {Function} [cb]
*/
EasyExtender.prototype.registerPlugin = function (module, opts, cb) {
var pluginOptions;
if (!_.isFunction(module.plugin)) {
return _.isFunction(cb) ? cb("Module must implement a .plugin() method") : false;
}
if (!cb && opts) {
if (_.isFunction(opts)) {
cb = opts;
} else {
pluginOptions = opts;
}
}
var name = _.isUndefined(module["plugin:name"]) ? _.uniqueId() : module["plugin:name"];
this.pluginOptions[name] = pluginOptions;
this.returnValues[name] = [];
this.plugins[name] = module;
if (_.isFunction(cb)) {
cb(null);
}
this.disablePlugin(name);
return this;
};
/**
*
* @param name
*/
EasyExtender.prototype.getPlugin = function (module) {
if (_.isString(module)) {
module = this.plugins[module];
}
if (!module) {
return false;
}
return module;
};
/**
*
* @param name
*/
EasyExtender.prototype.disablePlugin = function (module) {
module = this.getPlugin(module);
module._enabled = false;
return module;
};
/**
* @param name
*/
EasyExtender.prototype.enablePlugin = function (module) {
module = this.getPlugin(module);
module._enabled = true;
return module;
};
/**
* @param name
* @returns {*}
*/
EasyExtender.prototype.hook = function (name) {
// Get any extra args
var args = Array.prototype.slice.call(arguments, 1);
// build a list of hook funcs
var funcs = [];
_.each(this.plugins, function (plugin) {
if (plugin.hooks) {
if (!_.isUndefined(plugin.hooks[name])) {
funcs.push(plugin.hooks[name]);
}
}
});
return this.hooks[name].apply(this, [funcs].concat(args));
};
/**
* @param name
* @returns {*}
*/
EasyExtender.prototype.getReturnValues = function (name) {
return this.returnValues[name] || [];
};
module.exports = EasyExtender; | Marina-Gurrieri/montheme | node_modules/grunt-browser-sync/node_modules/browser-sync/node_modules/easy-extender/index.js | JavaScript | mit | 4,239 |
define("dojo/promise/instrumentation", [
"./tracer",
"../has",
"../_base/lang",
"../_base/array"
], function(tracer, has, lang, arrayUtil){
function logError(error, rejection, deferred){
var stack = "";
if(error && error.stack){
stack += error.stack;
}
if(rejection && rejection.stack){
stack += "\n ----------------------------------------\n rejected" + rejection.stack.split("\n").slice(1).join("\n").replace(/^\s+/, " ");
}
if(deferred && deferred.stack){
stack += "\n ----------------------------------------\n" + deferred.stack;
}
console.error(error, stack);
}
function reportRejections(error, handled, rejection, deferred){
if(!handled){
logError(error, rejection, deferred);
}
}
var errors = [];
var activeTimeout = false;
var unhandledWait = 1000;
function trackUnhandledRejections(error, handled, rejection, deferred){
if(handled){
arrayUtil.some(errors, function(obj, ix){
if(obj.error === error){
errors.splice(ix, 1);
return true;
}
});
}else if(!arrayUtil.some(errors, function(obj){ return obj.error === error; })){
errors.push({
error: error,
rejection: rejection,
deferred: deferred,
timestamp: new Date().getTime()
});
}
if(!activeTimeout){
activeTimeout = setTimeout(logRejected, unhandledWait);
}
}
function logRejected(){
var now = new Date().getTime();
var reportBefore = now - unhandledWait;
errors = arrayUtil.filter(errors, function(obj){
if(obj.timestamp < reportBefore){
logError(obj.error, obj.rejection, obj.deferred);
return false;
}
return true;
});
if(errors.length){
activeTimeout = setTimeout(logRejected, errors[0].timestamp + unhandledWait - now);
}else{
activeTimeout = false;
}
}
return function(Deferred){
// summary:
// Initialize instrumentation for the Deferred class.
// description:
// Initialize instrumentation for the Deferred class.
// Done automatically by `dojo/Deferred` if the
// `deferredInstrumentation` and `useDeferredInstrumentation`
// config options are set.
//
// Sets up `dojo/promise/tracer` to log to the console.
//
// Sets up instrumentation of rejected deferreds so unhandled
// errors are logged to the console.
var usage = has("config-useDeferredInstrumentation");
if(usage){
tracer.on("resolved", lang.hitch(console, "log", "resolved"));
tracer.on("rejected", lang.hitch(console, "log", "rejected"));
tracer.on("progress", lang.hitch(console, "log", "progress"));
var args = [];
if(typeof usage === "string"){
args = usage.split(",");
usage = args.shift();
}
if(usage === "report-rejections"){
Deferred.instrumentRejected = reportRejections;
}else if(usage === "report-unhandled-rejections" || usage === true || usage === 1){
Deferred.instrumentRejected = trackUnhandledRejections;
unhandledWait = parseInt(args[0], 10) || unhandledWait;
}else{
throw new Error("Unsupported instrumentation usage <" + usage + ">");
}
}
};
});
| ripple0328/cdnjs | ajax/libs/dojo/1.9.1/promise/instrumentation.js.uncompressed.js | JavaScript | mit | 3,049 |
define("dojo/promise/instrumentation", [
"./tracer",
"../has",
"../_base/lang",
"../_base/array"
], function(tracer, has, lang, arrayUtil){
function logError(error, rejection, deferred){
var stack = "";
if(error && error.stack){
stack += error.stack;
}
if(rejection && rejection.stack){
stack += "\n ----------------------------------------\n rejected" + rejection.stack.split("\n").slice(1).join("\n").replace(/^\s+/, " ");
}
if(deferred && deferred.stack){
stack += "\n ----------------------------------------\n" + deferred.stack;
}
console.error(error, stack);
}
function reportRejections(error, handled, rejection, deferred){
if(!handled){
logError(error, rejection, deferred);
}
}
var errors = [];
var activeTimeout = false;
var unhandledWait = 1000;
function trackUnhandledRejections(error, handled, rejection, deferred){
if(handled){
arrayUtil.some(errors, function(obj, ix){
if(obj.error === error){
errors.splice(ix, 1);
return true;
}
});
}else if(!arrayUtil.some(errors, function(obj){ return obj.error === error; })){
errors.push({
error: error,
rejection: rejection,
deferred: deferred,
timestamp: new Date().getTime()
});
}
if(!activeTimeout){
activeTimeout = setTimeout(logRejected, unhandledWait);
}
}
function logRejected(){
var now = new Date().getTime();
var reportBefore = now - unhandledWait;
errors = arrayUtil.filter(errors, function(obj){
if(obj.timestamp < reportBefore){
logError(obj.error, obj.rejection, obj.deferred);
return false;
}
return true;
});
if(errors.length){
activeTimeout = setTimeout(logRejected, errors[0].timestamp + unhandledWait - now);
}else{
activeTimeout = false;
}
}
return function(Deferred){
// summary:
// Initialize instrumentation for the Deferred class.
// description:
// Initialize instrumentation for the Deferred class.
// Done automatically by `dojo/Deferred` if the
// `deferredInstrumentation` and `useDeferredInstrumentation`
// config options are set.
//
// Sets up `dojo/promise/tracer` to log to the console.
//
// Sets up instrumentation of rejected deferreds so unhandled
// errors are logged to the console.
var usage = has("config-useDeferredInstrumentation");
if(usage){
tracer.on("resolved", lang.hitch(console, "log", "resolved"));
tracer.on("rejected", lang.hitch(console, "log", "rejected"));
tracer.on("progress", lang.hitch(console, "log", "progress"));
var args = [];
if(typeof usage === "string"){
args = usage.split(",");
usage = args.shift();
}
if(usage === "report-rejections"){
Deferred.instrumentRejected = reportRejections;
}else if(usage === "report-unhandled-rejections" || usage === true || usage === 1){
Deferred.instrumentRejected = trackUnhandledRejections;
unhandledWait = parseInt(args[0], 10) || unhandledWait;
}else{
throw new Error("Unsupported instrumentation usage <" + usage + ">");
}
}
};
});
| luhad/cdnjs | ajax/libs/dojo/1.9.0/promise/instrumentation.js.uncompressed.js | JavaScript | mit | 3,049 |
/**
* Sand-Signika theme for Highcharts JS
* @author Torstein Honsi
*/
// Load the fonts
Highcharts.createElement('link', {
href: 'http://fonts.googleapis.com/css?family=Signika:400,700',
rel: 'stylesheet',
type: 'text/css'
}, null, document.getElementsByTagName('head')[0]);
// Add the background image to the container
Highcharts.wrap(Highcharts.Chart.prototype, 'getContainer', function (proceed) {
proceed.call(this);
this.container.style.background = 'url(http://www.highcharts.com/samples/graphics/sand.png)';
});
Highcharts.theme = {
colors: ["#f45b5b", "#8085e9", "#8d4654", "#7798BF", "#aaeeee", "#ff0066", "#eeaaee",
"#55BF3B", "#DF5353", "#7798BF", "#aaeeee"],
chart: {
backgroundColor: null,
style: {
fontFamily: "Signika, serif"
}
},
title: {
style: {
color: 'black',
fontSize: '16px',
fontWeight: 'bold'
}
},
subtitle: {
style: {
color: 'black'
}
},
tooltip: {
borderWidth: 0
},
legend: {
itemStyle: {
fontWeight: 'bold',
fontSize: '13px'
}
},
xAxis: {
labels: {
style: {
color: '#6e6e70'
}
}
},
yAxis: {
labels: {
style: {
color: '#6e6e70'
}
}
},
plotOptions: {
series: {
shadow: true
},
candlestick: {
lineColor: '#404048'
},
map: {
shadow: false
}
},
// Highstock specific
navigator: {
xAxis: {
gridLineColor: '#D0D0D8'
}
},
rangeSelector: {
buttonTheme: {
fill: 'white',
stroke: '#C0C0C8',
'stroke-width': 1,
states: {
select: {
fill: '#D0D0D8'
}
}
}
},
scrollbar: {
trackBorderColor: '#C0C0C8'
},
// General
background2: '#E0E0E8'
};
// Apply the theme
Highcharts.setOptions(Highcharts.theme);
| dada0423/cdnjs | ajax/libs/highstock/2.0.4/themes/sand-signika.js | JavaScript | mit | 1,689 |
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/dnd/autoscroll",["../_base/lang","../sniff","../_base/window","../dom-geometry","../dom-style","../window"],function(_1,_2,_3,_4,_5,_6){
var _7={};
_1.setObject("dojo.dnd.autoscroll",_7);
_7.getViewport=_6.getBox;
_7.V_TRIGGER_AUTOSCROLL=32;
_7.H_TRIGGER_AUTOSCROLL=32;
_7.V_AUTOSCROLL_VALUE=16;
_7.H_AUTOSCROLL_VALUE=16;
var _8,_9=_3.doc,_a=Infinity,_b=Infinity;
_7.autoScrollStart=function(d){
_9=d;
_8=_6.getBox(_9);
var _c=_3.body(_9).parentNode;
_a=Math.max(_c.scrollHeight-_8.h,0);
_b=Math.max(_c.scrollWidth-_8.w,0);
};
_7.autoScroll=function(e){
var v=_8||_6.getBox(_9),_d=_3.body(_9).parentNode,dx=0,dy=0;
if(e.clientX<_7.H_TRIGGER_AUTOSCROLL){
dx=-_7.H_AUTOSCROLL_VALUE;
}else{
if(e.clientX>v.w-_7.H_TRIGGER_AUTOSCROLL){
dx=Math.min(_7.H_AUTOSCROLL_VALUE,_b-_d.scrollLeft);
}
}
if(e.clientY<_7.V_TRIGGER_AUTOSCROLL){
dy=-_7.V_AUTOSCROLL_VALUE;
}else{
if(e.clientY>v.h-_7.V_TRIGGER_AUTOSCROLL){
dy=Math.min(_7.V_AUTOSCROLL_VALUE,_a-_d.scrollTop);
}
}
window.scrollBy(dx,dy);
};
_7._validNodes={"div":1,"p":1,"td":1};
_7._validOverflow={"auto":1,"scroll":1};
_7.autoScrollNodes=function(e){
var b,t,w,h,rx,ry,dx=0,dy=0,_e,_f;
for(var n=e.target;n;){
if(n.nodeType==1&&(n.tagName.toLowerCase() in _7._validNodes)){
var s=_5.getComputedStyle(n),_10=(s.overflow.toLowerCase() in _7._validOverflow),_11=(s.overflowX.toLowerCase() in _7._validOverflow),_12=(s.overflowY.toLowerCase() in _7._validOverflow);
if(_10||_11||_12){
b=_4.getContentBox(n,s);
t=_4.position(n,true);
}
if(_10||_11){
w=Math.min(_7.H_TRIGGER_AUTOSCROLL,b.w/2);
rx=e.pageX-t.x;
if(_2("webkit")||_2("opera")){
rx+=_3.body().scrollLeft;
}
dx=0;
if(rx>0&&rx<b.w){
if(rx<w){
dx=-w;
}else{
if(rx>b.w-w){
dx=w;
}
}
_e=n.scrollLeft;
n.scrollLeft=n.scrollLeft+dx;
}
}
if(_10||_12){
h=Math.min(_7.V_TRIGGER_AUTOSCROLL,b.h/2);
ry=e.pageY-t.y;
if(_2("webkit")||_2("opera")){
ry+=_3.body().scrollTop;
}
dy=0;
if(ry>0&&ry<b.h){
if(ry<h){
dy=-h;
}else{
if(ry>b.h-h){
dy=h;
}
}
_f=n.scrollTop;
n.scrollTop=n.scrollTop+dy;
}
}
if(dx||dy){
return;
}
}
try{
n=n.parentNode;
}
catch(x){
n=null;
}
}
_7.autoScroll(e);
};
return _7;
});
| tresni/cdnjs | ajax/libs/dojo/1.10.1/dnd/autoscroll.js | JavaScript | mit | 2,309 |
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/_base/connect",["./kernel","../on","../topic","../aspect","./event","../mouse","./sniff","./lang","../keys"],function(_1,on,_2,_3,_4,_5,_6,_7){
_6.add("events-keypress-typed",function(){
var _8={charCode:0};
try{
_8=document.createEvent("KeyboardEvent");
(_8.initKeyboardEvent||_8.initKeyEvent).call(_8,"keypress",true,true,null,false,false,false,false,9,3);
}
catch(e){
}
return _8.charCode==0&&!_6("opera");
});
function _9(_a,_b,_c,_d,_e){
_d=_7.hitch(_c,_d);
if(!_a||!(_a.addEventListener||_a.attachEvent)){
return _3.after(_a||_1.global,_b,_d,true);
}
if(typeof _b=="string"&&_b.substring(0,2)=="on"){
_b=_b.substring(2);
}
if(!_a){
_a=_1.global;
}
if(!_e){
switch(_b){
case "keypress":
_b=_f;
break;
case "mouseenter":
_b=_5.enter;
break;
case "mouseleave":
_b=_5.leave;
break;
}
}
return on(_a,_b,_d,_e);
};
var _10={106:42,111:47,186:59,187:43,188:44,189:45,190:46,191:47,192:96,219:91,220:92,221:93,222:39,229:113};
var _11=_6("mac")?"metaKey":"ctrlKey";
var _12=function(evt,_13){
var _14=_7.mixin({},evt,_13);
_15(_14);
_14.preventDefault=function(){
evt.preventDefault();
};
_14.stopPropagation=function(){
evt.stopPropagation();
};
return _14;
};
function _15(evt){
evt.keyChar=evt.charCode?String.fromCharCode(evt.charCode):"";
evt.charOrCode=evt.keyChar||evt.keyCode;
};
var _f;
if(_6("events-keypress-typed")){
var _16=function(e,_17){
try{
return (e.keyCode=_17);
}
catch(e){
return 0;
}
};
_f=function(_18,_19){
var _1a=on(_18,"keydown",function(evt){
var k=evt.keyCode;
var _1b=(k!=13)&&k!=32&&(k!=27||!_6("ie"))&&(k<48||k>90)&&(k<96||k>111)&&(k<186||k>192)&&(k<219||k>222)&&k!=229;
if(_1b||evt.ctrlKey){
var c=_1b?0:k;
if(evt.ctrlKey){
if(k==3||k==13){
return _19.call(evt.currentTarget,evt);
}else{
if(c>95&&c<106){
c-=48;
}else{
if((!evt.shiftKey)&&(c>=65&&c<=90)){
c+=32;
}else{
c=_10[c]||c;
}
}
}
}
var _1c=_12(evt,{type:"keypress",faux:true,charCode:c});
_19.call(evt.currentTarget,_1c);
if(_6("ie")){
_16(evt,_1c.keyCode);
}
}
});
var _1d=on(_18,"keypress",function(evt){
var c=evt.charCode;
c=c>=32?c:0;
evt=_12(evt,{charCode:c,faux:true});
return _19.call(this,evt);
});
return {remove:function(){
_1a.remove();
_1d.remove();
}};
};
}else{
if(_6("opera")){
_f=function(_1e,_1f){
return on(_1e,"keypress",function(evt){
var c=evt.which;
if(c==3){
c=99;
}
c=c<32&&!evt.shiftKey?0:c;
if(evt.ctrlKey&&!evt.shiftKey&&c>=65&&c<=90){
c+=32;
}
return _1f.call(this,_12(evt,{charCode:c}));
});
};
}else{
_f=function(_20,_21){
return on(_20,"keypress",function(evt){
_15(evt);
return _21.call(this,evt);
});
};
}
}
var _22={_keypress:_f,connect:function(obj,_23,_24,_25,_26){
var a=arguments,_27=[],i=0;
_27.push(typeof a[0]=="string"?null:a[i++],a[i++]);
var a1=a[i+1];
_27.push(typeof a1=="string"||typeof a1=="function"?a[i++]:null,a[i++]);
for(var l=a.length;i<l;i++){
_27.push(a[i]);
}
return _9.apply(this,_27);
},disconnect:function(_28){
if(_28){
_28.remove();
}
},subscribe:function(_29,_2a,_2b){
return _2.subscribe(_29,_7.hitch(_2a,_2b));
},publish:function(_2c,_2d){
return _2.publish.apply(_2,[_2c].concat(_2d));
},connectPublisher:function(_2e,obj,_2f){
var pf=function(){
_22.publish(_2e,arguments);
};
return _2f?_22.connect(obj,_2f,pf):_22.connect(obj,pf);
},isCopyKey:function(e){
return e[_11];
}};
_22.unsubscribe=_22.disconnect;
1&&_7.mixin(_1,_22);
return _22;
});
| x112358/cdnjs | ajax/libs/dojo/1.10.4/_base/connect.js | JavaScript | mit | 3,524 |
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
!function ($) {
/**
* Dropdown module.
* @module foundation.dropdown
* @requires foundation.util.keyboard
* @requires foundation.util.box
* @requires foundation.util.triggers
*/
var Dropdown = function () {
/**
* Creates a new instance of a dropdown.
* @class
* @param {jQuery} element - jQuery object to make into a dropdown.
* Object should be of the dropdown panel, rather than its anchor.
* @param {Object} options - Overrides to the default plugin settings.
*/
function Dropdown(element, options) {
_classCallCheck(this, Dropdown);
this.$element = element;
this.options = $.extend({}, Dropdown.defaults, this.$element.data(), options);
this._init();
Foundation.registerPlugin(this, 'Dropdown');
Foundation.Keyboard.register('Dropdown', {
'ENTER': 'open',
'SPACE': 'open',
'ESCAPE': 'close'
});
}
/**
* Initializes the plugin by setting/checking options and attributes, adding helper variables, and saving the anchor.
* @function
* @private
*/
_createClass(Dropdown, [{
key: '_init',
value: function _init() {
var $id = this.$element.attr('id');
this.$anchor = $('[data-toggle="' + $id + '"]').length ? $('[data-toggle="' + $id + '"]') : $('[data-open="' + $id + '"]');
this.$anchor.attr({
'aria-controls': $id,
'data-is-focus': false,
'data-yeti-box': $id,
'aria-haspopup': true,
'aria-expanded': false
});
if (this.options.parentClass) {
this.$parent = this.$element.parents('.' + this.options.parentClass);
} else {
this.$parent = null;
}
this.options.positionClass = this.getPositionClass();
this.counter = 4;
this.usedPositions = [];
this.$element.attr({
'aria-hidden': 'true',
'data-yeti-box': $id,
'data-resize': $id,
'aria-labelledby': this.$anchor[0].id || Foundation.GetYoDigits(6, 'dd-anchor')
});
this._events();
}
/**
* Helper function to determine current orientation of dropdown pane.
* @function
* @returns {String} position - string value of a position class.
*/
}, {
key: 'getPositionClass',
value: function getPositionClass() {
var verticalPosition = this.$element[0].className.match(/(top|left|right|bottom)/g);
verticalPosition = verticalPosition ? verticalPosition[0] : '';
var horizontalPosition = /float-(\S+)/.exec(this.$anchor[0].className);
horizontalPosition = horizontalPosition ? horizontalPosition[1] : '';
var position = horizontalPosition ? horizontalPosition + ' ' + verticalPosition : verticalPosition;
return position;
}
/**
* Adjusts the dropdown panes orientation by adding/removing positioning classes.
* @function
* @private
* @param {String} position - position class to remove.
*/
}, {
key: '_reposition',
value: function _reposition(position) {
this.usedPositions.push(position ? position : 'bottom');
//default, try switching to opposite side
if (!position && this.usedPositions.indexOf('top') < 0) {
this.$element.addClass('top');
} else if (position === 'top' && this.usedPositions.indexOf('bottom') < 0) {
this.$element.removeClass(position);
} else if (position === 'left' && this.usedPositions.indexOf('right') < 0) {
this.$element.removeClass(position).addClass('right');
} else if (position === 'right' && this.usedPositions.indexOf('left') < 0) {
this.$element.removeClass(position).addClass('left');
}
//if default change didn't work, try bottom or left first
else if (!position && this.usedPositions.indexOf('top') > -1 && this.usedPositions.indexOf('left') < 0) {
this.$element.addClass('left');
} else if (position === 'top' && this.usedPositions.indexOf('bottom') > -1 && this.usedPositions.indexOf('left') < 0) {
this.$element.removeClass(position).addClass('left');
} else if (position === 'left' && this.usedPositions.indexOf('right') > -1 && this.usedPositions.indexOf('bottom') < 0) {
this.$element.removeClass(position);
} else if (position === 'right' && this.usedPositions.indexOf('left') > -1 && this.usedPositions.indexOf('bottom') < 0) {
this.$element.removeClass(position);
}
//if nothing cleared, set to bottom
else {
this.$element.removeClass(position);
}
this.classChanged = true;
this.counter--;
}
/**
* Sets the position and orientation of the dropdown pane, checks for collisions.
* Recursively calls itself if a collision is detected, with a new position class.
* @function
* @private
*/
}, {
key: '_setPosition',
value: function _setPosition() {
if (this.$anchor.attr('aria-expanded') === 'false') {
return false;
}
var position = this.getPositionClass(),
$eleDims = Foundation.Box.GetDimensions(this.$element),
$anchorDims = Foundation.Box.GetDimensions(this.$anchor),
_this = this,
direction = position === 'left' ? 'left' : position === 'right' ? 'left' : 'top',
param = direction === 'top' ? 'height' : 'width',
offset = param === 'height' ? this.options.vOffset : this.options.hOffset;
if ($eleDims.width >= $eleDims.windowDims.width || !this.counter && !Foundation.Box.ImNotTouchingYou(this.$element, this.$parent)) {
var newWidth = $eleDims.windowDims.width,
parentHOffset = 0;
if (this.$parent) {
var $parentDims = Foundation.Box.GetDimensions(this.$parent),
parentHOffset = $parentDims.offset.left;
if ($parentDims.width < newWidth) {
newWidth = $parentDims.width;
}
}
this.$element.offset(Foundation.Box.GetOffsets(this.$element, this.$anchor, 'center bottom', this.options.vOffset, this.options.hOffset + parentHOffset, true)).css({
'width': newWidth - this.options.hOffset * 2,
'height': 'auto'
});
this.classChanged = true;
return false;
}
this.$element.offset(Foundation.Box.GetOffsets(this.$element, this.$anchor, position, this.options.vOffset, this.options.hOffset));
while (!Foundation.Box.ImNotTouchingYou(this.$element, this.$parent, true) && this.counter) {
this._reposition(position);
this._setPosition();
}
}
/**
* Adds event listeners to the element utilizing the triggers utility library.
* @function
* @private
*/
}, {
key: '_events',
value: function _events() {
var _this = this;
this.$element.on({
'open.zf.trigger': this.open.bind(this),
'close.zf.trigger': this.close.bind(this),
'toggle.zf.trigger': this.toggle.bind(this),
'resizeme.zf.trigger': this._setPosition.bind(this)
});
if (this.options.hover) {
this.$anchor.off('mouseenter.zf.dropdown mouseleave.zf.dropdown').on('mouseenter.zf.dropdown', function () {
var bodyData = $('body').data();
if (typeof bodyData.whatinput === 'undefined' || bodyData.whatinput === 'mouse') {
clearTimeout(_this.timeout);
_this.timeout = setTimeout(function () {
_this.open();
_this.$anchor.data('hover', true);
}, _this.options.hoverDelay);
}
}).on('mouseleave.zf.dropdown', function () {
clearTimeout(_this.timeout);
_this.timeout = setTimeout(function () {
_this.close();
_this.$anchor.data('hover', false);
}, _this.options.hoverDelay);
});
if (this.options.hoverPane) {
this.$element.off('mouseenter.zf.dropdown mouseleave.zf.dropdown').on('mouseenter.zf.dropdown', function () {
clearTimeout(_this.timeout);
}).on('mouseleave.zf.dropdown', function () {
clearTimeout(_this.timeout);
_this.timeout = setTimeout(function () {
_this.close();
_this.$anchor.data('hover', false);
}, _this.options.hoverDelay);
});
}
}
this.$anchor.add(this.$element).on('keydown.zf.dropdown', function (e) {
var $target = $(this),
visibleFocusableElements = Foundation.Keyboard.findFocusable(_this.$element);
Foundation.Keyboard.handleKey(e, 'Dropdown', {
open: function () {
if ($target.is(_this.$anchor)) {
_this.open();
_this.$element.attr('tabindex', -1).focus();
e.preventDefault();
}
},
close: function () {
_this.close();
_this.$anchor.focus();
}
});
});
}
/**
* Adds an event handler to the body to close any dropdowns on a click.
* @function
* @private
*/
}, {
key: '_addBodyHandler',
value: function _addBodyHandler() {
var $body = $(document.body).not(this.$element),
_this = this;
$body.off('click.zf.dropdown').on('click.zf.dropdown', function (e) {
if (_this.$anchor.is(e.target) || _this.$anchor.find(e.target).length) {
return;
}
if (_this.$element.find(e.target).length) {
return;
}
_this.close();
$body.off('click.zf.dropdown');
});
}
/**
* Opens the dropdown pane, and fires a bubbling event to close other dropdowns.
* @function
* @fires Dropdown#closeme
* @fires Dropdown#show
*/
}, {
key: 'open',
value: function open() {
// var _this = this;
/**
* Fires to close other open dropdowns
* @event Dropdown#closeme
*/
this.$element.trigger('closeme.zf.dropdown', this.$element.attr('id'));
this.$anchor.addClass('hover').attr({ 'aria-expanded': true });
// this.$element/*.show()*/;
this._setPosition();
this.$element.addClass('is-open').attr({ 'aria-hidden': false });
if (this.options.autoFocus) {
var $focusable = Foundation.Keyboard.findFocusable(this.$element);
if ($focusable.length) {
$focusable.eq(0).focus();
}
}
if (this.options.closeOnClick) {
this._addBodyHandler();
}
if (this.options.trapFocus) {
Foundation.Keyboard.trapFocus(this.$element);
}
/**
* Fires once the dropdown is visible.
* @event Dropdown#show
*/
this.$element.trigger('show.zf.dropdown', [this.$element]);
}
/**
* Closes the open dropdown pane.
* @function
* @fires Dropdown#hide
*/
}, {
key: 'close',
value: function close() {
if (!this.$element.hasClass('is-open')) {
return false;
}
this.$element.removeClass('is-open').attr({ 'aria-hidden': true });
this.$anchor.removeClass('hover').attr('aria-expanded', false);
if (this.classChanged) {
var curPositionClass = this.getPositionClass();
if (curPositionClass) {
this.$element.removeClass(curPositionClass);
}
this.$element.addClass(this.options.positionClass)
/*.hide()*/.css({ height: '', width: '' });
this.classChanged = false;
this.counter = 4;
this.usedPositions.length = 0;
}
this.$element.trigger('hide.zf.dropdown', [this.$element]);
if (this.options.trapFocus) {
Foundation.Keyboard.releaseFocus(this.$element);
}
}
/**
* Toggles the dropdown pane's visibility.
* @function
*/
}, {
key: 'toggle',
value: function toggle() {
if (this.$element.hasClass('is-open')) {
if (this.$anchor.data('hover')) return;
this.close();
} else {
this.open();
}
}
/**
* Destroys the dropdown.
* @function
*/
}, {
key: 'destroy',
value: function destroy() {
this.$element.off('.zf.trigger').hide();
this.$anchor.off('.zf.dropdown');
Foundation.unregisterPlugin(this);
}
}]);
return Dropdown;
}();
Dropdown.defaults = {
/**
* Class that designates bounding container of Dropdown (Default: window)
* @option
* @example 'dropdown-parent'
*/
parentClass: null,
/**
* Amount of time to delay opening a submenu on hover event.
* @option
* @example 250
*/
hoverDelay: 250,
/**
* Allow submenus to open on hover events
* @option
* @example false
*/
hover: false,
/**
* Don't close dropdown when hovering over dropdown pane
* @option
* @example true
*/
hoverPane: false,
/**
* Number of pixels between the dropdown pane and the triggering element on open.
* @option
* @example 1
*/
vOffset: 1,
/**
* Number of pixels between the dropdown pane and the triggering element on open.
* @option
* @example 1
*/
hOffset: 1,
/**
* Class applied to adjust open position. JS will test and fill this in.
* @option
* @example 'top'
*/
positionClass: '',
/**
* Allow the plugin to trap focus to the dropdown pane if opened with keyboard commands.
* @option
* @example false
*/
trapFocus: false,
/**
* Allow the plugin to set focus to the first focusable element within the pane, regardless of method of opening.
* @option
* @example true
*/
autoFocus: false,
/**
* Allows a click on the body to close the dropdown.
* @option
* @example false
*/
closeOnClick: false
};
// Window exports
Foundation.plugin(Dropdown, 'Dropdown');
}(jQuery); | sreym/cdnjs | ajax/libs/foundation/6.3.0-rc3/js/plugins/foundation.dropdown.js | JavaScript | mit | 15,288 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/*
* QuickBlox JavaScript SDK
*
* Authentication Module
*
*/
// Browserify exports and dependencies
module.exports = AuthProxy;
var config = require('../qbConfig');
var Utils = require('../qbUtils');
var crypto = require('crypto-js/hmac-sha1');
function AuthProxy(service) {
this.service = service;
}
AuthProxy.prototype.createSession = function(params, callback) {
var _this = this, message;
if (typeof params === 'function' && typeof callback === 'undefined') {
callback = params;
params = {};
}
// Signature of message with SHA-1 using secret key
message = generateAuthMsg(params);
message.signature = signMessage(message, config.creds.authSecret);
if (config.debug) { console.log('AuthProxy.createSession', message); }
this.service.ajax({url: Utils.getUrl(config.urls.session), type: 'POST', data: message},
function(err, res) {
if (err) {
callback(err, null);
} else {
_this.service.setSession(res.session);
callback(null, res.session);
}
});
};
AuthProxy.prototype.destroySession = function(callback) {
var _this = this;
if (config.debug) { console.log('AuthProxy.destroySession'); }
this.service.ajax({url: Utils.getUrl(config.urls.session), type: 'DELETE', dataType: 'text'},
function(err, res) {
if (err) {
callback(err, null);
} else {
_this.service.setSession(null);
callback(null, res);
}
});
};
AuthProxy.prototype.login = function(params, callback) {
if (config.debug) { console.log('AuthProxy.login', params); }
this.service.ajax({url: Utils.getUrl(config.urls.login), type: 'POST', data: params},
function(err, res) {
if (err) { callback(err, null); }
else { callback(null, res.user); }
});
};
AuthProxy.prototype.logout = function(callback) {
if (config.debug) { console.log('AuthProxy.logout'); }
this.service.ajax({url: Utils.getUrl(config.urls.login), type: 'DELETE', dataType:'text'}, callback);
};
/* Private
---------------------------------------------------------------------- */
function generateAuthMsg(params) {
var message = {
application_id: config.creds.appId,
auth_key: config.creds.authKey,
nonce: Utils.randomNonce(),
timestamp: Utils.unixTime()
};
// With user authorization
if (params.login && params.password) {
message.user = {login: params.login, password: params.password};
} else if (params.email && params.password) {
message.user = {email: params.email, password: params.password};
} else if (params.provider) {
// Via social networking provider (e.g. facebook, twitter etc.)
message.provider = params.provider;
if (params.scope) {
message.scope = params.scope;
}
if (params.keys && params.keys.token) {
message.keys = {token: params.keys.token};
}
if (params.keys && params.keys.secret) {
messages.keys.secret = params.keys.secret;
}
}
return message;
}
function signMessage(message, secret) {
var sessionMsg = Object.keys(message).map(function(val) {
if (typeof message[val] === 'object') {
return Object.keys(message[val]).map(function(val1) {
return val + '[' + val1 + ']=' + message[val][val1];
}).sort().join('&');
} else {
return val + '=' + message[val];
}
}).sort().join('&');
return crypto(sessionMsg, secret).toString();
}
},{"../qbConfig":8,"../qbUtils":10,"crypto-js/hmac-sha1":14}],2:[function(require,module,exports){
/*
* QuickBlox JavaScript SDK
*
* Chat 2.0 Module
*
*/
/*
* User's callbacks (listener-functions):
* - onMessageListener
* - onContactListListener
* - onSubscribeListener
* - onConfirmSubscribeListener
* - onRejectSubscribeListener
* - onDisconnectingListener
*/
// Browserify exports and dependencies
require('../../lib/strophe/strophe.min');
var config = require('../qbConfig');
var Utils = require('../qbUtils');
module.exports = ChatProxy;
var dialogUrl = config.urls.chat + '/Dialog';
var messageUrl = config.urls.chat + '/Message';
var mutualSubscriptions = {};
// create Strophe Connection object
var protocol = config.chatProtocol.active === 1 ? config.chatProtocol.bosh : config.chatProtocol.websocket;
var connection = new Strophe.Connection(protocol);
// if (config.debug) {
if (config.chatProtocol.active === 1) {
connection.xmlInput = function(data) { if (typeof data.children !== 'undefined') data.children[0] && console.log('[QBChat RECV]:', data.children[0]); };
connection.xmlOutput = function(data) { if (typeof data.children !== 'undefined') data.children[0] && console.log('[QBChat SENT]:', data.children[0]); };
} else {
connection.xmlInput = function(data) { console.log('[QBChat RECV]:', data); };
connection.xmlOutput = function(data) { console.log('[QBChat SENT]:', data); };
}
// }
function ChatProxy(service) {
var self = this;
this.service = service;
this.roster = new RosterProxy(service);
this.muc = new MucProxy(service);
this.dialog = new DialogProxy(service);
this.message = new MessageProxy(service);
this.helpers = new Helpers;
// stanza callbacks (Message, Presence, IQ)
this._onMessage = function(stanza) {
var from = stanza.getAttribute('from'),
type = stanza.getAttribute('type'),
body = stanza.querySelector('body'),
invite = stanza.querySelector('invite'),
extraParams = stanza.querySelector('extraParams'),
delay = type === 'groupchat' && stanza.querySelector('delay'),
userId = type === 'groupchat' ? self.helpers.getIdFromResource(from) : self.helpers.getIdFromNode(from),
message, extension, attachments, attach, attributes;
if (invite) return true;
// custom parameters
if (extraParams) {
extension = {};
attachments = [];
for (var i = 0, len = extraParams.children.length; i < len; i++) {
if (extraParams.children[i].tagName === 'attachment') {
// attachments
attach = {};
attributes = extraParams.children[i].attributes;
for (var j = 0, len2 = attributes.length; j < len2; j++) {
if (attributes[j].name === 'id' || attributes[j].name === 'size')
attach[attributes[j].name] = parseInt(attributes[j].value);
else
attach[attributes[j].name] = attributes[j].value;
}
attachments.push(attach);
} else {
extension[extraParams.children[i].tagName] = extraParams.children[i].textContent;
}
}
if (attachments.length > 0)
extension.attachments = attachments;
}
message = {
type: type,
body: (body && body.textContent) || null,
extension: extension || null
};
// !delay - this needed to don't duplicate messages from chat 2.0 API history
// with typical XMPP behavior of history messages in group chat
if (typeof self.onMessageListener === 'function' && !delay)
self.onMessageListener(userId, message);
// we must return true to keep the handler alive
// returning false would remove it after it finishes
return true;
};
this._onPresence = function(stanza) {
var from = stanza.getAttribute('from'),
type = stanza.getAttribute('type'),
userId = self.helpers.getIdFromNode(from);
if (!type) {
if (typeof self.onContactListListener === 'function' && mutualSubscriptions[userId])
self.onContactListListener(userId, type);
} else {
// subscriptions callbacks
switch (type) {
case 'subscribe':
if (mutualSubscriptions[userId]) {
self.roster._sendSubscriptionPresence({
jid: from,
type: 'subscribed'
});
} else {
if (typeof self.onSubscribeListener === 'function')
self.onSubscribeListener(userId);
}
break;
case 'subscribed':
if (typeof self.onConfirmSubscribeListener === 'function')
self.onConfirmSubscribeListener(userId);
break;
case 'unsubscribed':
delete mutualSubscriptions[userId];
if (typeof self.onRejectSubscribeListener === 'function')
self.onRejectSubscribeListener(userId);
break;
case 'unsubscribe':
delete mutualSubscriptions[userId];
if (typeof self.onRejectSubscribeListener === 'function')
self.onRejectSubscribeListener(userId);
break;
case 'unavailable':
if (typeof self.onContactListListener === 'function' && mutualSubscriptions[userId])
self.onContactListListener(userId, type);
break;
}
}
// we must return true to keep the handler alive
// returning false would remove it after it finishes
return true;
};
this._onIQ = function(stanza) {
// we must return true to keep the handler alive
// returning false would remove it after it finishes
return true;
};
}
/* Chat module: Core
---------------------------------------------------------------------- */
ChatProxy.prototype._autoSendPresence = function() {
connection.send($pres().tree());
// we must return true to keep the handler alive
// returning false would remove it after it finishes
return true;
};
ChatProxy.prototype.connect = function(params, callback) {
if (config.debug) { console.log('ChatProxy.connect', params); }
var self = this, err;
connection.connect(params.jid, params.password, function(status) {
switch (status) {
case Strophe.Status.ERROR:
err = getError(422, 'Status.ERROR - An error has occurred');
callback(err, null);
break;
case Strophe.Status.CONNECTING:
trace('Status.CONNECTING');
trace('Chat Protocol - ' + (config.chatProtocol.active === 1 ? 'BOSH' : 'WebSocket'));
break;
case Strophe.Status.CONNFAIL:
err = getError(422, 'Status.CONNFAIL - The connection attempt failed');
callback(err, null);
break;
case Strophe.Status.AUTHENTICATING:
trace('Status.AUTHENTICATING');
break;
case Strophe.Status.AUTHFAIL:
err = getError(401, 'Status.AUTHFAIL - The authentication attempt failed');
callback(err, null);
break;
case Strophe.Status.CONNECTED:
trace('Status.CONNECTED at ' + getLocalTime());
connection.addHandler(self._onMessage, null, 'message');
connection.addHandler(self._onPresence, null, 'presence');
connection.addHandler(self._onIQ, null, 'iq');
// get the roster
self.roster.get(function(contacts) {
// chat server will close your connection if you are not active in chat during one minute
// initial presence and an automatic reminder of it each 55 seconds
connection.send($pres().tree());
connection.addTimedHandler(55 * 1000, self._autoSendPresence);
callback(null, contacts);
});
break;
case Strophe.Status.DISCONNECTING:
trace('Status.DISCONNECTING');
break;
case Strophe.Status.DISCONNECTED:
trace('Status.DISCONNECTED at ' + getLocalTime());
if (typeof self.onDisconnectingListener === 'function')
self.onDisconnectingListener();
connection.reset();
break;
case Strophe.Status.ATTACHED:
trace('Status.ATTACHED');
break;
}
});
};
ChatProxy.prototype.send = function(jid, message) {
var msg = $msg({
from: connection.jid,
to: jid,
type: message.type,
id: message.id || connection.getUniqueId()
});
if (message.body) {
msg.c('body', {
xmlns: Strophe.NS.CLIENT
}).t(message.body).up();
}
// custom parameters
if (message.extension) {
msg.c('extraParams', {
xmlns: Strophe.NS.CLIENT
});
Object.keys(message.extension).forEach(function(field) {
if (field === 'attachments') {
// attachments
message.extension[field].forEach(function(attach) {
msg.c('attachment', attach).up();
});
} else {
msg.c(field).t(message.extension[field]).up();
}
});
}
connection.send(msg);
};
// helper function for ChatProxy.send()
ChatProxy.prototype.sendPres = function(type) {
connection.send($pres({
from: connection.jid,
type: type
}));
};
ChatProxy.prototype.disconnect = function() {
connection.flush();
connection.disconnect();
};
ChatProxy.prototype.addListener = function(params, callback) {
return connection.addHandler(handler, null, params.name || null, params.type || null, params.id || null, params.from || null);
function handler() {
callback();
// if 'false' - a handler will be performed only once
return params.live !== false;
}
};
ChatProxy.prototype.deleteListener = function(ref) {
connection.deleteHandler(ref);
};
/* Chat module: Roster
*
* Integration of Roster Items and Presence Subscriptions
* http://xmpp.org/rfcs/rfc3921.html#int
* default - Mutual Subscription
*
---------------------------------------------------------------------- */
function RosterProxy(service) {
this.service = service;
this.helpers = new Helpers;
}
RosterProxy.prototype.get = function(callback) {
var iq, self = this,
items, userId, contacts = {};
iq = $iq({
from: connection.jid,
type: 'get',
id: connection.getUniqueId('roster')
}).c('query', {
xmlns: Strophe.NS.ROSTER
});
connection.sendIQ(iq, function(stanza) {
items = stanza.getElementsByTagName('item');
for (var i = 0, len = items.length; i < len; i++) {
userId = self.helpers.getIdFromNode(items[i].getAttribute('jid')).toString();
contacts[userId] = {
subscription: items[i].getAttribute('subscription'),
ask: items[i].getAttribute('ask') || null
};
// mutual subscription
if (items[i].getAttribute('ask') || items[i].getAttribute('subscription') !== 'none')
mutualSubscriptions[userId] = true;
}
callback(contacts);
});
};
RosterProxy.prototype.add = function(jid) {
this._sendRosterRequest({
jid: jid,
type: 'subscribe'
});
};
RosterProxy.prototype.confirm = function(jid) {
this._sendRosterRequest({
jid: jid,
type: 'subscribed'
});
};
RosterProxy.prototype.reject = function(jid) {
this._sendRosterRequest({
jid: jid,
type: 'unsubscribed'
});
};
RosterProxy.prototype.remove = function(jid) {
this._sendSubscriptionPresence({
jid: jid,
type: 'unsubscribe'
});
this._sendSubscriptionPresence({
jid: jid,
type: 'unsubscribed'
});
this._sendRosterRequest({
jid: jid,
subscription: 'remove',
type: 'unsubscribe'
});
};
RosterProxy.prototype._sendRosterRequest = function(params) {
var iq, attr = {},
userId, self = this;
iq = $iq({
from: connection.jid,
type: 'set',
id: connection.getUniqueId('roster')
}).c('query', {
xmlns: Strophe.NS.ROSTER
});
if (params.jid)
attr.jid = params.jid;
if (params.subscription)
attr.subscription = params.subscription;
iq.c('item', attr);
userId = self.helpers.getIdFromNode(params.jid).toString();
connection.sendIQ(iq, function() {
// subscriptions requests
switch (params.type) {
case 'subscribe':
self._sendSubscriptionPresence(params);
mutualSubscriptions[userId] = true;
break;
case 'subscribed':
self._sendSubscriptionPresence(params);
mutualSubscriptions[userId] = true;
params.type = 'subscribe';
self._sendSubscriptionPresence(params);
break;
case 'unsubscribed':
self._sendSubscriptionPresence(params);
break;
case 'unsubscribe':
delete mutualSubscriptions[userId];
params.type = 'unavailable';
self._sendSubscriptionPresence(params);
break;
}
});
};
RosterProxy.prototype._sendSubscriptionPresence = function(params) {
var pres, self = this;
pres = $pres({
to: params.jid,
type: params.type
});
connection.send(pres);
};
/* Chat module: Group Chat
*
* Multi-User Chat
* http://xmpp.org/extensions/xep-0045.html
*
---------------------------------------------------------------------- */
function MucProxy(service) {
this.service = service;
this.helpers = new Helpers;
}
MucProxy.prototype.join = function(jid, callback) {
var pres, self = this,
id = connection.getUniqueId('join');
pres = $pres({
from: connection.jid,
to: self.helpers.getRoomJid(jid),
id: id
}).c("x", {
xmlns: Strophe.NS.MUC
});
connection.addHandler(callback, null, 'presence', null, id);
connection.send(pres);
};
MucProxy.prototype.leave = function(jid, callback) {
var pres, self = this,
roomJid = self.helpers.getRoomJid(jid);
pres = $pres({
from: connection.jid,
to: roomJid,
type: 'unavailable'
});
connection.addHandler(callback, null, 'presence', 'unavailable', null, roomJid);
connection.send(pres);
};
/* Chat module: History
---------------------------------------------------------------------- */
// Dialogs
function DialogProxy(service) {
this.service = service;
this.helpers = new Helpers;
}
DialogProxy.prototype.list = function(params, callback) {
if (typeof params === 'function' && typeof callback === 'undefined') {
callback = params;
params = {};
}
if (config.debug) { console.log('DialogProxy.list', params); }
this.service.ajax({url: Utils.getUrl(dialogUrl), data: params}, callback);
};
DialogProxy.prototype.create = function(params, callback) {
if (config.debug) { console.log('DialogProxy.create', params); }
this.service.ajax({url: Utils.getUrl(dialogUrl), type: 'POST', data: params}, callback);
};
DialogProxy.prototype.update = function(id, params, callback) {
if (config.debug) { console.log('DialogProxy.update', id, params); }
this.service.ajax({url: Utils.getUrl(dialogUrl, id), type: 'PUT', data: params}, callback);
};
// Messages
function MessageProxy(service) {
this.service = service;
this.helpers = new Helpers;
}
MessageProxy.prototype.list = function(params, callback) {
if (config.debug) { console.log('MessageProxy.list', params); }
this.service.ajax({url: Utils.getUrl(messageUrl), data: params}, callback);
};
MessageProxy.prototype.update = function(id, params, callback) {
if (config.debug) { console.log('MessageProxy.update', id, params); }
this.service.ajax({url: Utils.getUrl(messageUrl, id), type: 'PUT', data: params}, callback);
};
MessageProxy.prototype.delete = function(id, callback) {
if (config.debug) { console.log('MessageProxy.delete', id); }
this.service.ajax({url: Utils.getUrl(messageUrl, id), type: 'DELETE', dataType: 'text'}, callback);
};
/* Helpers
---------------------------------------------------------------------- */
function Helpers() {}
Helpers.prototype = {
getUserJid: function(id, appId) {
return id + '-' + appId + '@' + config.endpoints.chat;
},
getIdFromNode: function(jid) {
return parseInt(Strophe.getNodeFromJid(jid).split('-')[0]);
},
getRoomJid: function(jid) {
return jid + '/' + this.getIdFromNode(connection.jid);
},
getIdFromResource: function(jid) {
return parseInt(Strophe.getResourceFromJid(jid));
},
getUniqueId: function(suffix) {
return connection.getUniqueId(suffix);
}
};
/* Private
---------------------------------------------------------------------- */
function trace(text) {
// if (config.debug) {
console.log('[QBChat]:', text);
// }
}
function getError(code, detail) {
var errorMsg = {
code: code,
status: 'error',
message: code === 401 ? 'Unauthorized' : 'Unprocessable Entity',
detail: detail
};
trace(detail);
return errorMsg;
}
function getLocalTime() {
return (new Date).toTimeString().split(' ')[0];
}
},{"../../lib/strophe/strophe.min":12,"../qbConfig":8,"../qbUtils":10}],3:[function(require,module,exports){
/*
* QuickBlox JavaScript SDK
*
* Content module
*
* For an overview of this module and what it can be used for
* see http://quickblox.com/modules/content
*
* The API itself is described at http://quickblox.com/developers/Content
*
*/
// Browserify exports and dependencies
module.exports = ContentProxy;
var config = require('../qbConfig');
var Utils = require('../qbUtils');
var taggedForUserUrl = config.urls.blobs + '/tagged';
function ContentProxy(service) {
this.service = service;
}
ContentProxy.prototype.create = function(params, callback){
if (config.debug) { console.log('ContentProxy.create', params);}
this.service.ajax({url: Utils.getUrl(config.urls.blobs), data: {blob:params}, type: 'POST'}, function(err,result){
if (err){ callback(err, null); }
else { callback (err, result.blob); }
});
};
ContentProxy.prototype.list = function(params, callback){
if (typeof params === 'function' && typeof callback ==='undefined') {
callback = params;
params = null;
}
this.service.ajax({url: Utils.getUrl(config.urls.blobs)}, function(err,result){
if (err){ callback(err, null); }
else { callback (err, result); }
});
};
ContentProxy.prototype.delete = function(id, callback){
this.service.ajax({url: Utils.getUrl(config.urls.blobs, id), type: 'DELETE', dataType: 'text'}, function(err, result) {
if (err) { callback(err,null); }
else { callback(null, true); }
});
};
ContentProxy.prototype.createAndUpload = function(params, callback){
var createParams= {}, file, name, type, size, fileId, _this = this;
if (config.debug) { console.log('ContentProxy.createAndUpload', params);}
file = params.file;
name = params.name || file.name;
type = params.type || file.type;
size = file.size;
createParams.name = name;
createParams.content_type = type;
if (params.public) { createParams.public = params.public; }
if (params.tag_list) { createParams.tag_list = params.tag_list; }
this.create(createParams, function(err,createResult){
if (err){ callback(err, null); }
else {
var uri = parseUri(createResult.blob_object_access.params), uploadParams = { url: uri.protocol + '://' + uri.host }, data = new FormData();
fileId = createResult.id;
Object.keys(uri.queryKey).forEach(function(val) {
data.append(val, decodeURIComponent(uri.queryKey[val]));
});
data.append('file', file, createResult.name);
uploadParams.data = data;
_this.upload(uploadParams, function(err, result) {
if (err) { callback(err, null); }
else {
createResult.path = result.Location;
_this.markUploaded({id: fileId, size: size}, function(err, result){
if (err) { callback(err, null);}
else {
callback(null, createResult);
}
});
}
});
}
});
};
ContentProxy.prototype.upload = function(params, callback){
this.service.ajax({url: params.url, data: params.data, dataType: 'xml',
contentType: false, processData: false, type: 'POST'}, function(err,xmlDoc){
if (err) { callback (err, null); }
else {
// AWS S3 doesn't respond with a JSON structure
// so parse the xml and return a JSON structure ourselves
var result = {}, rootElement = xmlDoc.documentElement, children = rootElement.childNodes, i, m;
for (i = 0, m = children.length; i < m ; i++){
result[children[i].nodeName] = children[i].childNodes[0].nodeValue;
}
if (config.debug) { console.log('result', result); }
callback (null, result);
}
});
};
ContentProxy.prototype.taggedForCurrentUser = function(callback) {
this.service.ajax({url: Utils.getUrl(taggedForUserUrl)}, function(err, result) {
if (err) { callback(err, null); }
else { callback(null, result); }
});
};
ContentProxy.prototype.markUploaded = function (params, callback) {
this.service.ajax({url: Utils.getUrl(config.urls.blobs, params.id + '/complete'), type: 'PUT', data: {size: params.size}, dataType: 'text' }, function(err, res){
if (err) { callback (err, null); }
else { callback (null, res); }
});
};
ContentProxy.prototype.getInfo = function (id, callback) {
this.service.ajax({url: Utils.getUrl(config.urls.blobs, id)}, function (err, res) {
if (err) { callback (err, null); }
else { callback (null, res); }
});
};
ContentProxy.prototype.getFile = function (uid, callback) {
this.service.ajax({url: Utils.getUrl(config.urls.blobs, uid)}, function (err, res) {
if (err) { callback (err, null); }
else { callback (null, res); }
});
};
ContentProxy.prototype.getFileUrl = function (id, callback) {
this.service.ajax({url: Utils.getUrl(config.urls.blobs, id + '/getblobobjectbyid'), type: 'POST'}, function (err, res) {
if (err) { callback (err, null); }
else { callback (null, res.blob_object_access.params); }
});
};
ContentProxy.prototype.update = function (params, callback) {
var data = {};
data.blob = {};
if (typeof params.name !== 'undefined') { data.blob.name = params.name; }
this.service.ajax({url: Utils.getUrl(config.urls.blobs, params.id), data: data}, function(err, res) {
if (err) { callback (err, null); }
else { callback (null, res); }
});
}
// parseUri 1.2.2
// (c) Steven Levithan <stevenlevithan.com>
// MIT License
// http://blog.stevenlevithan.com/archives/parseuri
function parseUri (str) {
var o = parseUri.options,
m = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
uri = {},
i = 14;
while (i--) {uri[o.key[i]] = m[i] || "";}
uri[o.q.name] = {};
uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
if ($1) {uri[o.q.name][$1] = $2;}
});
return uri;
}
parseUri.options = {
strictMode: false,
key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
q: {
name: "queryKey",
parser: /(?:^|&)([^&=]*)=?([^&]*)/g
},
parser: {
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
}
};
},{"../qbConfig":8,"../qbUtils":10}],4:[function(require,module,exports){
/*
* QuickBlox JavaScript SDK
*
* Custom Objects module
*
*/
// Browserify exports and dependencies
module.exports = DataProxy;
var config = require('../qbConfig');
var Utils = require('../qbUtils');
function DataProxy(service){
this.service = service;
if (config.debug) { console.log("LocationProxy", service); }
}
DataProxy.prototype.create = function(className, data, callback) {
if (config.debug) { console.log('DataProxy.create', className, data);}
this.service.ajax({url: Utils.getUrl(config.urls.data, className), data: data, type: 'POST'}, function(err,res){
if (err){ callback(err, null); }
else { callback (err, res); }
});
};
DataProxy.prototype.list = function(className, filters, callback) {
// make filters an optional parameter
if (typeof callback === 'undefined' && typeof filters === 'function') {
callback = filters;
filters = null;
}
if (config.debug) { console.log('DataProxy.list', className, filters);}
this.service.ajax({url: Utils.getUrl(config.urls.data, className), data: filters}, function(err,result){
if (err){ callback(err, null); }
else { callback (err, result); }
});
};
DataProxy.prototype.update = function(className, data, callback) {
if (config.debug) { console.log('DataProxy.update', className, data);}
this.service.ajax({url: Utils.getUrl(config.urls.data, className + '/' + data._id), data: data, type: 'PUT'}, function(err,result){
if (err){ callback(err, null); }
else { callback (err, result); }
});
};
DataProxy.prototype.delete = function(className, id, callback) {
if (config.debug) { console.log('DataProxy.delete', className, id);}
this.service.ajax({url: Utils.getUrl(config.urls.data, className + '/' + id), type: 'DELETE', dataType: 'text'},
function(err,result){
if (err){ callback(err, null); }
else { callback (err, true); }
});
};
DataProxy.prototype.uploadFile = function(className, params, callback) {
var formData;
if (config.debug) { console.log('DataProxy.uploadFile', className, params);}
formData = new FormData();
formData.append('field_name', params.field_name);
formData.append('file', params.file);
this.service.ajax({url: Utils.getUrl(config.urls.data, className + '/' + params.id + '/file'), data: formData,
contentType: false, processData: false, type:'POST'}, function(err, result){
if (err) { callback(err, null);}
else { callback (err, result); }
});
};
DataProxy.prototype.updateFile = function(className, params, callback) {
var formData;
if (config.debug) { console.log('DataProxy.updateFile', className, params);}
formData = new FormData();
formData.append('field_name', params.field_name);
formData.append('file', params.file);
this.service.ajax({url: Utils.getUrl(config.urls.data, className + '/' + params.id + '/file'), data: formData,
contentType: false, processData: false, type: 'POST'}, function(err, result) {
if (err) { callback (err, null); }
else { callback (err, result); }
});
};
DataProxy.prototype.downloadFile = function(className, params, callback) {
if (config.debug) { console.log('DataProxy.downloadFile', className, params); }
var result = Utils.getUrl(config.urls.data, className + '/' + params.id + '/file');
result += '?field_name=' + params.field_name + '&token=' + this.service.getSession().token;
callback(null, result);
};
DataProxy.prototype.deleteFile = function(className, params, callback) {
if (config.debug) { console.log('DataProxy.deleteFile', className, params);}
this.service.ajax({url: Utils.getUrl(config.urls.data, className + '/' + params.id + '/file'), data: {field_name: params.field_name},
dataType: 'text', type: 'DELETE'}, function(err, result) {
if (err) { callback (err, null); }
else { callback (err, true); }
});
};
},{"../qbConfig":8,"../qbUtils":10}],5:[function(require,module,exports){
/*
* QuickBlox JavaScript SDK
*
* Location module
*
*/
// Browserify exports and dependencies
module.exports = LocationProxy;
var config = require('../qbConfig');
var Utils = require('../qbUtils');
var geoFindUrl = config.urls.geodata + '/find';
function LocationProxy(service){
this.service = service;
this.geodata = new GeoProxy(service);
this.places = new PlacesProxy(service);
if (config.debug) { console.log("LocationProxy", service); }
}
function GeoProxy(service){
this.service = service;
}
GeoProxy.prototype.create = function(params, callback){
if (config.debug) { console.log('GeoProxy.create', {geo_data: params});}
this.service.ajax({url: Utils.getUrl(config.urls.geodata), data: {geo_data: params}, type: 'POST'}, function(err,result){
if (err){ callback(err, null); }
else { callback (err, result.geo_datum); }
});
};
GeoProxy.prototype.update = function(params, callback){
var allowedProps = ['longitude', 'latitude', 'status'], prop, msg = {};
for (prop in params) {
if (params.hasOwnProperty(prop)) {
if (allowedProps.indexOf(prop)>0) {
msg[prop] = params[prop];
}
}
}
if (config.debug) { console.log('GeoProxy.create', params);}
this.service.ajax({url: Utils.getUrl(config.urls.geodata, params.id), data: {geo_data:msg}, type: 'PUT'},
function(err,res){
if (err) { callback(err,null);}
else { callback(err, res.geo_datum);}
});
};
GeoProxy.prototype.get = function(id, callback){
if (config.debug) { console.log('GeoProxy.get', id);}
this.service.ajax({url: Utils.getUrl(config.urls.geodata, id)}, function(err,result){
if (err) { callback (err, null); }
else { callback(null, result.geo_datum); }
});
};
GeoProxy.prototype.list = function(params, callback){
if (typeof params === 'function') {
callback = params;
params = undefined;
}
if (config.debug) { console.log('GeoProxy.find', params);}
this.service.ajax({url: Utils.getUrl(geoFindUrl), data: params}, callback);
};
GeoProxy.prototype.delete = function(id, callback){
if (config.debug) { console.log('GeoProxy.delete', id); }
this.service.ajax({url: Utils.getUrl(config.urls.geodata, id), type: 'DELETE', dataType: 'text'},
function(err,res){
if (err) { callback(err, null);}
else { callback(null, true);}
});
};
GeoProxy.prototype.purge = function(days, callback){
if (config.debug) { console.log('GeoProxy.purge', days); }
this.service.ajax({url: Utils.getUrl(config.urls.geodata), data: {days: days}, type: 'DELETE', dataType: 'text'},
function(err, res){
if (err) { callback(err, null);}
else { callback(null, true);}
});
};
function PlacesProxy(service) {
this.service = service;
}
PlacesProxy.prototype.list = function(params, callback){
if (config.debug) { console.log('PlacesProxy.list', params);}
this.service.ajax({url: Utils.getUrl(config.urls.places)}, callback);
};
PlacesProxy.prototype.create = function(params, callback){
if (config.debug) { console.log('PlacesProxy.create', params);}
this.service.ajax({url: Utils.getUrl(config.urls.places), data: {place:params}, type: 'POST'}, callback);
};
PlacesProxy.prototype.get = function(id, callback){
if (config.debug) { console.log('PlacesProxy.get', id);}
this.service.ajax({url: Utils.getUrl(config.urls.places, id)}, callback);
};
PlacesProxy.prototype.update = function(place, callback){
if (config.debug) { console.log('PlacesProxy.update', place);}
this.service.ajax({url: Utils.getUrl(config.urls.places, place.id), data: {place: place}, type: 'PUT'} , callback);
};
PlacesProxy.prototype.delete = function(id, callback){
if (config.debug) { console.log('PlacesProxy.delete', id);}
this.service.ajax({url: Utils.getUrl(config.urls.places, id), type: 'DELETE', dataType: 'text'}, callback);
};
},{"../qbConfig":8,"../qbUtils":10}],6:[function(require,module,exports){
/*
* QuickBlox JavaScript SDK
*
* Messages Module
*
*/
// broserify export and dependencies
// Browserify exports and dependencies
module.exports = MessagesProxy;
var config = require('../qbConfig');
var Utils = require('../qbUtils');
function MessagesProxy(service) {
this.service = service;
this.tokens = new TokensProxy(service);
this.subscriptions = new SubscriptionsProxy(service);
this.events = new EventsProxy(service);
}
// Push Tokens
function TokensProxy(service){
this.service = service;
}
TokensProxy.prototype.create = function(params, callback){
var message = {
push_token: {
environment: params.environment,
client_identification_sequence: params.client_identification_sequence
},
device: { platform: params.platform, udid: params.udid}
};
if (config.debug) { console.log('TokensProxy.create', message);}
this.service.ajax({url: Utils.getUrl(config.urls.pushtokens), type: 'POST', data: message},
function(err, data){
if (err) { callback(err, null);}
else { callback(null, data.push_token); }
});
};
TokensProxy.prototype.delete = function(id, callback) {
if (config.debug) { console.log('MessageProxy.deletePushToken', id); }
this.service.ajax({url: Utils.getUrl(config.urls.pushtokens, id), type: 'DELETE', dataType:'text'},
function (err, res) {
if (err) {callback(err, null);}
else {callback(null, true);}
});
};
// Subscriptions
function SubscriptionsProxy(service){
this.service = service;
}
SubscriptionsProxy.prototype.create = function(params, callback) {
if (config.debug) { console.log('MessageProxy.createSubscription', params); }
this.service.ajax({url: Utils.getUrl(config.urls.subscriptions), type: 'POST', data: params}, callback);
};
SubscriptionsProxy.prototype.list = function(callback) {
if (config.debug) { console.log('MessageProxy.listSubscription'); }
this.service.ajax({url: Utils.getUrl(config.urls.subscriptions)}, callback);
};
SubscriptionsProxy.prototype.delete = function(id, callback) {
if (config.debug) { console.log('MessageProxy.deleteSubscription', id); }
this.service.ajax({url: Utils.getUrl(config.urls.subscriptions, id), type: 'DELETE', dataType:'text'},
function(err, res){
if (err) { callback(err, null);}
else { callback(null, true);}
});
};
// Events
function EventsProxy(service){
this.service = service;
}
EventsProxy.prototype.create = function(params, callback) {
if (config.debug) { console.log('MessageProxy.createEvent', params); }
var message = {event: params};
this.service.ajax({url: Utils.getUrl(config.urls.events), type: 'POST', data: message}, callback);
};
EventsProxy.prototype.list = function(callback) {
if (config.debug) { console.log('MessageProxy.listEvents'); }
this.service.ajax({url: Utils.getUrl(config.urls.events)}, callback);
};
EventsProxy.prototype.get = function(id, callback) {
if (config.debug) { console.log('MessageProxy.getEvents', id); }
this.service.ajax({url: Utils.getUrl(config.urls.events, id)}, callback);
};
EventsProxy.prototype.update = function(params, callback) {
if (config.debug) { console.log('MessageProxy.createEvent', params); }
var message = {event: params};
this.service.ajax({url: Utils.getUrl(config.urls.events, params.id), type: 'PUT', data: message}, callback);
};
EventsProxy.prototype.delete = function(id, callback) {
if (config.debug) { console.log('MessageProxy.deleteEvent', id); }
this.service.ajax({url: Utils.getUrl(config.urls.events, id), type: 'DELETE'}, callback);
};
},{"../qbConfig":8,"../qbUtils":10}],7:[function(require,module,exports){
/*
* QuickBlox JavaScript SDK
*
* Users Module
*
*/
// Browserify exports and dependencies
module.exports = UsersProxy;
var config = require('../qbConfig');
var Utils = require('../qbUtils');
var DATE_FIELDS = ['created_at', 'updated_at', 'last_request_at'];
var NUMBER_FIELDS = ['id', 'external_user_id'];
var resetPasswordUrl = config.urls.users + '/password/reset';
function UsersProxy(service) {
this.service = service;
}
UsersProxy.prototype.listUsers = function(params, callback) {
var message = {}, filters = [], item;
if (typeof params === 'function' && typeof callback === 'undefined') {
callback = params;
params = {};
}
if (params.filter) {
if (params.filter instanceof Array) {
params.filter.forEach(function(el) {
item = generateFilter(el);
filters.push(item);
});
} else {
item = generateFilter(params.filter);
filters.push(item);
}
message.filter = filters;
}
if (params.order) {
message.order = generateOrder(params.order);
}
if (params.page) {
message.page = params.page;
}
if (params.per_page) {
message.per_page = params.per_page;
}
if (config.debug) { console.log('UsersProxy.listUsers', message); }
this.service.ajax({url: Utils.getUrl(config.urls.users), data: message}, callback);
};
UsersProxy.prototype.get = function(params, callback) {
var url;
if (typeof params === 'number') {
url = params;
params = {};
} else {
if (params.login) {
url = 'by_login';
} else if (params.full_name) {
url = 'by_full_name';
} else if (params.facebook_id) {
url = 'by_facebook_id';
} else if (params.twitter_id) {
url = 'by_twitter_id';
} else if (params.email) {
url = 'by_email';
} else if (params.tags) {
url = 'by_tags';
} else if (params.external) {
url = 'external/' + params.external;
params = {};
}
}
if (config.debug) { console.log('UsersProxy.get', params); }
this.service.ajax({url: Utils.getUrl(config.urls.users, url), data: params},
function(err, res) {
if (err) { callback(err, null); }
else { callback(null, res.user || res); }
});
};
UsersProxy.prototype.create = function(params, callback) {
if (config.debug) { console.log('UsersProxy.create', params); }
this.service.ajax({url: Utils.getUrl(config.urls.users), type: 'POST', data: {user: params}},
function(err, res) {
if (err) { callback(err, null); }
else { callback(null, res.user); }
});
};
UsersProxy.prototype.update = function(id, params, callback) {
if (config.debug) { console.log('UsersProxy.update', id, params); }
this.service.ajax({url: Utils.getUrl(config.urls.users, id), type: 'PUT', data: {user: params}},
function(err, res) {
if (err) { callback(err, null); }
else { callback(null, res.user); }
});
};
UsersProxy.prototype.delete = function(params, callback) {
var url;
if (typeof params === 'number') {
url = params;
} else {
if (params.external) {
url = 'external/' + params.external;
}
}
if (config.debug) { console.log('UsersProxy.delete', url); }
this.service.ajax({url: Utils.getUrl(config.urls.users, url), type: 'DELETE', dataType: 'text'}, callback);
};
UsersProxy.prototype.resetPassword = function(email, callback) {
if (config.debug) { console.log('UsersProxy.resetPassword', email); }
this.service.ajax({url: Utils.getUrl(resetPasswordUrl), data: {email: email}}, callback);
};
/* Private
---------------------------------------------------------------------- */
function generateFilter(obj) {
var type = obj.field in DATE_FIELDS ? 'date' : typeof obj.value;
if (obj.value instanceof Array) {
if (type == 'object') {
type = typeof obj.value[0];
}
obj.value = obj.value.toString();
}
return [type, obj.field, obj.param, obj.value].join(' ');
}
function generateOrder(obj) {
var type = obj.field in DATE_FIELDS ? 'date' : obj.field in NUMBER_FIELDS ? 'number' : 'string';
return [obj.sort, type, obj.field].join(' ');
}
},{"../qbConfig":8,"../qbUtils":10}],8:[function(require,module,exports){
/*
* QuickBlox JavaScript SDK
*
* Configuration Module
*
*/
var config = {
version: '1.3.0',
creds: {
appId: '',
authKey: '',
authSecret: ''
},
endpoints: {
api: 'api.quickblox.com',
chat: 'chat.quickblox.com',
muc: 'muc.chat.quickblox.com',
turn: 'turnserver.quickblox.com',
s3Bucket: 'qbprod'
},
chatProtocol: {
//bosh: 'http://chat.quickblox.com:8080',
bosh: 'https://chat.quickblox.com:8081', // With SSL
websocket: 'ws://chat.quickblox.com:5290',
active: 1
},
urls: {
session: 'session',
login: 'login',
users: 'users',
chat: 'chat',
blobs: 'blobs',
geodata: 'geodata',
places: 'places',
pushtokens: 'push_tokens',
subscriptions: 'subscriptions',
events: 'events',
data: 'data',
type: '.json'
},
ssl: true,
debug: false
};
// Browserify exports
module.exports = config;
},{}],9:[function(require,module,exports){
/*
* QuickBlox JavaScript SDK
*
* Proxy Module
*
*/
// Browserify exports and dependencies
module.exports = ServiceProxy;
var config = require('./qbConfig');
// For server-side applications through using npm package 'quickblox' you should include the following block
/*var jsdom = require('jsdom');
var XMLHttpRequest = require('xmlhttprequest').XMLHttpRequest;
var jQuery = require('jquery/dist/jquery.min')(jsdom.jsdom().createWindow());
jQuery.support.cors = true;
jQuery.ajaxSettings.xhr = function() {
return new XMLHttpRequest;
};*/
function ServiceProxy() {
this.qbInst = {
config: config,
session: null
};
if (config.debug) { console.log("ServiceProxy", this.qbInst); }
}
ServiceProxy.prototype.setSession = function(session) {
this.qbInst.session = session;
};
ServiceProxy.prototype.getSession = function() {
return this.qbInst.session;
};
ServiceProxy.prototype.ajax = function(params, callback) {
if (config.debug) { console.log('ServiceProxy', params.type || 'GET', params); }
var _this = this;
var ajaxCall = {
url: params.url,
type: params.type || 'GET',
dataType: params.dataType || 'json',
data: params.data || ' ',
beforeSend: function(jqXHR, settings) {
if (config.debug) { console.log('ServiceProxy.ajax beforeSend', jqXHR, settings); }
if (settings.url.indexOf('://' + config.endpoints.s3Bucket) === -1) {
console.log('setting headers on request to ' + settings.url);
if (_this.qbInst.session && _this.qbInst.session.token) {
jqXHR.setRequestHeader('QB-Token', _this.qbInst.session.token);
}
}
},
success: function(data, status, jqHXR) {
if (config.debug) { console.log('ServiceProxy.ajax success', data); }
callback(null, data);
},
error: function(jqHXR, status, error) {
if (config.debug) { console.log('ServiceProxy.ajax error', jqHXR.status, error, jqHXR.responseText); }
var errorMsg = {
code: jqHXR.status,
status: status,
message: error,
detail: jqHXR.responseText
};
callback(errorMsg, null);
}
};
// Optional - for example 'multipart/form-data' when sending a file.
// Default is 'application/x-www-form-urlencoded; charset=UTF-8'
if (typeof params.contentType === 'boolean' || typeof params.contentType === 'string') { ajaxCall.contentType = params.contentType; }
if (typeof params.processData === 'boolean') { ajaxCall.processData = params.processData; }
jQuery.ajax( ajaxCall );
};
},{"./qbConfig":8}],10:[function(require,module,exports){
/*
* QuickBlox JavaScript SDK
*
* QuickBlox Utilities
*
*/
// Browserify exports and dependencies
var config = require('./qbConfig');
exports.randomNonce = function() {
return Math.floor(Math.random() * 10000);
};
exports.unixTime = function() {
return Math.floor(Date.now() / 1000);
};
exports.getUrl = function(base, id) {
var protocol = config.ssl ? 'https://' : 'http://';
var resource = id ? '/' + id : '';
return protocol + config.endpoints.api + '/' + base + resource + config.urls.type;
};
},{"./qbConfig":8}],11:[function(require,module,exports){
/*
* QuickBlox JavaScript SDK
*
* Main SDK Module
*
* Provides a window scoped variable (QB) for use in browsers.
* Also exports QuickBlox for using with node.js, browserify, etc.
*
*/
// Browserify dependencies
var config = require('./qbConfig');
var Proxy = require('./qbProxy');
var Auth = require('./modules/qbAuth');
var Users = require('./modules/qbUsers');
var Chat = require('./modules/qbChat');
var Content = require('./modules/qbContent');
var Location = require('./modules/qbLocation');
var Messages = require('./modules/qbMessages');
var Data = require('./modules/qbData');
// Creating a window scoped QB instance
if (typeof window !== 'undefined' && typeof window.QB === 'undefined') {
window.QB = new QuickBlox();
}
// Actual QuickBlox API starts here
function QuickBlox() {}
QuickBlox.prototype.init = function(appId, authKey, authSecret, debug) {
this.service = new Proxy();
this.auth = new Auth(this.service);
this.users = new Users(this.service);
this.chat = new Chat(this.service);
this.content = new Content(this.service);
this.location = new Location(this.service);
this.messages = new Messages(this.service);
this.data = new Data(this.service);
// Initialization by outside token
if (typeof appId === 'string' && !authKey && !authSecret) {
this.service.setSession({ token: appId });
appId = '';
}
config.creds.appId = appId;
config.creds.authKey = authKey;
config.creds.authSecret = authSecret;
if (debug) {
config.debug = debug;
console.log('QuickBlox.init', this);
}
};
QuickBlox.prototype.createSession = function(params, callback) {
this.auth.createSession(params, callback);
};
QuickBlox.prototype.destroySession = function(callback) {
this.auth.destroySession(callback);
};
QuickBlox.prototype.login = function(params, callback) {
this.auth.login(params, callback);
};
QuickBlox.prototype.logout = function(callback) {
this.auth.logout(callback);
};
// Browserify exports
module.exports = (typeof window === 'undefined') ? new QuickBlox() : QuickBlox;
},{"./modules/qbAuth":1,"./modules/qbChat":2,"./modules/qbContent":3,"./modules/qbData":4,"./modules/qbLocation":5,"./modules/qbMessages":6,"./modules/qbUsers":7,"./qbConfig":8,"./qbProxy":9}],12:[function(require,module,exports){
// Browserify exports start
module.exports=function(){function b(a){return n(f(l(a),a.length*8))}function c(a){return m(f(l(a),a.length*8))}function d(a,b){return n(i(a,b))}function e(a,b){return m(i(a,b))}function f(a,b){a[b>>5]|=128<<24-b%32,a[(b+64>>9<<4)+15]=b;var c=new Array(80),d=1732584193,e=-271733879,f=-1732584194,i=271733878,l=-1009589776,m,n,o,p,q,r,s,t;for(m=0;m<a.length;m+=16){p=d,q=e,r=f,s=i,t=l;for(n=0;n<80;n++)n<16?c[n]=a[m+n]:c[n]=k(c[n-3]^c[n-8]^c[n-14]^c[n-16],1),o=j(j(k(d,5),g(n,e,f,i)),j(j(l,c[n]),h(n))),l=i,i=f,f=k(e,30),e=d,d=o;d=j(d,p),e=j(e,q),f=j(f,r),i=j(i,s),l=j(l,t)}return[d,e,f,i,l]}function g(a,b,c,d){return a<20?b&c|~b&d:a<40?b^c^d:a<60?b&c|b&d|c&d:b^c^d}function h(a){return a<20?1518500249:a<40?1859775393:a<60?-1894007588:-899497514}function i(a,b){var c=l(a);c.length>16&&(c=f(c,a.length*8));var d=new Array(16),e=new Array(16);for(var g=0;g<16;g++)d[g]=c[g]^909522486,e[g]=c[g]^1549556828;var h=f(d.concat(l(b)),512+b.length*8);return f(e.concat(h),672)}function j(a,b){var c=(a&65535)+(b&65535),d=(a>>16)+(b>>16)+(c>>16);return d<<16|c&65535}function k(a,b){return a<<b|a>>>32-b}function l(a){var b=[],c=255;for(var d=0;d<a.length*8;d+=8)b[d>>5]|=(a.charCodeAt(d/8)&c)<<24-d%32;return b}function m(a){var b="",c=255;for(var d=0;d<a.length*32;d+=8)b+=String.fromCharCode(a[d>>5]>>>24-d%32&c);return b}function n(a){var b="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",c="",d,e;for(var f=0;f<a.length*4;f+=3){d=(a[f>>2]>>8*(3-f%4)&255)<<16|(a[f+1>>2]>>8*(3-(f+1)%4)&255)<<8|a[f+2>>2]>>8*(3-(f+2)%4)&255;for(e=0;e<4;e++)f*8+e*6>a.length*32?c+="=":c+=b.charAt(d>>6*(3-e)&63)}return c}var a=function(){var a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",b={encode:function(b){var c="",d,e,f,g,h,i,j,k=0;do d=b.charCodeAt(k++),e=b.charCodeAt(k++),f=b.charCodeAt(k++),g=d>>2,h=(d&3)<<4|e>>4,i=(e&15)<<2|f>>6,j=f&63,isNaN(e)?i=j=64:isNaN(f)&&(j=64),c=c+a.charAt(g)+a.charAt(h)+a.charAt(i)+a.charAt(j);while(k<b.length);return c},decode:function(b){var c="",d,e,f,g,h,i,j,k=0;b=b.replace(/[^A-Za-z0-9\+\/\=]/g,"");do g=a.indexOf(b.charAt(k++)),h=a.indexOf(b.charAt(k++)),i=a.indexOf(b.charAt(k++)),j=a.indexOf(b.charAt(k++)),d=g<<2|h>>4,e=(h&15)<<4|i>>2,f=(i&3)<<6|j,c+=String.fromCharCode(d),i!=64&&(c+=String.fromCharCode(e)),j!=64&&(c+=String.fromCharCode(f));while(k<b.length);return c}};return b}(),o=function(){var a=function(a,b){var c=(a&65535)+(b&65535),d=(a>>16)+(b>>16)+(c>>16);return d<<16|c&65535},b=function(a,b){return a<<b|a>>>32-b},c=function(a){var b=[];for(var c=0;c<a.length*8;c+=8)b[c>>5]|=(a.charCodeAt(c/8)&255)<<c%32;return b},d=function(a){var b="";for(var c=0;c<a.length*32;c+=8)b+=String.fromCharCode(a[c>>5]>>>c%32&255);return b},e=function(a){var b="0123456789abcdef",c="";for(var d=0;d<a.length*4;d++)c+=b.charAt(a[d>>2]>>d%4*8+4&15)+b.charAt(a[d>>2]>>d%4*8&15);return c},f=function(c,d,e,f,g,h){return a(b(a(a(d,c),a(f,h)),g),e)},g=function(a,b,c,d,e,g,h){return f(b&c|~b&d,a,b,e,g,h)},h=function(a,b,c,d,e,g,h){return f(b&d|c&~d,a,b,e,g,h)},i=function(a,b,c,d,e,g,h){return f(b^c^d,a,b,e,g,h)},j=function(a,b,c,d,e,g,h){return f(c^(b|~d),a,b,e,g,h)},k=function(b,c){b[c>>5]|=128<<c%32,b[(c+64>>>9<<4)+14]=c;var d=1732584193,e=-271733879,f=-1732584194,k=271733878,l,m,n,o;for(var p=0;p<b.length;p+=16)l=d,m=e,n=f,o=k,d=g(d,e,f,k,b[p+0],7,-680876936),k=g(k,d,e,f,b[p+1],12,-389564586),f=g(f,k,d,e,b[p+2],17,606105819),e=g(e,f,k,d,b[p+3],22,-1044525330),d=g(d,e,f,k,b[p+4],7,-176418897),k=g(k,d,e,f,b[p+5],12,1200080426),f=g(f,k,d,e,b[p+6],17,-1473231341),e=g(e,f,k,d,b[p+7],22,-45705983),d=g(d,e,f,k,b[p+8],7,1770035416),k=g(k,d,e,f,b[p+9],12,-1958414417),f=g(f,k,d,e,b[p+10],17,-42063),e=g(e,f,k,d,b[p+11],22,-1990404162),d=g(d,e,f,k,b[p+12],7,1804603682),k=g(k,d,e,f,b[p+13],12,-40341101),f=g(f,k,d,e,b[p+14],17,-1502002290),e=g(e,f,k,d,b[p+15],22,1236535329),d=h(d,e,f,k,b[p+1],5,-165796510),k=h(k,d,e,f,b[p+6],9,-1069501632),f=h(f,k,d,e,b[p+11],14,643717713),e=h(e,f,k,d,b[p+0],20,-373897302),d=h(d,e,f,k,b[p+5],5,-701558691),k=h(k,d,e,f,b[p+10],9,38016083),f=h(f,k,d,e,b[p+15],14,-660478335),e=h(e,f,k,d,b[p+4],20,-405537848),d=h(d,e,f,k,b[p+9],5,568446438),k=h(k,d,e,f,b[p+14],9,-1019803690),f=h(f,k,d,e,b[p+3],14,-187363961),e=h(e,f,k,d,b[p+8],20,1163531501),d=h(d,e,f,k,b[p+13],5,-1444681467),k=h(k,d,e,f,b[p+2],9,-51403784),f=h(f,k,d,e,b[p+7],14,1735328473),e=h(e,f,k,d,b[p+12],20,-1926607734),d=i(d,e,f,k,b[p+5],4,-378558),k=i(k,d,e,f,b[p+8],11,-2022574463),f=i(f,k,d,e,b[p+11],16,1839030562),e=i(e,f,k,d,b[p+14],23,-35309556),d=i(d,e,f,k,b[p+1],4,-1530992060),k=i(k,d,e,f,b[p+4],11,1272893353),f=i(f,k,d,e,b[p+7],16,-155497632),e=i(e,f,k,d,b[p+10],23,-1094730640),d=i(d,e,f,k,b[p+13],4,681279174),k=i(k,d,e,f,b[p+0],11,-358537222),f=i(f,k,d,e,b[p+3],16,-722521979),e=i(e,f,k,d,b[p+6],23,76029189),d=i(d,e,f,k,b[p+9],4,-640364487),k=i(k,d,e,f,b[p+12],11,-421815835),f=i(f,k,d,e,b[p+15],16,530742520),e=i(e,f,k,d,b[p+2],23,-995338651),d=j(d,e,f,k,b[p+0],6,-198630844),k=j(k,d,e,f,b[p+7],10,1126891415),f=j(f,k,d,e,b[p+14],15,-1416354905),e=j(e,f,k,d,b[p+5],21,-57434055),d=j(d,e,f,k,b[p+12],6,1700485571),k=j(k,d,e,f,b[p+3],10,-1894986606),f=j(f,k,d,e,b[p+10],15,-1051523),e=j(e,f,k,d,b[p+1],21,-2054922799),d=j(d,e,f,k,b[p+8],6,1873313359),k=j(k,d,e,f,b[p+15],10,-30611744),f=j(f,k,d,e,b[p+6],15,-1560198380),e=j(e,f,k,d,b[p+13],21,1309151649),d=j(d,e,f,k,b[p+4],6,-145523070),k=j(k,d,e,f,b[p+11],10,-1120210379),f=j(f,k,d,e,b[p+2],15,718787259),e=j(e,f,k,d,b[p+9],21,-343485551),d=a(d,l),e=a(e,m),f=a(f,n),k=a(k,o);return[d,e,f,k]},l={hexdigest:function(a){return e(k(c(a),a.length*8))},hash:function(a){return d(k(c(a),a.length*8))}};return l}();Function.prototype.bind||(Function.prototype.bind=function(a){var b=this,c=Array.prototype.slice,d=Array.prototype.concat,e=c.call(arguments,1);return function(){return b.apply(a?a:this,d.call(e,c.call(arguments,0)))}}),Array.prototype.indexOf||(Array.prototype.indexOf=function(a){var b=this.length,c=Number(arguments[1])||0;c=c<0?Math.ceil(c):Math.floor(c),c<0&&(c+=b);for(;c<b;c++)if(c in this&&this[c]===a)return c;return-1}),function(b){function g(a,b){return new f.Builder(a,b)}function h(a){return new f.Builder("message",a)}function j(a){return new f.Builder("iq",a)}function k(a){return new f.Builder("presence",a)}var f;f={VERSION:"1.1.3",NS:{HTTPBIND:"http://jabber.org/protocol/httpbind",BOSH:"urn:xmpp:xbosh",CLIENT:"jabber:client",AUTH:"jabber:iq:auth",ROSTER:"jabber:iq:roster",PROFILE:"jabber:iq:profile",DISCO_INFO:"http://jabber.org/protocol/disco#info",DISCO_ITEMS:"http://jabber.org/protocol/disco#items",MUC:"http://jabber.org/protocol/muc",SASL:"urn:ietf:params:xml:ns:xmpp-sasl",STREAM:"http://etherx.jabber.org/streams",BIND:"urn:ietf:params:xml:ns:xmpp-bind",SESSION:"urn:ietf:params:xml:ns:xmpp-session",VERSION:"jabber:iq:version",STANZAS:"urn:ietf:params:xml:ns:xmpp-stanzas",XHTML_IM:"http://jabber.org/protocol/xhtml-im",XHTML:"http://www.w3.org/1999/xhtml"},XHTML:{tags:["a","blockquote","br","cite","em","img","li","ol","p","span","strong","ul","body"],attributes:{a:["href"],blockquote:["style"],br:[],cite:["style"],em:[],img:["src","alt","style","height","width"],li:["style"],ol:["style"],p:["style"],span:["style"],strong:[],ul:["style"],body:[]},css:["background-color","color","font-family","font-size","font-style","font-weight","margin-left","margin-right","text-align","text-decoration"],validTag:function(a){for(var b=0;b<f.XHTML.tags.length;b++)if(a==f.XHTML.tags[b])return!0;return!1},validAttribute:function(a,b){if(typeof f.XHTML.attributes[a]!="undefined"&&f.XHTML.attributes[a].length>0)for(var c=0;c<f.XHTML.attributes[a].length;c++)if(b==f.XHTML.attributes[a][c])return!0;return!1},validCSS:function(a){for(var b=0;b<f.XHTML.css.length;b++)if(a==f.XHTML.css[b])return!0;return!1}},Status:{ERROR:0,CONNECTING:1,CONNFAIL:2,AUTHENTICATING:3,AUTHFAIL:4,CONNECTED:5,DISCONNECTED:6,DISCONNECTING:7,ATTACHED:8},LogLevel:{DEBUG:0,INFO:1,WARN:2,ERROR:3,FATAL:4},ElementType:{NORMAL:1,TEXT:3,CDATA:4,FRAGMENT:11},TIMEOUT:1.1,SECONDARY_TIMEOUT:.1,addNamespace:function(a,b){f.NS[a]=b},forEachChild:function(a,b,c){var d,e;for(d=0;d<a.childNodes.length;d++)e=a.childNodes[d],e.nodeType==f.ElementType.NORMAL&&(!b||this.isTagEqual(e,b))&&c(e)},isTagEqual:function(a,b){return a.tagName.toLowerCase()==b.toLowerCase()},_xmlGenerator:null,_makeGenerator:function(){var a;return document.implementation.createDocument===undefined||document.implementation.createDocument&&document.documentMode&&document.documentMode<10?(a=this._getIEXmlDom(),a.appendChild(a.createElement("strophe"))):a=document.implementation.createDocument("jabber:client","strophe",null),a},xmlGenerator:function(){return f._xmlGenerator||(f._xmlGenerator=f._makeGenerator()),f._xmlGenerator},_getIEXmlDom:function(){var a=null,b=["Msxml2.DOMDocument.6.0","Msxml2.DOMDocument.5.0","Msxml2.DOMDocument.4.0","MSXML2.DOMDocument.3.0","MSXML2.DOMDocument","MSXML.DOMDocument","Microsoft.XMLDOM"];for(var c=0;c<b.length;c++){if(a!==null)break;try{a=new ActiveXObject(b[c])}catch(d){a=null}}return a},xmlElement:function(a){if(!a)return null;var b=f.xmlGenerator().createElement(a),c,d,e;for(c=1;c<arguments.length;c++){if(!arguments[c])continue;if(typeof arguments[c]=="string"||typeof arguments[c]=="number")b.appendChild(f.xmlTextNode(arguments[c]));else if(typeof arguments[c]=="object"&&typeof arguments[c].sort=="function")for(d=0;d<arguments[c].length;d++)typeof arguments[c][d]=="object"&&typeof arguments[c][d].sort=="function"&&b.setAttribute(arguments[c][d][0],arguments[c][d][1]);else if(typeof arguments[c]=="object")for(e in arguments[c])arguments[c].hasOwnProperty(e)&&b.setAttribute(e,arguments[c][e])}return b},xmlescape:function(a){return a=a.replace(/\&/g,"&"),a=a.replace(/</g,"<"),a=a.replace(/>/g,">"),a=a.replace(/'/g,"'"),a=a.replace(/"/g,"""),a},xmlunescape:function(a){return a=a.replace(/\&/g,"&"),a=a.replace(/</g,"<"),a=a.replace(/>/g,">"),a=a.replace(/'/g,"'"),a=a.replace(/"/g,'"'),a},xmlTextNode:function(a){return f.xmlGenerator().createTextNode(a)},xmlHtmlNode:function(a){var b;if(window.DOMParser){var c=new DOMParser;b=c.parseFromString(a,"text/xml")}else b=new ActiveXObject("Microsoft.XMLDOM"),b.async="false",b.loadXML(a);return b},getText:function(a){if(!a)return null;var b="";a.childNodes.length===0&&a.nodeType==f.ElementType.TEXT&&(b+=a.nodeValue);for(var c=0;c<a.childNodes.length;c++)a.childNodes[c].nodeType==f.ElementType.TEXT&&(b+=a.childNodes[c].nodeValue);return f.xmlescape(b)},copyElement:function(a){var b,c;if(a.nodeType==f.ElementType.NORMAL){c=f.xmlElement(a.tagName);for(b=0;b<a.attributes.length;b++)c.setAttribute(a.attributes[b].nodeName.toLowerCase(),a.attributes[b].value);for(b=0;b<a.childNodes.length;b++)c.appendChild(f.copyElement(a.childNodes[b]))}else a.nodeType==f.ElementType.TEXT&&(c=f.xmlGenerator().createTextNode(a.nodeValue));return c},createHtml:function(a){var b,c,d,e,g,h,i,j,k,l,m;if(a.nodeType==f.ElementType.NORMAL){e=a.nodeName.toLowerCase();if(f.XHTML.validTag(e))try{c=f.xmlElement(e);for(b=0;b<f.XHTML.attributes[e].length;b++){g=f.XHTML.attributes[e][b],h=a.getAttribute(g);if(typeof h=="undefined"||h===null||h===""||h===!1||h===0)continue;g=="style"&&typeof h=="object"&&typeof h.cssText!="undefined"&&(h=h.cssText);if(g=="style"){i=[],j=h.split(";");for(d=0;d<j.length;d++)k=j[d].split(":"),l=k[0].replace(/^\s*/,"").replace(/\s*$/,"").toLowerCase(),f.XHTML.validCSS(l)&&(m=k[1].replace(/^\s*/,"").replace(/\s*$/,""),i.push(l+": "+m));i.length>0&&(h=i.join("; "),c.setAttribute(g,h))}else c.setAttribute(g,h)}for(b=0;b<a.childNodes.length;b++)c.appendChild(f.createHtml(a.childNodes[b]))}catch(n){c=f.xmlTextNode("")}else{c=f.xmlGenerator().createDocumentFragment();for(b=0;b<a.childNodes.length;b++)c.appendChild(f.createHtml(a.childNodes[b]))}}else if(a.nodeType==f.ElementType.FRAGMENT){c=f.xmlGenerator().createDocumentFragment();for(b=0;b<a.childNodes.length;b++)c.appendChild(f.createHtml(a.childNodes[b]))}else a.nodeType==f.ElementType.TEXT&&(c=f.xmlTextNode(a.nodeValue));return c},escapeNode:function(a){return a.replace(/^\s+|\s+$/g,"").replace(/\\/g,"\\5c").replace(/ /g,"\\20").replace(/\"/g,"\\22").replace(/\&/g,"\\26").replace(/\'/g,"\\27").replace(/\//g,"\\2f").replace(/:/g,"\\3a").replace(/</g,"\\3c").replace(/>/g,"\\3e").replace(/@/g,"\\40")},unescapeNode:function(a){return a.replace(/\\20/g," ").replace(/\\22/g,'"').replace(/\\26/g,"&").replace(/\\27/g,"'").replace(/\\2f/g,"/").replace(/\\3a/g,":").replace(/\\3c/g,"<").replace(/\\3e/g,">").replace(/\\40/g,"@").replace(/\\5c/g,"\\")},getNodeFromJid:function(a){return a.indexOf("@")<0?null:a.split("@")[0]},getDomainFromJid:function(a){var b=f.getBareJidFromJid(a);if(b.indexOf("@")<0)return b;var c=b.split("@");return c.splice(0,1),c.join("@")},getResourceFromJid:function(a){var b=a.split("/");return b.length<2?null:(b.splice(0,1),b.join("/"))},getBareJidFromJid:function(a){return a?a.split("/")[0]:null},log:function(a,b){return},debug:function(a){this.log(this.LogLevel.DEBUG,a)},info:function(a){this.log(this.LogLevel.INFO,a)},warn:function(a){this.log(this.LogLevel.WARN,a)},error:function(a){this.log(this.LogLevel.ERROR,a)},fatal:function(a){this.log(this.LogLevel.FATAL,a)},serialize:function(a){var b;if(!a)return null;typeof a.tree=="function"&&(a=a.tree());var c=a.nodeName,d,e;a.getAttribute("_realname")&&(c=a.getAttribute("_realname")),b="<"+c;for(d=0;d<a.attributes.length;d++)a.attributes[d].nodeName!="_realname"&&(b+=" "+a.attributes[d].nodeName.toLowerCase()+"='"+a.attributes[d].value.replace(/&/g,"&").replace(/\'/g,"'").replace(/>/g,">").replace(/</g,"<")+"'");if(a.childNodes.length>0){b+=">";for(d=0;d<a.childNodes.length;d++){e=a.childNodes[d];switch(e.nodeType){case f.ElementType.NORMAL:b+=f.serialize(e);break;case f.ElementType.TEXT:b+=f.xmlescape(e.nodeValue);break;case f.ElementType.CDATA:b+="<![CDATA["+e.nodeValue+"]]>"}}b+="</"+c+">"}else b+="/>";return b},_requestId:0,_connectionPlugins:{},addConnectionPlugin:function(a,b){f._connectionPlugins[a]=b}},f.Builder=function(a,b){if(a=="presence"||a=="message"||a=="iq")b&&!b.xmlns?b.xmlns=f.NS.CLIENT:b||(b={xmlns:f.NS.CLIENT});this.nodeTree=f.xmlElement(a,b),this.node=this.nodeTree},f.Builder.prototype={tree:function(){return this.nodeTree},toString:function(){return f.serialize(this.nodeTree)},up:function(){return this.node=this.node.parentNode,this},attrs:function(a){for(var b in a)a.hasOwnProperty(b)&&this.node.setAttribute(b,a[b]);return this},c:function(a,b,c){var d=f.xmlElement(a,b,c);return this.node.appendChild(d),c||(this.node=d),this},cnode:function(a){var b,c=f.xmlGenerator();try{b=c.importNode!==undefined}catch(d){b=!1}var e=b?c.importNode(a,!0):f.copyElement(a);return this.node.appendChild(e),this.node=e,this},t:function(a){var b=f.xmlTextNode(a);return this.node.appendChild(b),this},h:function(a){var b=document.createElement("body");b.innerHTML=a;var c=f.createHtml(b);while(c.childNodes.length>0)this.node.appendChild(c.childNodes[0]);return this}},f.Handler=function(a,b,c,d,e,g,h){this.handler=a,this.ns=b,this.name=c,this.type=d,this.id=e,this.options=h||{matchBare:!1},this.options.matchBare||(this.options.matchBare=!1),this.options.matchBare?this.from=g?f.getBareJidFromJid(g):null:this.from=g,this.user=!0},f.Handler.prototype={isMatch:function(a){var b,c=null;this.options.matchBare?c=f.getBareJidFromJid(a.getAttribute("from")):c=a.getAttribute("from"),b=!1;if(!this.ns)b=!0;else{var d=this;f.forEachChild(a,null,function(a){a.getAttribute("xmlns")==d.ns&&(b=!0)}),b=b||a.getAttribute("xmlns")==this.ns}return!b||!!this.name&&!f.isTagEqual(a,this.name)||!!this.type&&a.getAttribute("type")!=this.type||!!this.id&&a.getAttribute("id")!=this.id||!!this.from&&c!=this.from?!1:!0},run:function(a){var b=null;try{b=this.handler(a)}catch(c){throw c.sourceURL?f.fatal("error: "+this.handler+" "+c.sourceURL+":"+c.line+" - "+c.name+": "+c.message):c.fileName?(typeof console!="undefined"&&(console.trace(),console.error(this.handler," - error - ",c,c.message)),f.fatal("error: "+this.handler+" "+c.fileName+":"+c.lineNumber+" - "+c.name+": "+c.message)):f.fatal("error: "+c.message+"\n"+c.stack),c}return b},toString:function(){return"{Handler: "+this.handler+"("+this.name+","+this.id+","+this.ns+")}"}},f.TimedHandler=function(a,b){this.period=a,this.handler=b,this.lastCalled=(new Date).getTime(),this.user=!0},f.TimedHandler.prototype={run:function(){return this.lastCalled=(new Date).getTime(),this.handler()},reset:function(){this.lastCalled=(new Date).getTime()},toString:function(){return"{TimedHandler: "+this.handler+"("+this.period+")}"}},f.Connection=function(a,b){this.service=a,this.options=b||{};var c=this.options.protocol||"";a.indexOf("ws:")===0||a.indexOf("wss:")===0||c.indexOf("ws")===0?this._proto=new f.Websocket(this):this._proto=new f.Bosh(this),this.jid="",this.domain=null,this.features=null,this._sasl_data={},this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this._authentication={},this._idleTimeout=null,this._disconnectTimeout=null,this.do_authentication=!0,this.authenticated=!1,this.disconnecting=!1,this.connected=!1,this.errors=0,this.paused=!1,this._data=[],this._uniqueId=0,this._sasl_success_handler=null,this._sasl_failure_handler=null,this._sasl_challenge_handler=null,this.maxRetries=5,this._idleTimeout=setTimeout(this._onIdle.bind(this),100);for(var d in f._connectionPlugins)if(f._connectionPlugins.hasOwnProperty(d)){var e=f._connectionPlugins[d],g=function(){};g.prototype=e,this[d]=new g,this[d].init(this)}},f.Connection.prototype={reset:function(){this._proto._reset(),this.do_session=!1,this.do_bind=!1,this.timedHandlers=[],this.handlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this._authentication={},this.authenticated=!1,this.disconnecting=!1,this.connected=!1,this.errors=0,this._requests=[],this._uniqueId=0},pause:function(){this.paused=!0},resume:function(){this.paused=!1},getUniqueId:function(a){return typeof a=="string"||typeof a=="number"?++this._uniqueId+":"+a:++this._uniqueId+""},connect:function(a,b,c,d,e,g){this.jid=a,this.authzid=f.getBareJidFromJid(this.jid),this.authcid=f.getNodeFromJid(this.jid),this.pass=b,this.servtype="xmpp",this.connect_callback=c,this.disconnecting=!1,this.connected=!1,this.authenticated=!1,this.errors=0,this.domain=f.getDomainFromJid(this.jid),this._changeConnectStatus(f.Status.CONNECTING,null),this._proto._connect(d,e,g)},attach:function(a,b,c,d,e,f,g){this._proto._attach(a,b,c,d,e,f,g)},xmlInput:function(a){return},xmlOutput:function(a){return},rawInput:function(a){return},rawOutput:function(a){return},send:function(a){if(a===null)return;if(typeof a.sort=="function")for(var b=0;b<a.length;b++)this._queueData(a[b]);else typeof a.tree=="function"?this._queueData(a.tree()):this._queueData(a);this._proto._send()},flush:function(){clearTimeout(this._idleTimeout),this._onIdle()},sendIQ:function(a,b,c,d){var e=null,f=this;typeof a.tree=="function"&&(a=a.tree());var g=a.getAttribute("id");g||(g=this.getUniqueId("sendIQ"),a.setAttribute("id",g));var h=this.addHandler(function(a){e&&f.deleteTimedHandler(e);var d=a.getAttribute("type");if(d=="result")b&&b(a);else{if(d!="error")throw{name:"StropheError",message:"Got bad IQ type of "+d};c&&c(a)}},null,"iq",null,g);return d&&(e=this.addTimedHandler(d,function(){return f.deleteHandler(h),c&&c(null),!1})),this.send(a),g},_queueData:function(a){if(a===null||!a.tagName||!a.childNodes)throw{name:"StropheError",message:"Cannot queue non-DOMElement."};this._data.push(a)},_sendRestart:function(){this._data.push("restart"),this._proto._sendRestart(),this._idleTimeout=setTimeout(this._onIdle.bind(this),100)},addTimedHandler:function(a,b){var c=new f.TimedHandler(a,b);return this.addTimeds.push(c),c},deleteTimedHandler:function(a){this.removeTimeds.push(a)},addHandler:function(a,b,c,d,e,g,h){var i=new f.Handler(a,b,c,d,e,g,h);return this.addHandlers.push(i),i},deleteHandler:function(a){this.removeHandlers.push(a)},disconnect:function(a){this._changeConnectStatus(f.Status.DISCONNECTING,a),f.info("Disconnect was called because: "+a);if(this.connected){var b=!1;this.disconnecting=!0,this.authenticated&&(b=k({xmlns:f.NS.CLIENT,type:"unavailable"})),this._disconnectTimeout=this._addSysTimedHandler(3e3,this._onDisconnectTimeout.bind(this)),this._proto._disconnect(b)}},_changeConnectStatus:function(a,b){for(var c in f._connectionPlugins)if(f._connectionPlugins.hasOwnProperty(c)){var d=this[c];if(d.statusChanged)try{d.statusChanged(a,b)}catch(e){f.error(""+c+" plugin caused an exception "+"changing status: "+e)}}if(this.connect_callback)try{this.connect_callback(a,b)}catch(g){f.error("User connection callback caused an exception: "+g)}},_doDisconnect:function(){this._disconnectTimeout!==null&&(this.deleteTimedHandler(this._disconnectTimeout),this._disconnectTimeout=null),f.info("_doDisconnect was called"),this._proto._doDisconnect(),this.authenticated=!1,this.disconnecting=!1,this.handlers=[],this.timedHandlers=[],this.removeTimeds=[],this.removeHandlers=[],this.addTimeds=[],this.addHandlers=[],this._changeConnectStatus(f.Status.DISCONNECTED,null),this.connected=!1},_dataRecv:function(a,b){f.info("_dataRecv called");var c=this._proto._reqToData(a);if(c===null)return;this.xmlInput!==f.Connection.prototype.xmlInput&&(c.nodeName===this._proto.strip&&c.childNodes.length?this.xmlInput(c.childNodes[0]):this.xmlInput(c)),this.rawInput!==f.Connection.prototype.rawInput&&(b?this.rawInput(b):this.rawInput(f.serialize(c)));var d,e;while(this.removeHandlers.length>0)e=this.removeHandlers.pop(),d=this.handlers.indexOf(e),d>=0&&this.handlers.splice(d,1);while(this.addHandlers.length>0)this.handlers.push(this.addHandlers.pop());if(this.disconnecting&&this._proto._emptyQueue()){this._doDisconnect();return}var g=c.getAttribute("type"),h,i;if(g!==null&&g=="terminate"){if(this.disconnecting)return;h=c.getAttribute("condition"),i=c.getElementsByTagName("conflict"),h!==null?(h=="remote-stream-error"&&i.length>0&&(h="conflict"),this._changeConnectStatus(f.Status.CONNFAIL,h)):this._changeConnectStatus(f.Status.CONNFAIL,"unknown"),this.disconnect("unknown stream-error");return}var j=this;f.forEachChild(c,null,function(a){var b,c;c=j.handlers,j.handlers=[];for(b=0;b<c.length;b++){var d=c[b];try{d.isMatch(a)&&(j.authenticated||!d.user)?d.run(a)&&j.handlers.push(d):j.handlers.push(d)}catch(e){f.warn("Removing Strophe handlers due to uncaught exception: "+e.message)}}})},mechanisms:{},_connect_cb:function(a,b,c){f.info("_connect_cb was called"),this.connected=!0;var d=this._proto._reqToData(a);if(!d)return;this.xmlInput!==f.Connection.prototype.xmlInput&&(d.nodeName===this._proto.strip&&d.childNodes.length?this.xmlInput(d.childNodes[0]):this.xmlInput(d)),this.rawInput!==f.Connection.prototype.rawInput&&(c?this.rawInput(c):this.rawInput(f.serialize(d)));var e=this._proto._connect_cb(d);if(e===f.Status.CONNFAIL)return;this._authentication.sasl_scram_sha1=!1,this._authentication.sasl_plain=!1,this._authentication.sasl_digest_md5=!1,this._authentication.sasl_anonymous=!1,this._authentication.legacy_auth=!1;var g=d.getElementsByTagName("stream:features").length>0;g||(g=d.getElementsByTagName("features").length>0);var h=d.getElementsByTagName("mechanism"),i=[],j,k,l=!1;if(!g){this._proto._no_auth_received(b);return}if(h.length>0)for(j=0;j<h.length;j++)k=f.getText(h[j]),this.mechanisms[k]&&i.push(this.mechanisms[k]);this._authentication.legacy_auth=d.getElementsByTagName("auth").length>0,l=this._authentication.legacy_auth||i.length>0;if(!l){this._proto._no_auth_received(b);return}this.do_authentication!==!1&&this.authenticate(i)},authenticate:function(b){var c;for(c=0;c<b.length-1;++c){var d=c;for(var e=c+1;e<b.length;++e)b[e].prototype.priority>b[d].prototype.priority&&(d=e);if(d!=c){var h=b[c];b[c]=b[d],b[d]=h}}var i=!1;for(c=0;c<b.length;++c){if(!b[c].test(this))continue;this._sasl_success_handler=this._addSysHandler(this._sasl_success_cb.bind(this),null,"success",null,null),this._sasl_failure_handler=this._addSysHandler(this._sasl_failure_cb.bind(this),null,"failure",null,null),this._sasl_challenge_handler=this._addSysHandler(this._sasl_challenge_cb.bind(this),null,"challenge",null,null),this._sasl_mechanism=new b[c],this._sasl_mechanism.onStart(this);var k=g("auth",{xmlns:f.NS.SASL,mechanism:this._sasl_mechanism.name});if(this._sasl_mechanism.isClientFirst){var l=this._sasl_mechanism.onChallenge(this,null);k.t(a.encode(l))}this.send(k.tree()),i=!0;break}i||(f.getNodeFromJid(this.jid)===null?(this._changeConnectStatus(f.Status.CONNFAIL,"x-strophe-bad-non-anon-jid"),this.disconnect("x-strophe-bad-non-anon-jid")):(this._changeConnectStatus(f.Status.AUTHENTICATING,null),this._addSysHandler(this._auth1_cb.bind(this),null,null,null,"_auth_1"),this.send(j({type:"get",to:this.domain,id:"_auth_1"}).c("query",{xmlns:f.NS.AUTH}).c("username",{}).t(f.getNodeFromJid(this.jid)).tree())))},_sasl_challenge_cb:function(b){var c=a.decode(f.getText(b)),d=this._sasl_mechanism.onChallenge(this,c),e=g("response",{xmlns:f.NS.SASL});return d!==""&&e.t(a.encode(d)),this.send(e.tree()),!0},_auth1_cb:function(a){var b=j({type:"set",id:"_auth_2"}).c("query",{xmlns:f.NS.AUTH}).c("username",{}).t(f.getNodeFromJid(this.jid)).up().c("password").t(this.pass);return f.getResourceFromJid(this.jid)||(this.jid=f.getBareJidFromJid(this.jid)+"/strophe"),b.up().c("resource",{}).t(f.getResourceFromJid(this.jid)),this._addSysHandler(this._auth2_cb.bind(this),null,null,null,"_auth_2"),this.send(b.tree()),!1},_sasl_success_cb:function(b){if(this._sasl_data["server-signature"]){var c,d=a.decode(f.getText(b)),e=/([a-z]+)=([^,]+)(,|$)/,g=d.match(e);g[1]=="v"&&(c=g[2]);if(c!=this._sasl_data["server-signature"])return this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_data={},this._sasl_failure_cb(null)}return f.info("SASL authentication succeeded."),this._sasl_mechanism&&this._sasl_mechanism.onSuccess(),this.deleteHandler(this._sasl_failure_handler),this._sasl_failure_handler=null,this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._addSysHandler(this._sasl_auth1_cb.bind(this),null,"stream:features",null,null),this._sendRestart(),!1},_sasl_auth1_cb:function(a){this.features=a;var b,c;for(b=0;b<a.childNodes.length;b++)c=a.childNodes[b],c.nodeName=="bind"&&(this.do_bind=!0),c.nodeName=="session"&&(this.do_session=!0);if(!this.do_bind)return this._changeConnectStatus(f.Status.AUTHFAIL,null),!1;this._addSysHandler(this._sasl_bind_cb.bind(this),null,null,null,"_bind_auth_2");var d=f.getResourceFromJid(this.jid);return d?this.send(j({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:f.NS.BIND}).c("resource",{}).t(d).tree()):this.send(j({type:"set",id:"_bind_auth_2"}).c("bind",{xmlns:f.NS.BIND}).tree()),!1},_sasl_bind_cb:function(a){if(a.getAttribute("type")=="error"){f.info("SASL binding failed.");var b=a.getElementsByTagName("conflict"),c;return b.length>0&&(c="conflict"),this._changeConnectStatus(f.Status.AUTHFAIL,c),!1}var d=a.getElementsByTagName("bind"),e;if(!(d.length>0))return f.info("SASL binding failed."),this._changeConnectStatus(f.Status.AUTHFAIL,null),!1;e=d[0].getElementsByTagName("jid"),e.length>0&&(this.jid=f.getText(e[0]),this.do_session?(this._addSysHandler(this._sasl_session_cb.bind(this),null,null,null,"_session_auth_2"),this.send(j({type:"set",id:"_session_auth_2"}).c("session",{xmlns:f.NS.SESSION}).tree())):(this.authenticated=!0,this._changeConnectStatus(f.Status.CONNECTED,null)))},_sasl_session_cb:function(a){if(a.getAttribute("type")=="result")this.authenticated=!0,this._changeConnectStatus(f.Status.CONNECTED,null);else if(a.getAttribute("type")=="error")return f.info("Session creation failed."),this._changeConnectStatus(f.Status.AUTHFAIL,null),!1;return!1},_sasl_failure_cb:function(a){return this._sasl_success_handler&&(this.deleteHandler(this._sasl_success_handler),this._sasl_success_handler=null),this._sasl_challenge_handler&&(this.deleteHandler(this._sasl_challenge_handler),this._sasl_challenge_handler=null),this._sasl_mechanism&&this._sasl_mechanism.onFailure(),this._changeConnectStatus(f.Status.AUTHFAIL,null),!1},_auth2_cb:function(a){return a.getAttribute("type")=="result"?(this.authenticated=!0,this._changeConnectStatus(f.Status.CONNECTED,null)):a.getAttribute("type")=="error"&&(this._changeConnectStatus(f.Status.AUTHFAIL,null),this.disconnect("authentication failed")),!1},_addSysTimedHandler:function(a,b){var c=new f.TimedHandler(a,b);return c.user=!1,this.addTimeds.push(c),c},_addSysHandler:function(a,b,c,d,e){var g=new f.Handler(a,b,c,d,e);return g.user=!1,this.addHandlers.push(g),g},_onDisconnectTimeout:function(){return f.info("_onDisconnectTimeout was called"),this._proto._onDisconnectTimeout(),this._doDisconnect(),!1},_onIdle:function(){var a,b,c,d;while(this.addTimeds.length>0)this.timedHandlers.push(this.addTimeds.pop());while(this.removeTimeds.length>0)b=this.removeTimeds.pop(),a=this.timedHandlers.indexOf(b),a>=0&&this.timedHandlers.splice(a,1);var e=(new Date).getTime();d=[];for(a=0;a<this.timedHandlers.length;a++){b=this.timedHandlers[a];if(this.authenticated||!b.user)c=b.lastCalled+b.period,c-e<=0?b.run()&&d.push(b):d.push(b)}this.timedHandlers=d,clearTimeout(this._idleTimeout),this._proto._onIdle(),this.connected&&(this._idleTimeout=setTimeout(this._onIdle.bind(this),100))}},b&&b(f,g,h,j,k),f.SASLMechanism=function(a,b,c){this.name=a,this.isClientFirst=b,this.priority=c},f.SASLMechanism.prototype={test:function(a){return!0},onStart:function(a){this._connection=a},onChallenge:function(a,b){throw new Error("You should implement challenge handling!")},onFailure:function(){this._connection=null},onSuccess:function(){this._connection=null}},f.SASLAnonymous=function(){},f.SASLAnonymous.prototype=new f.SASLMechanism("ANONYMOUS",!1,10),f.SASLAnonymous.test=function(a){return a.authcid===null},f.Connection.prototype.mechanisms[f.SASLAnonymous.prototype.name]=f.SASLAnonymous,f.SASLPlain=function(){},f.SASLPlain.prototype=new f.SASLMechanism("PLAIN",!0,20),f.SASLPlain.test=function(a){return a.authcid!==null},f.SASLPlain.prototype.onChallenge=function(a){var b=a.authzid;return b+="\0",b+=a.authcid,b+="\0",b+=a.pass,b},f.Connection.prototype.mechanisms[f.SASLPlain.prototype.name]=f.SASLPlain,f.SASLSHA1=function(){},f.SASLSHA1.prototype=new f.SASLMechanism("SCRAM-SHA-1",!0,40),f.SASLSHA1.test=function(a){return a.authcid!==null},f.SASLSHA1.prototype.onChallenge=function(b,f,g){var h=g||o.hexdigest(Math.random()*1234567890),j="n="+b.authcid;return j+=",r=",j+=h,b._sasl_data.cnonce=h,b._sasl_data["client-first-message-bare"]=j,j="n,,"+j,this.onChallenge=function(b,f){var g,h,j,k,l,n,o,p,q,r,s,t="c=biws,",u=b._sasl_data["client-first-message-bare"]+","+f+",",v=b._sasl_data.cnonce,w=/([a-z]+)=([^,]+)(,|$)/;while(f.match(w)){var x=f.match(w);f=f.replace(x[0],"");switch(x[1]){case"r":g=x[2];break;case"s":h=x[2];break;case"i":j=x[2]}}if(g.substr(0,v.length)!==v)return b._sasl_data={},b._sasl_failure_cb();t+="r="+g,u+=t,h=a.decode(h),h+="\0\0\0",k=n=i(b.pass,h);for(o=1;o<j;o++){l=i(b.pass,m(n));for(p=0;p<5;p++)k[p]^=l[p];n=l}k=m(k),q=i(k,"Client Key"),r=e(k,"Server Key"),s=i(c(m(q)),u),b._sasl_data["server-signature"]=d(r,u);for(p=0;p<5;p++)q[p]^=s[p];return t+=",p="+a.encode(m(q)),t}.bind(this),j},f.Connection.prototype.mechanisms[f.SASLSHA1.prototype.name]=f.SASLSHA1,f.SASLMD5=function(){},f.SASLMD5.prototype=new f.SASLMechanism("DIGEST-MD5",!1,30),f.SASLMD5.test=function(a){return a.authcid!==null},f.SASLMD5.prototype._quote=function(a){return'"'+a.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"'},f.SASLMD5.prototype.onChallenge=function(a,b,c){var d=/([a-z]+)=("[^"]+"|[^,"]+)(?:,|$)/,e=c||o.hexdigest(""+Math.random()*1234567890),f="",g=null,h="",i="",j;while(b.match(d)){j=b.match(d),b=b.replace(j[0],""),j[2]=j[2].replace(/^"(.+)"$/,"$1");switch(j[1]){case"realm":f=j[2];break;case"nonce":h=j[2];break;case"qop":i=j[2];break;case"host":g=j[2]}}var k=a.servtype+"/"+a.domain;g!==null&&(k=k+"/"+g);var l=o.hash(a.authcid+":"+f+":"+this._connection.pass)+":"+h+":"+e,m="AUTHENTICATE:"+k,n="";return n+="charset=utf-8,",n+="username="+this._quote(a.authcid)+",",n+="realm="+this._quote(f)+",",n+="nonce="+this._quote(h)+",",n+="nc=00000001,",n+="cnonce="+this._quote(e)+",",n+="digest-uri="+this._quote(k)+",",n+="response="+o.hexdigest(o.hexdigest(l)+":"+h+":00000001:"+e+":auth:"+o.hexdigest(m))+",",n+="qop=auth",this.onChallenge=function(){return""}.bind(this),n}
,f.Connection.prototype.mechanisms[f.SASLMD5.prototype.name]=f.SASLMD5}(function(){window.Strophe=arguments[0],window.$build=arguments[1],window.$msg=arguments[2],window.$iq=arguments[3],window.$pres=arguments[4]}),Strophe.Request=function(a,b,c,d){this.id=++Strophe._requestId,this.xmlData=a,this.data=Strophe.serialize(a),this.origFunc=b,this.func=b,this.rid=c,this.date=NaN,this.sends=d||0,this.abort=!1,this.dead=null,this.age=function(){if(!this.date)return 0;var a=new Date;return(a-this.date)/1e3},this.timeDead=function(){if(!this.dead)return 0;var a=new Date;return(a-this.dead)/1e3},this.xhr=this._newXHR()},Strophe.Request.prototype={getResponse:function(){var a=null;if(this.xhr.responseXML&&this.xhr.responseXML.documentElement){a=this.xhr.responseXML.documentElement;if(a.tagName=="parsererror")throw Strophe.error("invalid response received"),Strophe.error("responseText: "+this.xhr.responseText),Strophe.error("responseXML: "+Strophe.serialize(this.xhr.responseXML)),"parsererror"}else this.xhr.responseText&&(Strophe.error("invalid response received"),Strophe.error("responseText: "+this.xhr.responseText),Strophe.error("responseXML: "+Strophe.serialize(this.xhr.responseXML)));return a},_newXHR:function(){var a=null;return window.XMLHttpRequest?(a=new XMLHttpRequest,a.overrideMimeType&&a.overrideMimeType("text/xml")):window.ActiveXObject&&(a=new ActiveXObject("Microsoft.XMLHTTP")),a.onreadystatechange=this.func.bind(null,this),a}},Strophe.Bosh=function(a){this._conn=a,this.rid=Math.floor(Math.random()*4294967295),this.sid=null,this.hold=1,this.wait=60,this.window=5,this._requests=[]},Strophe.Bosh.prototype={strip:null,_buildBody:function(){var a=$build("body",{rid:this.rid++,xmlns:Strophe.NS.HTTPBIND});return this.sid!==null&&a.attrs({sid:this.sid}),a},_reset:function(){this.rid=Math.floor(Math.random()*4294967295),this.sid=null},_connect:function(a,b,c){this.wait=a||this.wait,this.hold=b||this.hold;var d=this._buildBody().attrs({to:this._conn.domain,"xml:lang":"en",wait:this.wait,hold:this.hold,content:"text/xml; charset=utf-8",ver:"1.6","xmpp:version":"1.0","xmlns:xmpp":Strophe.NS.BOSH});c&&d.attrs({route:c});var e=this._conn._connect_cb;this._requests.push(new Strophe.Request(d.tree(),this._onRequestStateChange.bind(this,e.bind(this._conn)),d.tree().getAttribute("rid"))),this._throttledRequestHandler()},_attach:function(a,b,c,d,e,f,g){this._conn.jid=a,this.sid=b,this.rid=c,this._conn.connect_callback=d,this._conn.domain=Strophe.getDomainFromJid(this._conn.jid),this._conn.authenticated=!0,this._conn.connected=!0,this.wait=e||this.wait,this.hold=f||this.hold,this.window=g||this.window,this._conn._changeConnectStatus(Strophe.Status.ATTACHED,null)},_connect_cb:function(a){var b=a.getAttribute("type"),c,d;if(b!==null&&b=="terminate")return Strophe.error("BOSH-Connection failed: "+c),c=a.getAttribute("condition"),d=a.getElementsByTagName("conflict"),c!==null?(c=="remote-stream-error"&&d.length>0&&(c="conflict"),this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,c)):this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,"unknown"),this._conn._doDisconnect(),Strophe.Status.CONNFAIL;this.sid||(this.sid=a.getAttribute("sid"));var e=a.getAttribute("requests");e&&(this.window=parseInt(e,10));var f=a.getAttribute("hold");f&&(this.hold=parseInt(f,10));var g=a.getAttribute("wait");g&&(this.wait=parseInt(g,10))},_disconnect:function(a){this._sendTerminate(a)},_doDisconnect:function(){this.sid=null,this.rid=Math.floor(Math.random()*4294967295)},_emptyQueue:function(){return this._requests.length===0},_hitError:function(a){this.errors++,Strophe.warn("request errored, status: "+a+", number of errors: "+this.errors),this.errors>4&&this._onDisconnectTimeout()},_no_auth_received:function(a){a?a=a.bind(this._conn):a=this._conn._connect_cb.bind(this._conn);var b=this._buildBody();this._requests.push(new Strophe.Request(b.tree(),this._onRequestStateChange.bind(this,a.bind(this._conn)),b.tree().getAttribute("rid"))),this._throttledRequestHandler()},_onDisconnectTimeout:function(){var a;while(this._requests.length>0)a=this._requests.pop(),a.abort=!0,a.xhr.abort(),a.xhr.onreadystatechange=function(){}},_onIdle:function(){var a=this._conn._data;this._conn.authenticated&&this._requests.length===0&&a.length===0&&!this._conn.disconnecting&&(Strophe.info("no requests during idle cycle, sending blank request"),a.push(null));if(this._requests.length<2&&a.length>0&&!this._conn.paused){var b=this._buildBody();for(var c=0;c<a.length;c++)a[c]!==null&&(a[c]==="restart"?b.attrs({to:this._conn.domain,"xml:lang":"en","xmpp:restart":"true","xmlns:xmpp":Strophe.NS.BOSH}):b.cnode(a[c]).up());delete this._conn._data,this._conn._data=[],this._requests.push(new Strophe.Request(b.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),b.tree().getAttribute("rid"))),this._processRequest(this._requests.length-1)}if(this._requests.length>0){var d=this._requests[0].age();this._requests[0].dead!==null&&this._requests[0].timeDead()>Math.floor(Strophe.SECONDARY_TIMEOUT*this.wait)&&this._throttledRequestHandler(),d>Math.floor(Strophe.TIMEOUT*this.wait)&&(Strophe.warn("Request "+this._requests[0].id+" timed out, over "+Math.floor(Strophe.TIMEOUT*this.wait)+" seconds since last activity"),this._throttledRequestHandler())}},_onRequestStateChange:function(a,b){Strophe.debug("request id "+b.id+"."+b.sends+" state changed to "+b.xhr.readyState);if(b.abort){b.abort=!1;return}var c;if(b.xhr.readyState==4){c=0;try{c=b.xhr.status}catch(d){}typeof c=="undefined"&&(c=0);if(this.disconnecting&&c>=400){this._hitError(c);return}var e=this._requests[0]==b,f=this._requests[1]==b;if(c>0&&c<500||b.sends>5)this._removeRequest(b),Strophe.debug("request id "+b.id+" should now be removed");if(c==200)(f||e&&this._requests.length>0&&this._requests[0].age()>Math.floor(Strophe.SECONDARY_TIMEOUT*this.wait))&&this._restartRequest(0),Strophe.debug("request id "+b.id+"."+b.sends+" got 200"),a(b),this.errors=0;else{Strophe.error("request id "+b.id+"."+b.sends+" error "+c+" happened");if(c===0||c>=400&&c<600||c>=12e3)this._hitError(c),c>=400&&c<500&&(this._conn._changeConnectStatus(Strophe.Status.DISCONNECTING,null),this._conn._doDisconnect())}c>0&&c<500||b.sends>5||this._throttledRequestHandler()}},_processRequest:function(a){var b=this,c=this._requests[a],d=-1;try{c.xhr.readyState==4&&(d=c.xhr.status)}catch(e){Strophe.error("caught an error in _requests["+a+"], reqStatus: "+d)}typeof d=="undefined"&&(d=-1);if(c.sends>this.maxRetries){this._onDisconnectTimeout();return}var f=c.age(),g=!isNaN(f)&&f>Math.floor(Strophe.TIMEOUT*this.wait),h=c.dead!==null&&c.timeDead()>Math.floor(Strophe.SECONDARY_TIMEOUT*this.wait),i=c.xhr.readyState==4&&(d<1||d>=500);if(g||h||i)h&&Strophe.error("Request "+this._requests[a].id+" timed out (secondary), restarting"),c.abort=!0,c.xhr.abort(),c.xhr.onreadystatechange=function(){},this._requests[a]=new Strophe.Request(c.xmlData,c.origFunc,c.rid,c.sends),c=this._requests[a];if(c.xhr.readyState===0){Strophe.debug("request id "+c.id+"."+c.sends+" posting");try{c.xhr.open("POST",this._conn.service,this._conn.options.sync?!1:!0)}catch(j){Strophe.error("XHR open failed."),this._conn.connected||this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,"bad-service"),this._conn.disconnect();return}var k=function(){c.date=new Date;if(b._conn.options.customHeaders){var a=b._conn.options.customHeaders;for(var d in a)a.hasOwnProperty(d)&&c.xhr.setRequestHeader(d,a[d])}c.xhr.setRequestHeader("Content-Type","text/plain"),c.xhr.send(c.data)};if(c.sends>1){var l=Math.min(Math.floor(Strophe.TIMEOUT*this.wait),Math.pow(c.sends,3))*1e3;setTimeout(k,l)}else k();c.sends++,this._conn.xmlOutput!==Strophe.Connection.prototype.xmlOutput&&(c.xmlData.nodeName===this.strip&&c.xmlData.childNodes.length?this._conn.xmlOutput(c.xmlData.childNodes[0]):this._conn.xmlOutput(c.xmlData)),this._conn.rawOutput!==Strophe.Connection.prototype.rawOutput&&this._conn.rawOutput(c.data)}else Strophe.debug("_processRequest: "+(a===0?"first":"second")+" request has readyState of "+c.xhr.readyState)},_removeRequest:function(a){Strophe.debug("removing request");var b;for(b=this._requests.length-1;b>=0;b--)a==this._requests[b]&&this._requests.splice(b,1);a.xhr.onreadystatechange=function(){},this._throttledRequestHandler()},_restartRequest:function(a){var b=this._requests[a];b.dead===null&&(b.dead=new Date),this._processRequest(a)},_reqToData:function(a){try{return a.getResponse()}catch(b){if(b!="parsererror")throw b;this._conn.disconnect("strophe-parsererror")}},_sendTerminate:function(a){Strophe.info("_sendTerminate was called");var b=this._buildBody().attrs({type:"terminate"});a&&b.cnode(a.tree());var c=new Strophe.Request(b.tree(),this._onRequestStateChange.bind(this,this._conn._dataRecv.bind(this._conn)),b.tree().getAttribute("rid"));this._requests.push(c),this._throttledRequestHandler()},_send:function(){clearTimeout(this._conn._idleTimeout),this._throttledRequestHandler(),this._conn._idleTimeout=setTimeout(this._conn._onIdle.bind(this._conn),100)},_sendRestart:function(){this._throttledRequestHandler(),clearTimeout(this._conn._idleTimeout)},_throttledRequestHandler:function(){this._requests?Strophe.debug("_throttledRequestHandler called with "+this._requests.length+" requests"):Strophe.debug("_throttledRequestHandler called with undefined requests");if(!this._requests||this._requests.length===0)return;this._requests.length>0&&this._processRequest(0),this._requests.length>1&&Math.abs(this._requests[0].rid-this._requests[1].rid)<this.window&&this._processRequest(1)}},Strophe.Websocket=function(a){this._conn=a,this.strip="stream:stream";var b=a.service;if(b.indexOf("ws:")!==0&&b.indexOf("wss:")!==0){var c="";a.options.protocol==="ws"&&window.location.protocol!=="https:"?c+="ws":c+="wss",c+="://"+window.location.host,b.indexOf("/")!==0?c+=window.location.pathname+b:c+=b,a.service=c}},Strophe.Websocket.prototype={_buildStream:function(){return $build("stream:stream",{to:this._conn.domain,xmlns:Strophe.NS.CLIENT,"xmlns:stream":Strophe.NS.STREAM,version:"1.0"})},_check_streamerror:function(a,b){var c=a.getElementsByTagName("stream:error");if(c.length===0)return!1;var d=c[0],e="",f="",g="urn:ietf:params:xml:ns:xmpp-streams";for(var h=0;h<d.childNodes.length;h++){var i=d.childNodes[h];if(i.getAttribute("xmlns")!==g)break;i.nodeName==="text"?f=i.textContent:e=i.nodeName}var j="WebSocket stream error: ";return e?j+=e:j+="unknown",f&&(j+=" - "+e),Strophe.error(j),this._conn._changeConnectStatus(b,e),this._conn._doDisconnect(),!0},_reset:function(){return},_connect:function(){this._closeSocket(),this.socket=new WebSocket(this._conn.service,"xmpp"),this.socket.onopen=this._onOpen.bind(this),this.socket.onerror=this._onError.bind(this),this.socket.onclose=this._onClose.bind(this),this.socket.onmessage=this._connect_cb_wrapper.bind(this)},_connect_cb:function(a){var b=this._check_streamerror(a,Strophe.Status.CONNFAIL);if(b)return Strophe.Status.CONNFAIL},_handleStreamStart:function(a){var b=!1,c=a.getAttribute("xmlns");typeof c!="string"?b="Missing xmlns in stream:stream":c!==Strophe.NS.CLIENT&&(b="Wrong xmlns in stream:stream: "+c);var d=a.namespaceURI;typeof d!="string"?b="Missing xmlns:stream in stream:stream":d!==Strophe.NS.STREAM&&(b="Wrong xmlns:stream in stream:stream: "+d);var e=a.getAttribute("version");return typeof e!="string"?b="Missing version in stream:stream":e!=="1.0"&&(b="Wrong version in stream:stream: "+e),b?(this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,b),this._conn._doDisconnect(),!1):!0},_connect_cb_wrapper:function(a){if(a.data.indexOf("<stream:stream ")===0||a.data.indexOf("<?xml")===0){var b=a.data.replace(/^(<\?.*?\?>\s*)*/,"");if(b==="")return;b=a.data.replace(/<stream:stream (.*[^\/])>/,"<stream:stream $1/>");var c=(new DOMParser).parseFromString(b,"text/xml").documentElement;this._conn.xmlInput(c),this._conn.rawInput(a.data),this._handleStreamStart(c)&&(this._connect_cb(c),this.streamStart=a.data.replace(/^<stream:(.*)\/>$/,"<stream:$1>"))}else{if(a.data==="</stream:stream>"){this._conn.rawInput(a.data),this._conn.xmlInput(document.createElement("stream:stream")),this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,"Received closing stream"),this._conn._doDisconnect();return}var d=this._streamWrap(a.data),e=(new DOMParser).parseFromString(d,"text/xml").documentElement;this.socket.onmessage=this._onMessage.bind(this),this._conn._connect_cb(e,null,a.data)}},_disconnect:function(a){if(this.socket.readyState!==WebSocket.CLOSED){a&&this._conn.send(a);var b="</stream:stream>";this._conn.xmlOutput(document.createElement("stream:stream")),this._conn.rawOutput(b);try{this.socket.send(b)}catch(c){Strophe.info("Couldn't send closing stream tag.")}}this._conn._doDisconnect()},_doDisconnect:function(){Strophe.info("WebSockets _doDisconnect was called"),this._closeSocket()},_streamWrap:function(a){return this.streamStart+a+"</stream:stream>"},_closeSocket:function(){if(this.socket)try{this.socket.close()}catch(a){}this.socket=null},_emptyQueue:function(){return!0},_onClose:function(){this._conn.connected&&!this._conn.disconnecting?(Strophe.error("Websocket closed unexcectedly"),this._conn._doDisconnect()):Strophe.info("Websocket closed")},_no_auth_received:function(a){Strophe.error("Server did not send any auth methods"),this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,"Server did not send any auth methods"),a&&(a=a.bind(this._conn),a()),this._conn._doDisconnect()},_onDisconnectTimeout:function(){},_onError:function(a){Strophe.error("Websocket error "+a),this._conn._changeConnectStatus(Strophe.Status.CONNFAIL,"The WebSocket connection could not be established was disconnected."),this._disconnect()},_onIdle:function(){var a=this._conn._data;if(a.length>0&&!this._conn.paused){for(var b=0;b<a.length;b++)if(a[b]!==null){var c,d;a[b]==="restart"?(c=this._buildStream(),d=this._removeClosingTag(c),c=c.tree()):(c=a[b],d=Strophe.serialize(c)),this._conn.xmlOutput(c),this._conn.rawOutput(d),this.socket.send(d)}this._conn._data=[]}},_onMessage:function(a){var b,c;if(a.data==="</stream:stream>"){var d="</stream:stream>";this._conn.rawInput(d),this._conn.xmlInput(document.createElement("stream:stream")),this._conn.disconnecting||this._conn._doDisconnect();return}if(a.data.search("<stream:stream ")===0){c=a.data.replace(/<stream:stream (.*[^\/])>/,"<stream:stream $1/>"),b=(new DOMParser).parseFromString(c,"text/xml").documentElement;if(!this._handleStreamStart(b))return}else c=this._streamWrap(a.data),b=(new DOMParser).parseFromString(c,"text/xml").documentElement;if(this._check_streamerror(b,Strophe.Status.ERROR))return;if(this._conn.disconnecting&&b.firstChild.nodeName==="presence"&&b.firstChild.getAttribute("type")==="unavailable"){this._conn.xmlInput(b),this._conn.rawInput(Strophe.serialize(b));return}this._conn._dataRecv(b,a.data)},_onOpen:function(){Strophe.info("Websocket open");var a=this._buildStream();this._conn.xmlOutput(a.tree());var b=this._removeClosingTag(a);this._conn.rawOutput(b),this.socket.send(b)},_removeClosingTag:function(a){var b=Strophe.serialize(a);return b=b.replace(/<(stream:stream .*[^\/])\/>$/,"<$1>"),b},_reqToData:function(a){return a},_send:function(){this._conn.flush()},_sendRestart:function(){clearTimeout(this._conn._idleTimeout),this._conn._onIdle.bind(this._conn)()}}}();
},{}],13:[function(require,module,exports){
(function(e,r){"object"==typeof exports?module.exports=exports=r():"function"==typeof define&&define.amd?define([],r):e.CryptoJS=r()})(this,function(){var e=e||function(e,r){var t={},i=t.lib={},n=i.Base=function(){function e(){}return{extend:function(r){e.prototype=this;var t=new e;return r&&t.mixIn(r),t.hasOwnProperty("init")||(t.init=function(){t.$super.init.apply(this,arguments)}),t.init.prototype=t,t.$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var r in e)e.hasOwnProperty(r)&&(this[r]=e[r]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),o=i.WordArray=n.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=t!=r?t:4*e.length},toString:function(e){return(e||s).stringify(this)},concat:function(e){var r=this.words,t=e.words,i=this.sigBytes,n=e.sigBytes;if(this.clamp(),i%4)for(var o=0;n>o;o++){var c=255&t[o>>>2]>>>24-8*(o%4);r[i+o>>>2]|=c<<24-8*((i+o)%4)}else if(t.length>65535)for(var o=0;n>o;o+=4)r[i+o>>>2]=t[o>>>2];else r.push.apply(r,t);return this.sigBytes+=n,this},clamp:function(){var r=this.words,t=this.sigBytes;r[t>>>2]&=4294967295<<32-8*(t%4),r.length=e.ceil(t/4)},clone:function(){var e=n.clone.call(this);return e.words=this.words.slice(0),e},random:function(r){for(var t=[],i=0;r>i;i+=4)t.push(0|4294967296*e.random());return new o.init(t,r)}}),c=t.enc={},s=c.Hex={stringify:function(e){for(var r=e.words,t=e.sigBytes,i=[],n=0;t>n;n++){var o=255&r[n>>>2]>>>24-8*(n%4);i.push((o>>>4).toString(16)),i.push((15&o).toString(16))}return i.join("")},parse:function(e){for(var r=e.length,t=[],i=0;r>i;i+=2)t[i>>>3]|=parseInt(e.substr(i,2),16)<<24-4*(i%8);return new o.init(t,r/2)}},u=c.Latin1={stringify:function(e){for(var r=e.words,t=e.sigBytes,i=[],n=0;t>n;n++){var o=255&r[n>>>2]>>>24-8*(n%4);i.push(String.fromCharCode(o))}return i.join("")},parse:function(e){for(var r=e.length,t=[],i=0;r>i;i++)t[i>>>2]|=(255&e.charCodeAt(i))<<24-8*(i%4);return new o.init(t,r)}},f=c.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(r){throw Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},a=i.BufferedBlockAlgorithm=n.extend({reset:function(){this._data=new o.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=f.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(r){var t=this._data,i=t.words,n=t.sigBytes,c=this.blockSize,s=4*c,u=n/s;u=r?e.ceil(u):e.max((0|u)-this._minBufferSize,0);var f=u*c,a=e.min(4*f,n);if(f){for(var p=0;f>p;p+=c)this._doProcessBlock(i,p);var d=i.splice(0,f);t.sigBytes-=a}return new o.init(d,a)},clone:function(){var e=n.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0});i.Hasher=a.extend({cfg:n.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){a.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){e&&this._append(e);var r=this._doFinalize();return r},blockSize:16,_createHelper:function(e){return function(r,t){return new e.init(t).finalize(r)}},_createHmacHelper:function(e){return function(r,t){return new p.HMAC.init(e,t).finalize(r)}}});var p=t.algo={};return t}(Math);return e});
},{}],14:[function(require,module,exports){
(function(e,r){"object"==typeof exports?module.exports=exports=r(require("./core"),require("./sha1"),require("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],r):r(e.CryptoJS)})(this,function(e){return e.HmacSHA1});
},{"./core":13,"./hmac":15,"./sha1":16}],15:[function(require,module,exports){
(function(e,r){"object"==typeof exports?module.exports=exports=r(require("./core")):"function"==typeof define&&define.amd?define(["./core"],r):r(e.CryptoJS)})(this,function(e){(function(){var r=e,t=r.lib,n=t.Base,i=r.enc,o=i.Utf8,s=r.algo;s.HMAC=n.extend({init:function(e,r){e=this._hasher=new e.init,"string"==typeof r&&(r=o.parse(r));var t=e.blockSize,n=4*t;r.sigBytes>n&&(r=e.finalize(r)),r.clamp();for(var i=this._oKey=r.clone(),s=this._iKey=r.clone(),a=i.words,c=s.words,f=0;t>f;f++)a[f]^=1549556828,c[f]^=909522486;i.sigBytes=s.sigBytes=n,this.reset()},reset:function(){var e=this._hasher;e.reset(),e.update(this._iKey)},update:function(e){return this._hasher.update(e),this},finalize:function(e){var r=this._hasher,t=r.finalize(e);r.reset();var n=r.finalize(this._oKey.clone().concat(t));return n}})})()});
},{"./core":13}],16:[function(require,module,exports){
(function(e,r){"object"==typeof exports?module.exports=exports=r(require("./core")):"function"==typeof define&&define.amd?define(["./core"],r):r(e.CryptoJS)})(this,function(e){return function(){var r=e,t=r.lib,n=t.WordArray,i=t.Hasher,o=r.algo,s=[],c=o.SHA1=i.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,r){for(var t=this._hash.words,n=t[0],i=t[1],o=t[2],c=t[3],a=t[4],f=0;80>f;f++){if(16>f)s[f]=0|e[r+f];else{var u=s[f-3]^s[f-8]^s[f-14]^s[f-16];s[f]=u<<1|u>>>31}var d=(n<<5|n>>>27)+a+s[f];d+=20>f?(i&o|~i&c)+1518500249:40>f?(i^o^c)+1859775393:60>f?(i&o|i&c|o&c)-1894007588:(i^o^c)-899497514,a=c,c=o,o=i<<30|i>>>2,i=n,n=d}t[0]=0|t[0]+n,t[1]=0|t[1]+i,t[2]=0|t[2]+o,t[3]=0|t[3]+c,t[4]=0|t[4]+a},_doFinalize:function(){var e=this._data,r=e.words,t=8*this._nDataBytes,n=8*e.sigBytes;return r[n>>>5]|=128<<24-n%32,r[(n+64>>>9<<4)+14]=Math.floor(t/4294967296),r[(n+64>>>9<<4)+15]=t,e.sigBytes=4*r.length,this._process(),this._hash},clone:function(){var e=i.clone.call(this);return e._hash=this._hash.clone(),e}});r.SHA1=i._createHelper(c),r.HmacSHA1=i._createHmacHelper(c)}(),e.SHA1});
},{"./core":13}]},{},[11]) | kiwi89/cdnjs | ajax/libs/quickblox/1.3.0/quickblox.js | JavaScript | mit | 103,950 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Locale\Stub;
use Symfony\Component\Locale\Exception\MethodNotImplementedException;
use Symfony\Component\Locale\Exception\MethodArgumentValueNotImplementedException;
/**
* Provides a stub Collator for the 'en' locale.
*
* @author Igor Wiedler <igor@wiedler.ch>
*/
class StubCollator
{
/** Attribute constants */
const FRENCH_COLLATION = 0;
const ALTERNATE_HANDLING = 1;
const CASE_FIRST = 2;
const CASE_LEVEL = 3;
const NORMALIZATION_MODE = 4;
const STRENGTH = 5;
const HIRAGANA_QUATERNARY_MODE = 6;
const NUMERIC_COLLATION = 7;
/** Attribute constants values */
const DEFAULT_VALUE = -1;
const PRIMARY = 0;
const SECONDARY = 1;
const TERTIARY = 2;
const DEFAULT_STRENGTH = 2;
const QUATERNARY = 3;
const IDENTICAL = 15;
const OFF = 16;
const ON = 17;
const SHIFTED = 20;
const NON_IGNORABLE = 21;
const LOWER_FIRST = 24;
const UPPER_FIRST = 25;
/** Sorting options */
const SORT_REGULAR = 0;
const SORT_NUMERIC = 2;
const SORT_STRING = 1;
/**
* Constructor
*
* @param string $locale The locale code
*
* @throws MethodArgumentValueNotImplementedException When $locale different than 'en' is passed
*/
public function __construct($locale)
{
if ('en' != $locale) {
throw new MethodArgumentValueNotImplementedException(__METHOD__, 'locale', $locale, 'Only the \'en\' locale is supported');
}
}
/**
* Static constructor
*
* @param string $locale The locale code
*
* @return StubCollator
*
* @throws MethodArgumentValueNotImplementedException When $locale different than 'en' is passed
*/
public static function create($locale)
{
return new self($locale);
}
/**
* Sort array maintaining index association
*
* @param array &$array Input array
* @param integer $sortFlag Flags for sorting, can be one of the following:
* StubCollator::SORT_REGULAR - compare items normally (don't change types)
* StubCollator::SORT_NUMERIC - compare items numerically
* StubCollator::SORT_STRING - compare items as strings
*
* @return Boolean True on success or false on failure
*/
public function asort(&$array, $sortFlag = self::SORT_REGULAR)
{
$intlToPlainFlagMap = array(
self::SORT_REGULAR => \SORT_REGULAR,
self::SORT_NUMERIC => \SORT_NUMERIC,
self::SORT_STRING => \SORT_STRING,
);
$plainSortFlag = isset($intlToPlainFlagMap[$sortFlag]) ? $intlToPlainFlagMap[$sortFlag] : self::SORT_REGULAR;
return asort($array, $plainSortFlag);
}
/**
* Compare two Unicode strings
*
* @param string $str1 The first string to compare
* @param string $str2 The second string to compare
*
* @return Boolean|int Return the comparison result or false on failure:
* 1 if $str1 is greater than $str2
* 0 if $str1 is equal than $str2
* -1 if $str1 is less than $str2
*
* @see http://www.php.net/manual/en/collator.compare.php
*
* @throws MethodNotImplementedException
*/
public function compare($str1, $str2)
{
throw new MethodNotImplementedException(__METHOD__);
}
/**
* Get a value of an integer collator attribute
*
* @param int $attr An attribute specifier, one of the attribute constants
*
* @return Boolean|int The attribute value on success or false on error
*
* @see http://www.php.net/manual/en/collator.getattribute.php
*
* @throws MethodNotImplementedException
*/
public function getAttribute($attr)
{
throw new MethodNotImplementedException(__METHOD__);
}
/**
* Returns collator's last error code. Always returns the U_ZERO_ERROR class constant value
*
* @return int The error code from last collator call
*/
public function getErrorCode()
{
return StubIntl::U_ZERO_ERROR;
}
/**
* Returns collator's last error message. Always returns the U_ZERO_ERROR_MESSAGE class constant value
*
* @return string The error message from last collator call
*/
public function getErrorMessage()
{
return 'U_ZERO_ERROR';
}
/**
* Returns the collator's locale
*
* @param int $type The locale name type to return between valid or actual (StubLocale::VALID_LOCALE or StubLocale::ACTUAL_LOCALE, respectively)
*
* @return string The locale name used to create the collator
*/
public function getLocale($type = StubLocale::ACTUAL_LOCALE)
{
return 'en';
}
/**
* Get sorting key for a string
*
* @param string $string The string to produce the key from
*
* @return string The collation key for $string
*
* @see http://www.php.net/manual/en/collator.getsortkey.php
*
* @throws MethodNotImplementedException
*/
public function getSortKey($string)
{
throw new MethodNotImplementedException(__METHOD__);
}
/**
* Get current collator's strength
*
* @return Boolean|int The current collator's strength or false on failure
*
* @see http://www.php.net/manual/en/collator.getstrength.php
*
* @throws MethodNotImplementedException
*/
public function getStrength()
{
throw new MethodNotImplementedException(__METHOD__);
}
/**
* Set a collator's attribute
*
* @param int $attr An attribute specifier, one of the attribute constants
* @param int $val The attribute value, one of the attribute value constants
*
* @return Boolean True on success or false on failure
*
* @see http://www.php.net/manual/en/collator.setattribute.php
*
* @throws MethodNotImplementedException
*/
public function setAttribute($attr, $val)
{
throw new MethodNotImplementedException(__METHOD__);
}
/**
* Set the collator's strength
*
* @param int $strength Strength to set, possible values:
* StubCollator::PRIMARY
* StubCollator::SECONDARY
* StubCollator::TERTIARY
* StubCollator::QUATERNARY
* StubCollator::IDENTICAL
* StubCollator::DEFAULT
*
* @return Boolean True on success or false on failure
*
* @see http://www.php.net/manual/en/collator.setstrength.php
*
* @throws MethodNotImplementedException
*/
public function setStrength($strength)
{
throw new MethodNotImplementedException(__METHOD__);
}
/**
* Sort array using specified collator and sort keys
*
* @param array &$arr Array of strings to sort
*
* @return Boolean True on success or false on failure
*
* @see http://www.php.net/manual/en/collator.sortwithsortkeys.php
*
* @throws MethodNotImplementedException
*/
public function sortWithSortKeys(&$arr)
{
throw new MethodNotImplementedException(__METHOD__);
}
/**
* Sort array using specified collator
*
* @param array &$arr Array of string to sort
* @param int $sortFlag Optional sorting type, one of the following:
* StubCollator::SORT_REGULAR
* StubCollator::SORT_NUMERIC
* StubCollator::SORT_STRING
*
* @return Boolean True on success or false on failure
*
* @see http://www.php.net/manual/en/collator.sort.php
*
* @throws MethodNotImplementedException
*/
public function sort(&$arr, $sortFlag = self::SORT_REGULAR)
{
throw new MethodNotImplementedException(__METHOD__);
}
}
| houcine88/projet | vendor/symfony/symfony/src/Symfony/Component/Locale/Stub/StubCollator.php | PHP | mit | 8,491 |
/*
* Usage:
*
* <div class="sk-cube-grid">
* <div class="sk-cube sk-cube1"></div>
* <div class="sk-cube sk-cube2"></div>
* <div class="sk-cube sk-cube3"></div>
* <div class="sk-cube sk-cube4"></div>
* <div class="sk-cube sk-cube5"></div>
* <div class="sk-cube sk-cube6"></div>
* <div class="sk-cube sk-cube7"></div>
* <div class="sk-cube sk-cube8"></div>
* <div class="sk-cube sk-cube9"></div>
* </div>
*
*/
.sk-cube-grid {
width: 40px;
height: 40px;
margin: 40px auto;
/*
* Spinner positions
* 1 2 3
* 4 5 6
* 7 8 9
*/ }
.sk-cube-grid .sk-cube {
width: 33%;
height: 33%;
background-color: #333;
float: left;
-webkit-animation: sk-cubeGridScaleDelay 1.3s infinite ease-in-out;
animation: sk-cubeGridScaleDelay 1.3s infinite ease-in-out; }
.sk-cube-grid .sk-cube1 {
-webkit-animation-delay: 0.2s;
animation-delay: 0.2s; }
.sk-cube-grid .sk-cube2 {
-webkit-animation-delay: 0.3s;
animation-delay: 0.3s; }
.sk-cube-grid .sk-cube3 {
-webkit-animation-delay: 0.4s;
animation-delay: 0.4s; }
.sk-cube-grid .sk-cube4 {
-webkit-animation-delay: 0.1s;
animation-delay: 0.1s; }
.sk-cube-grid .sk-cube5 {
-webkit-animation-delay: 0.2s;
animation-delay: 0.2s; }
.sk-cube-grid .sk-cube6 {
-webkit-animation-delay: 0.3s;
animation-delay: 0.3s; }
.sk-cube-grid .sk-cube7 {
-webkit-animation-delay: 0.0s;
animation-delay: 0.0s; }
.sk-cube-grid .sk-cube8 {
-webkit-animation-delay: 0.1s;
animation-delay: 0.1s; }
.sk-cube-grid .sk-cube9 {
-webkit-animation-delay: 0.2s;
animation-delay: 0.2s; }
@-webkit-keyframes sk-cubeGridScaleDelay {
0%, 70%, 100% {
-webkit-transform: scale3D(1, 1, 1);
transform: scale3D(1, 1, 1); }
35% {
-webkit-transform: scale3D(0, 0, 1);
transform: scale3D(0, 0, 1); } }
@keyframes sk-cubeGridScaleDelay {
0%, 70%, 100% {
-webkit-transform: scale3D(1, 1, 1);
transform: scale3D(1, 1, 1); }
35% {
-webkit-transform: scale3D(0, 0, 1);
transform: scale3D(0, 0, 1); } }
| iwdmb/cdnjs | ajax/libs/spinkit/1.2.2/spinners/9-cube-grid.css | CSS | mit | 2,235 |
(function () {
var Bacon, BufferingSource, Bus, CompositeUnsubscribe, ConsumingSource, Desc, Dispatcher, End, Error, Event, EventStream, Exception, Initial, Next, None, Observable, Property, PropertyDispatcher, Some, Source, UpdateBarrier, _, addPropertyInitValueToStream, assert, assertArray, assertEventStream, assertFunction, assertNoArguments, assertObservable, assertObservableIsProperty, assertString, cloneArray, constantToFunction, containsDuplicateDeps, convertArgsToFunction, describe, endEvent, eventIdCounter, eventMethods, findDeps, findHandlerMethods, flatMap_, former, idCounter, initialEvent, isArray, isFieldKey, isObservable, latter, liftCallback, makeFunction, makeFunctionArgs, makeFunction_, makeObservable, makeSpawner, nextEvent, nop, partiallyApplied, recursionDepth, ref, registerObs, spys, toCombinator, toEvent, toFieldExtractor, toFieldKey, toOption, toSimpleExtractor, valueAndEnd, withDescription, withMethodCallSupport, hasProp = {}.hasOwnProperty, extend = function (child, parent) {
for (var key in parent) {
if (hasProp.call(parent, key))
child[key] = parent[key];
}
function ctor() {
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor();
child.__super__ = parent.prototype;
return child;
}, slice = [].slice, bind = function (fn, me) {
return function () {
return fn.apply(me, arguments);
};
};
Bacon = {
toString: function () {
return 'Bacon';
}
};
Bacon.version = '0.7.59';
Exception = (typeof global !== 'undefined' && global !== null ? global : this).Error;
nop = function () {
};
latter = function (_, x) {
return x;
};
former = function (x, _) {
return x;
};
cloneArray = function (xs) {
return xs.slice(0);
};
isArray = function (xs) {
return xs instanceof Array;
};
isObservable = function (x) {
return x instanceof Observable;
};
_ = {
indexOf: Array.prototype.indexOf ? function (xs, x) {
return xs.indexOf(x);
} : function (xs, x) {
var i, j, len1, y;
for (i = j = 0, len1 = xs.length; j < len1; i = ++j) {
y = xs[i];
if (x === y) {
return i;
}
}
return -1;
},
indexWhere: function (xs, f) {
var i, j, len1, y;
for (i = j = 0, len1 = xs.length; j < len1; i = ++j) {
y = xs[i];
if (f(y)) {
return i;
}
}
return -1;
},
head: function (xs) {
return xs[0];
},
always: function (x) {
return function () {
return x;
};
},
negate: function (f) {
return function (x) {
return !f(x);
};
},
empty: function (xs) {
return xs.length === 0;
},
tail: function (xs) {
return xs.slice(1, xs.length);
},
filter: function (f, xs) {
var filtered, j, len1, x;
filtered = [];
for (j = 0, len1 = xs.length; j < len1; j++) {
x = xs[j];
if (f(x)) {
filtered.push(x);
}
}
return filtered;
},
map: function (f, xs) {
var j, len1, results, x;
results = [];
for (j = 0, len1 = xs.length; j < len1; j++) {
x = xs[j];
results.push(f(x));
}
return results;
},
each: function (xs, f) {
var key, value;
for (key in xs) {
value = xs[key];
f(key, value);
}
return void 0;
},
toArray: function (xs) {
if (isArray(xs)) {
return xs;
} else {
return [xs];
}
},
contains: function (xs, x) {
return _.indexOf(xs, x) !== -1;
},
id: function (x) {
return x;
},
last: function (xs) {
return xs[xs.length - 1];
},
all: function (xs, f) {
var j, len1, x;
if (f == null) {
f = _.id;
}
for (j = 0, len1 = xs.length; j < len1; j++) {
x = xs[j];
if (!f(x)) {
return false;
}
}
return true;
},
any: function (xs, f) {
var j, len1, x;
if (f == null) {
f = _.id;
}
for (j = 0, len1 = xs.length; j < len1; j++) {
x = xs[j];
if (f(x)) {
return true;
}
}
return false;
},
without: function (x, xs) {
return _.filter(function (y) {
return y !== x;
}, xs);
},
remove: function (x, xs) {
var i;
i = _.indexOf(xs, x);
if (i >= 0) {
return xs.splice(i, 1);
}
},
fold: function (xs, seed, f) {
var j, len1, x;
for (j = 0, len1 = xs.length; j < len1; j++) {
x = xs[j];
seed = f(seed, x);
}
return seed;
},
flatMap: function (f, xs) {
return _.fold(xs, [], function (ys, x) {
return ys.concat(f(x));
});
},
cached: function (f) {
var value;
value = None;
return function () {
if (value === None) {
value = f();
f = void 0;
}
return value;
};
},
isFunction: function (f) {
return typeof f === 'function';
},
toString: function (obj) {
var ex, internals, key, value;
try {
recursionDepth++;
if (obj == null) {
return 'undefined';
} else if (_.isFunction(obj)) {
return 'function';
} else if (isArray(obj)) {
if (recursionDepth > 5) {
return '[..]';
}
return '[' + _.map(_.toString, obj).toString() + ']';
} else if ((obj != null ? obj.toString : void 0) != null && obj.toString !== Object.prototype.toString) {
return obj.toString();
} else if (typeof obj === 'object') {
if (recursionDepth > 5) {
return '{..}';
}
internals = function () {
var results;
results = [];
for (key in obj) {
if (!hasProp.call(obj, key))
continue;
value = function () {
try {
return obj[key];
} catch (_error) {
ex = _error;
return ex;
}
}();
results.push(_.toString(key) + ':' + _.toString(value));
}
return results;
}();
return '{' + internals + '}';
} else {
return obj;
}
} finally {
recursionDepth--;
}
}
};
recursionDepth = 0;
Bacon._ = _;
UpdateBarrier = Bacon.UpdateBarrier = function () {
var afterTransaction, afters, aftersIndex, currentEventId, flush, flushDepsOf, flushWaiters, hasWaiters, inTransaction, rootEvent, waiterObs, waiters, whenDoneWith, wrappedSubscribe;
rootEvent = void 0;
waiterObs = [];
waiters = {};
afters = [];
aftersIndex = 0;
afterTransaction = function (f) {
if (rootEvent) {
return afters.push(f);
} else {
return f();
}
};
whenDoneWith = function (obs, f) {
var obsWaiters;
if (rootEvent) {
obsWaiters = waiters[obs.id];
if (obsWaiters == null) {
obsWaiters = waiters[obs.id] = [f];
return waiterObs.push(obs);
} else {
return obsWaiters.push(f);
}
} else {
return f();
}
};
flush = function () {
while (waiterObs.length > 0) {
flushWaiters(0);
}
return void 0;
};
flushWaiters = function (index) {
var f, j, len1, obs, obsId, obsWaiters;
obs = waiterObs[index];
obsId = obs.id;
obsWaiters = waiters[obsId];
waiterObs.splice(index, 1);
delete waiters[obsId];
flushDepsOf(obs);
for (j = 0, len1 = obsWaiters.length; j < len1; j++) {
f = obsWaiters[j];
f();
}
return void 0;
};
flushDepsOf = function (obs) {
var dep, deps, index, j, len1;
deps = obs.internalDeps();
for (j = 0, len1 = deps.length; j < len1; j++) {
dep = deps[j];
flushDepsOf(dep);
if (waiters[dep.id]) {
index = _.indexOf(waiterObs, dep);
flushWaiters(index);
}
}
return void 0;
};
inTransaction = function (event, context, f, args) {
var after, result;
if (rootEvent) {
return f.apply(context, args);
} else {
rootEvent = event;
try {
result = f.apply(context, args);
flush();
} finally {
rootEvent = void 0;
while (aftersIndex < afters.length) {
after = afters[aftersIndex];
aftersIndex++;
after();
}
aftersIndex = 0;
afters = [];
}
return result;
}
};
currentEventId = function () {
if (rootEvent) {
return rootEvent.id;
} else {
return void 0;
}
};
wrappedSubscribe = function (obs, sink) {
var doUnsub, shouldUnsub, unsub, unsubd;
unsubd = false;
shouldUnsub = false;
doUnsub = function () {
return shouldUnsub = true;
};
unsub = function () {
unsubd = true;
return doUnsub();
};
doUnsub = obs.dispatcher.subscribe(function (event) {
return afterTransaction(function () {
var reply;
if (!unsubd) {
reply = sink(event);
if (reply === Bacon.noMore) {
return unsub();
}
}
});
});
if (shouldUnsub) {
doUnsub();
}
return unsub;
};
hasWaiters = function () {
return waiterObs.length > 0;
};
return {
whenDoneWith: whenDoneWith,
hasWaiters: hasWaiters,
inTransaction: inTransaction,
currentEventId: currentEventId,
wrappedSubscribe: wrappedSubscribe,
afterTransaction: afterTransaction
};
}();
Source = function () {
function Source(obs1, sync, lazy1) {
this.obs = obs1;
this.sync = sync;
this.lazy = lazy1 != null ? lazy1 : false;
this.queue = [];
}
Source.prototype.subscribe = function (sink) {
return this.obs.dispatcher.subscribe(sink);
};
Source.prototype.toString = function () {
return this.obs.toString();
};
Source.prototype.markEnded = function () {
return this.ended = true;
};
Source.prototype.consume = function () {
if (this.lazy) {
return { value: _.always(this.queue[0]) };
} else {
return this.queue[0];
}
};
Source.prototype.push = function (x) {
return this.queue = [x];
};
Source.prototype.mayHave = function () {
return true;
};
Source.prototype.hasAtLeast = function () {
return this.queue.length;
};
Source.prototype.flatten = true;
return Source;
}();
ConsumingSource = function (superClass) {
extend(ConsumingSource, superClass);
function ConsumingSource() {
return ConsumingSource.__super__.constructor.apply(this, arguments);
}
ConsumingSource.prototype.consume = function () {
return this.queue.shift();
};
ConsumingSource.prototype.push = function (x) {
return this.queue.push(x);
};
ConsumingSource.prototype.mayHave = function (c) {
return !this.ended || this.queue.length >= c;
};
ConsumingSource.prototype.hasAtLeast = function (c) {
return this.queue.length >= c;
};
ConsumingSource.prototype.flatten = false;
return ConsumingSource;
}(Source);
BufferingSource = function (superClass) {
extend(BufferingSource, superClass);
function BufferingSource(obs) {
BufferingSource.__super__.constructor.call(this, obs, true);
}
BufferingSource.prototype.consume = function () {
var values;
values = this.queue;
this.queue = [];
return {
value: function () {
return values;
}
};
};
BufferingSource.prototype.push = function (x) {
return this.queue.push(x.value());
};
BufferingSource.prototype.hasAtLeast = function () {
return true;
};
return BufferingSource;
}(Source);
Source.isTrigger = function (s) {
if (s instanceof Source) {
return s.sync;
} else {
return s instanceof EventStream;
}
};
Source.fromObservable = function (s) {
if (s instanceof Source) {
return s;
} else if (s instanceof Property) {
return new Source(s, false);
} else {
return new ConsumingSource(s, true);
}
};
Desc = function () {
function Desc(context1, method1, args1) {
this.context = context1;
this.method = method1;
this.args = args1;
this.cached = void 0;
}
Desc.prototype.deps = function () {
return this.cached || (this.cached = findDeps([this.context].concat(this.args)));
};
Desc.prototype.apply = function (obs) {
obs.desc = this;
return obs;
};
Desc.prototype.toString = function () {
return _.toString(this.context) + '.' + _.toString(this.method) + '(' + _.map(_.toString, this.args) + ')';
};
return Desc;
}();
describe = function () {
var args, context, method;
context = arguments[0], method = arguments[1], args = 3 <= arguments.length ? slice.call(arguments, 2) : [];
if ((context || method) instanceof Desc) {
return context || method;
} else {
return new Desc(context, method, args);
}
};
withDescription = function () {
var desc, j, obs;
desc = 2 <= arguments.length ? slice.call(arguments, 0, j = arguments.length - 1) : (j = 0, []), obs = arguments[j++];
return describe.apply(null, desc).apply(obs);
};
findDeps = function (x) {
if (isArray(x)) {
return _.flatMap(findDeps, x);
} else if (isObservable(x)) {
return [x];
} else if (x instanceof Source) {
return [x.obs];
} else {
return [];
}
};
withMethodCallSupport = function (wrapped) {
return function () {
var args, context, f, methodName;
f = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
if (typeof f === 'object' && args.length) {
context = f;
methodName = args[0];
f = function () {
return context[methodName].apply(context, arguments);
};
args = args.slice(1);
}
return wrapped.apply(null, [f].concat(slice.call(args)));
};
};
makeFunctionArgs = function (args) {
args = Array.prototype.slice.call(args);
return makeFunction_.apply(null, args);
};
partiallyApplied = function (f, applied) {
return function () {
var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return f.apply(null, applied.concat(args));
};
};
toSimpleExtractor = function (args) {
return function (key) {
return function (value) {
var fieldValue;
if (value == null) {
return void 0;
} else {
fieldValue = value[key];
if (_.isFunction(fieldValue)) {
return fieldValue.apply(value, args);
} else {
return fieldValue;
}
}
};
};
};
toFieldExtractor = function (f, args) {
var partFuncs, parts;
parts = f.slice(1).split('.');
partFuncs = _.map(toSimpleExtractor(args), parts);
return function (value) {
var j, len1;
for (j = 0, len1 = partFuncs.length; j < len1; j++) {
f = partFuncs[j];
value = f(value);
}
return value;
};
};
isFieldKey = function (f) {
return typeof f === 'string' && f.length > 1 && f.charAt(0) === '.';
};
makeFunction_ = withMethodCallSupport(function () {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
if (_.isFunction(f)) {
if (args.length) {
return partiallyApplied(f, args);
} else {
return f;
}
} else if (isFieldKey(f)) {
return toFieldExtractor(f, args);
} else {
return _.always(f);
}
});
makeFunction = function (f, args) {
return makeFunction_.apply(null, [f].concat(slice.call(args)));
};
convertArgsToFunction = function (obs, f, args, method) {
var sampled;
if (f instanceof Property) {
sampled = f.sampledBy(obs, function (p, s) {
return [
p,
s
];
});
return method.call(sampled, function (arg) {
var p, s;
p = arg[0], s = arg[1];
return p;
}).map(function (arg) {
var p, s;
p = arg[0], s = arg[1];
return s;
});
} else {
f = makeFunction(f, args);
return method.call(obs, f);
}
};
toCombinator = function (f) {
var key;
if (_.isFunction(f)) {
return f;
} else if (isFieldKey(f)) {
key = toFieldKey(f);
return function (left, right) {
return left[key](right);
};
} else {
throw new Exception('not a function or a field key: ' + f);
}
};
toFieldKey = function (f) {
return f.slice(1);
};
Some = function () {
function Some(value1) {
this.value = value1;
}
Some.prototype.getOrElse = function () {
return this.value;
};
Some.prototype.get = function () {
return this.value;
};
Some.prototype.filter = function (f) {
if (f(this.value)) {
return new Some(this.value);
} else {
return None;
}
};
Some.prototype.map = function (f) {
return new Some(f(this.value));
};
Some.prototype.forEach = function (f) {
return f(this.value);
};
Some.prototype.isDefined = true;
Some.prototype.toArray = function () {
return [this.value];
};
Some.prototype.inspect = function () {
return 'Some(' + this.value + ')';
};
Some.prototype.toString = function () {
return this.inspect();
};
return Some;
}();
None = {
getOrElse: function (value) {
return value;
},
filter: function () {
return None;
},
map: function () {
return None;
},
forEach: function () {
},
isDefined: false,
toArray: function () {
return [];
},
inspect: function () {
return 'None';
},
toString: function () {
return this.inspect();
}
};
toOption = function (v) {
if (v instanceof Some || v === None) {
return v;
} else {
return new Some(v);
}
};
Bacon.noMore = ['<no-more>'];
Bacon.more = ['<more>'];
eventIdCounter = 0;
Event = function () {
function Event() {
this.id = ++eventIdCounter;
}
Event.prototype.isEvent = function () {
return true;
};
Event.prototype.isEnd = function () {
return false;
};
Event.prototype.isInitial = function () {
return false;
};
Event.prototype.isNext = function () {
return false;
};
Event.prototype.isError = function () {
return false;
};
Event.prototype.hasValue = function () {
return false;
};
Event.prototype.filter = function () {
return true;
};
Event.prototype.inspect = function () {
return this.toString();
};
Event.prototype.log = function () {
return this.toString();
};
return Event;
}();
Next = function (superClass) {
extend(Next, superClass);
function Next(valueF, eager) {
Next.__super__.constructor.call(this);
if (!eager && _.isFunction(valueF) || valueF instanceof Next) {
this.valueF = valueF;
this.valueInternal = void 0;
} else {
this.valueF = void 0;
this.valueInternal = valueF;
}
}
Next.prototype.isNext = function () {
return true;
};
Next.prototype.hasValue = function () {
return true;
};
Next.prototype.value = function () {
if (this.valueF instanceof Next) {
this.valueInternal = this.valueF.value();
this.valueF = void 0;
} else if (this.valueF) {
this.valueInternal = this.valueF();
this.valueF = void 0;
}
return this.valueInternal;
};
Next.prototype.fmap = function (f) {
var event, value;
if (this.valueInternal) {
value = this.valueInternal;
return this.apply(function () {
return f(value);
});
} else {
event = this;
return this.apply(function () {
return f(event.value());
});
}
};
Next.prototype.apply = function (value) {
return new Next(value);
};
Next.prototype.filter = function (f) {
return f(this.value());
};
Next.prototype.toString = function () {
return _.toString(this.value());
};
Next.prototype.log = function () {
return this.value();
};
return Next;
}(Event);
Initial = function (superClass) {
extend(Initial, superClass);
function Initial() {
return Initial.__super__.constructor.apply(this, arguments);
}
Initial.prototype.isInitial = function () {
return true;
};
Initial.prototype.isNext = function () {
return false;
};
Initial.prototype.apply = function (value) {
return new Initial(value);
};
Initial.prototype.toNext = function () {
return new Next(this);
};
return Initial;
}(Next);
End = function (superClass) {
extend(End, superClass);
function End() {
return End.__super__.constructor.apply(this, arguments);
}
End.prototype.isEnd = function () {
return true;
};
End.prototype.fmap = function () {
return this;
};
End.prototype.apply = function () {
return this;
};
End.prototype.toString = function () {
return '<end>';
};
return End;
}(Event);
Error = function (superClass) {
extend(Error, superClass);
function Error(error1) {
this.error = error1;
}
Error.prototype.isError = function () {
return true;
};
Error.prototype.fmap = function () {
return this;
};
Error.prototype.apply = function () {
return this;
};
Error.prototype.toString = function () {
return '<error> ' + _.toString(this.error);
};
return Error;
}(Event);
Bacon.Event = Event;
Bacon.Initial = Initial;
Bacon.Next = Next;
Bacon.End = End;
Bacon.Error = Error;
initialEvent = function (value) {
return new Initial(value, true);
};
nextEvent = function (value) {
return new Next(value, true);
};
endEvent = function () {
return new End();
};
toEvent = function (x) {
if (x instanceof Event) {
return x;
} else {
return nextEvent(x);
}
};
idCounter = 0;
registerObs = function () {
};
Observable = function () {
function Observable(desc) {
this.id = ++idCounter;
withDescription(desc, this);
this.initialDesc = this.desc;
}
Observable.prototype.subscribe = function (sink) {
return UpdateBarrier.wrappedSubscribe(this, sink);
};
Observable.prototype.subscribeInternal = function (sink) {
return this.dispatcher.subscribe(sink);
};
Observable.prototype.onValue = function () {
var f;
f = makeFunctionArgs(arguments);
return this.subscribe(function (event) {
if (event.hasValue()) {
return f(event.value());
}
});
};
Observable.prototype.onValues = function (f) {
return this.onValue(function (args) {
return f.apply(null, args);
});
};
Observable.prototype.onError = function () {
var f;
f = makeFunctionArgs(arguments);
return this.subscribe(function (event) {
if (event.isError()) {
return f(event.error);
}
});
};
Observable.prototype.onEnd = function () {
var f;
f = makeFunctionArgs(arguments);
return this.subscribe(function (event) {
if (event.isEnd()) {
return f();
}
});
};
Observable.prototype.name = function (name) {
this._name = name;
return this;
};
Observable.prototype.withDescription = function () {
return describe.apply(null, arguments).apply(this);
};
Observable.prototype.toString = function () {
if (this._name) {
return this._name;
} else {
return this.desc.toString();
}
};
Observable.prototype.internalDeps = function () {
return this.initialDesc.deps();
};
return Observable;
}();
Observable.prototype.assign = Observable.prototype.onValue;
Observable.prototype.forEach = Observable.prototype.onValue;
Observable.prototype.inspect = Observable.prototype.toString;
Bacon.Observable = Observable;
CompositeUnsubscribe = function () {
function CompositeUnsubscribe(ss) {
var j, len1, s;
if (ss == null) {
ss = [];
}
this.unsubscribe = bind(this.unsubscribe, this);
this.unsubscribed = false;
this.subscriptions = [];
this.starting = [];
for (j = 0, len1 = ss.length; j < len1; j++) {
s = ss[j];
this.add(s);
}
}
CompositeUnsubscribe.prototype.add = function (subscription) {
var ended, unsub, unsubMe;
if (this.unsubscribed) {
return;
}
ended = false;
unsub = nop;
this.starting.push(subscription);
unsubMe = function (_this) {
return function () {
if (_this.unsubscribed) {
return;
}
ended = true;
_this.remove(unsub);
return _.remove(subscription, _this.starting);
};
}(this);
unsub = subscription(this.unsubscribe, unsubMe);
if (!(this.unsubscribed || ended)) {
this.subscriptions.push(unsub);
} else {
unsub();
}
_.remove(subscription, this.starting);
return unsub;
};
CompositeUnsubscribe.prototype.remove = function (unsub) {
if (this.unsubscribed) {
return;
}
if (_.remove(unsub, this.subscriptions) !== void 0) {
return unsub();
}
};
CompositeUnsubscribe.prototype.unsubscribe = function () {
var j, len1, ref, s;
if (this.unsubscribed) {
return;
}
this.unsubscribed = true;
ref = this.subscriptions;
for (j = 0, len1 = ref.length; j < len1; j++) {
s = ref[j];
s();
}
this.subscriptions = [];
return this.starting = [];
};
CompositeUnsubscribe.prototype.count = function () {
if (this.unsubscribed) {
return 0;
}
return this.subscriptions.length + this.starting.length;
};
CompositeUnsubscribe.prototype.empty = function () {
return this.count() === 0;
};
return CompositeUnsubscribe;
}();
Bacon.CompositeUnsubscribe = CompositeUnsubscribe;
Dispatcher = function () {
function Dispatcher(_subscribe, _handleEvent) {
this._subscribe = _subscribe;
this._handleEvent = _handleEvent;
this.subscribe = bind(this.subscribe, this);
this.handleEvent = bind(this.handleEvent, this);
this.subscriptions = [];
this.queue = [];
this.pushing = false;
this.ended = false;
this.prevError = void 0;
this.unsubSrc = void 0;
}
Dispatcher.prototype.hasSubscribers = function () {
return this.subscriptions.length > 0;
};
Dispatcher.prototype.removeSub = function (subscription) {
return this.subscriptions = _.without(subscription, this.subscriptions);
};
Dispatcher.prototype.push = function (event) {
if (event.isEnd()) {
this.ended = true;
}
return UpdateBarrier.inTransaction(event, this, this.pushIt, [event]);
};
Dispatcher.prototype.pushToSubscriptions = function (event) {
var e, j, len1, reply, sub, tmp;
try {
tmp = this.subscriptions;
for (j = 0, len1 = tmp.length; j < len1; j++) {
sub = tmp[j];
reply = sub.sink(event);
if (reply === Bacon.noMore || event.isEnd()) {
this.removeSub(sub);
}
}
return true;
} catch (_error) {
e = _error;
this.pushing = false;
this.queue = [];
throw e;
}
};
Dispatcher.prototype.pushIt = function (event) {
if (!this.pushing) {
if (event === this.prevError) {
return;
}
if (event.isError()) {
this.prevError = event;
}
this.pushing = true;
this.pushToSubscriptions(event);
this.pushing = false;
while (this.queue.length) {
event = this.queue.shift();
this.push(event);
}
if (this.hasSubscribers()) {
return Bacon.more;
} else {
this.unsubscribeFromSource();
return Bacon.noMore;
}
} else {
this.queue.push(event);
return Bacon.more;
}
};
Dispatcher.prototype.handleEvent = function (event) {
if (this._handleEvent) {
return this._handleEvent(event);
} else {
return this.push(event);
}
};
Dispatcher.prototype.unsubscribeFromSource = function () {
if (this.unsubSrc) {
this.unsubSrc();
}
return this.unsubSrc = void 0;
};
Dispatcher.prototype.subscribe = function (sink) {
var subscription;
if (this.ended) {
sink(endEvent());
return nop;
} else {
subscription = { sink: sink };
this.subscriptions.push(subscription);
if (this.subscriptions.length === 1) {
this.unsubSrc = this._subscribe(this.handleEvent);
}
return function (_this) {
return function () {
_this.removeSub(subscription);
if (!_this.hasSubscribers()) {
return _this.unsubscribeFromSource();
}
};
}(this);
}
};
return Dispatcher;
}();
EventStream = function (superClass) {
extend(EventStream, superClass);
function EventStream(desc, subscribe, handler) {
if (_.isFunction(desc)) {
handler = subscribe;
subscribe = desc;
desc = [];
}
EventStream.__super__.constructor.call(this, desc);
this.dispatcher = new Dispatcher(subscribe, handler);
registerObs(this);
}
EventStream.prototype.toProperty = function (initValue_) {
var disp, initValue;
initValue = arguments.length === 0 ? None : toOption(function () {
return initValue_;
});
disp = this.dispatcher;
return new Property(describe(this, 'toProperty', initValue_), function (sink) {
var initSent, reply, sendInit, unsub;
initSent = false;
unsub = nop;
reply = Bacon.more;
sendInit = function () {
if (!initSent) {
return initValue.forEach(function (value) {
initSent = true;
reply = sink(new Initial(value));
if (reply === Bacon.noMore) {
unsub();
return unsub = nop;
}
});
}
};
unsub = disp.subscribe(function (event) {
if (event.hasValue()) {
if (initSent && event.isInitial()) {
return Bacon.more;
} else {
if (!event.isInitial()) {
sendInit();
}
initSent = true;
initValue = new Some(event);
return sink(event);
}
} else {
if (event.isEnd()) {
reply = sendInit();
}
if (reply !== Bacon.noMore) {
return sink(event);
}
}
});
sendInit();
return unsub;
});
};
EventStream.prototype.toEventStream = function () {
return this;
};
EventStream.prototype.withHandler = function (handler) {
return new EventStream(describe(this, 'withHandler', handler), this.dispatcher.subscribe, handler);
};
return EventStream;
}(Observable);
Bacon.EventStream = EventStream;
Bacon.never = function () {
return new EventStream(describe(Bacon, 'never'), function (sink) {
sink(endEvent());
return nop;
});
};
Bacon.when = function () {
var f, i, index, ix, j, k, len, len1, len2, needsBarrier, pat, patSources, pats, patterns, ref, resultStream, s, sources, triggerFound, usage;
if (arguments.length === 0) {
return Bacon.never();
}
len = arguments.length;
usage = 'when: expecting arguments in the form (Observable+,function)+';
sources = [];
pats = [];
i = 0;
patterns = [];
while (i < len) {
patterns[i] = arguments[i];
patterns[i + 1] = arguments[i + 1];
patSources = _.toArray(arguments[i]);
f = constantToFunction(arguments[i + 1]);
pat = {
f: f,
ixs: []
};
triggerFound = false;
for (j = 0, len1 = patSources.length; j < len1; j++) {
s = patSources[j];
index = _.indexOf(sources, s);
if (!triggerFound) {
triggerFound = Source.isTrigger(s);
}
if (index < 0) {
sources.push(s);
index = sources.length - 1;
}
ref = pat.ixs;
for (k = 0, len2 = ref.length; k < len2; k++) {
ix = ref[k];
if (ix.index === index) {
ix.count++;
}
}
pat.ixs.push({
index: index,
count: 1
});
}
if (patSources.length > 0) {
pats.push(pat);
}
i = i + 2;
}
if (!sources.length) {
return Bacon.never();
}
sources = _.map(Source.fromObservable, sources);
needsBarrier = _.any(sources, function (s) {
return s.flatten;
}) && containsDuplicateDeps(_.map(function (s) {
return s.obs;
}, sources));
return resultStream = new EventStream(describe.apply(null, [
Bacon,
'when'
].concat(slice.call(patterns))), function (sink) {
var cannotMatch, cannotSync, ends, match, nonFlattened, part, triggers;
triggers = [];
ends = false;
match = function (p) {
var l, len3, ref1;
ref1 = p.ixs;
for (l = 0, len3 = ref1.length; l < len3; l++) {
i = ref1[l];
if (!sources[i.index].hasAtLeast(i.count)) {
return false;
}
}
return true;
};
cannotSync = function (source) {
return !source.sync || source.ended;
};
cannotMatch = function (p) {
var l, len3, ref1;
ref1 = p.ixs;
for (l = 0, len3 = ref1.length; l < len3; l++) {
i = ref1[l];
if (!sources[i.index].mayHave(i.count)) {
return true;
}
}
};
nonFlattened = function (trigger) {
return !trigger.source.flatten;
};
part = function (source) {
return function (unsubAll) {
var flush, flushLater, flushWhileTriggers;
flushLater = function () {
return UpdateBarrier.whenDoneWith(resultStream, flush);
};
flushWhileTriggers = function () {
var events, l, len3, p, reply, trigger;
if (triggers.length > 0) {
reply = Bacon.more;
trigger = triggers.pop();
for (l = 0, len3 = pats.length; l < len3; l++) {
p = pats[l];
if (match(p)) {
events = function () {
var len4, m, ref1, results;
ref1 = p.ixs;
results = [];
for (m = 0, len4 = ref1.length; m < len4; m++) {
i = ref1[m];
results.push(sources[i.index].consume());
}
return results;
}();
reply = sink(trigger.e.apply(function () {
var event, values;
values = function () {
var len4, m, results;
results = [];
for (m = 0, len4 = events.length; m < len4; m++) {
event = events[m];
results.push(event.value());
}
return results;
}();
return p.f.apply(p, values);
}));
if (triggers.length) {
triggers = _.filter(nonFlattened, triggers);
}
if (reply === Bacon.noMore) {
return reply;
} else {
return flushWhileTriggers();
}
}
}
} else {
return Bacon.more;
}
};
flush = function () {
var reply;
reply = flushWhileTriggers();
if (ends) {
ends = false;
if (_.all(sources, cannotSync) || _.all(pats, cannotMatch)) {
reply = Bacon.noMore;
sink(endEvent());
}
}
if (reply === Bacon.noMore) {
unsubAll();
}
return reply;
};
return source.subscribe(function (e) {
var reply;
if (e.isEnd()) {
ends = true;
source.markEnded();
flushLater();
} else if (e.isError()) {
reply = sink(e);
} else {
source.push(e);
if (source.sync) {
triggers.push({
source: source,
e: e
});
if (needsBarrier || UpdateBarrier.hasWaiters()) {
flushLater();
} else {
flush();
}
}
}
if (reply === Bacon.noMore) {
unsubAll();
}
return reply || Bacon.more;
});
};
};
return new Bacon.CompositeUnsubscribe(function () {
var l, len3, results;
results = [];
for (l = 0, len3 = sources.length; l < len3; l++) {
s = sources[l];
results.push(part(s));
}
return results;
}()).unsubscribe;
});
};
containsDuplicateDeps = function (observables, state) {
var checkObservable;
if (state == null) {
state = [];
}
checkObservable = function (obs) {
var deps;
if (_.contains(state, obs)) {
return true;
} else {
deps = obs.internalDeps();
if (deps.length) {
state.push(obs);
return _.any(deps, checkObservable);
} else {
state.push(obs);
return false;
}
}
};
return _.any(observables, checkObservable);
};
constantToFunction = function (f) {
if (_.isFunction(f)) {
return f;
} else {
return _.always(f);
}
};
Bacon.groupSimultaneous = function () {
var s, sources, streams;
streams = 1 <= arguments.length ? slice.call(arguments, 0) : [];
if (streams.length === 1 && isArray(streams[0])) {
streams = streams[0];
}
sources = function () {
var j, len1, results;
results = [];
for (j = 0, len1 = streams.length; j < len1; j++) {
s = streams[j];
results.push(new BufferingSource(s));
}
return results;
}();
return withDescription.apply(null, [
Bacon,
'groupSimultaneous'
].concat(slice.call(streams), [Bacon.when(sources, function () {
var xs;
xs = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return xs;
})]));
};
PropertyDispatcher = function (superClass) {
extend(PropertyDispatcher, superClass);
function PropertyDispatcher(property1, subscribe, handleEvent) {
this.property = property1;
this.subscribe = bind(this.subscribe, this);
PropertyDispatcher.__super__.constructor.call(this, subscribe, handleEvent);
this.current = None;
this.currentValueRootId = void 0;
this.propertyEnded = false;
}
PropertyDispatcher.prototype.push = function (event) {
if (event.isEnd()) {
this.propertyEnded = true;
}
if (event.hasValue()) {
this.current = new Some(event);
this.currentValueRootId = UpdateBarrier.currentEventId();
}
return PropertyDispatcher.__super__.push.call(this, event);
};
PropertyDispatcher.prototype.maybeSubSource = function (sink, reply) {
if (reply === Bacon.noMore) {
return nop;
} else if (this.propertyEnded) {
sink(endEvent());
return nop;
} else {
return Dispatcher.prototype.subscribe.call(this, sink);
}
};
PropertyDispatcher.prototype.subscribe = function (sink) {
var dispatchingId, initSent, reply, valId;
initSent = false;
reply = Bacon.more;
if (this.current.isDefined && (this.hasSubscribers() || this.propertyEnded)) {
dispatchingId = UpdateBarrier.currentEventId();
valId = this.currentValueRootId;
if (!this.propertyEnded && valId && dispatchingId && dispatchingId !== valId) {
UpdateBarrier.whenDoneWith(this.property, function (_this) {
return function () {
if (_this.currentValueRootId === valId) {
return sink(initialEvent(_this.current.get().value()));
}
};
}(this));
return this.maybeSubSource(sink, reply);
} else {
UpdateBarrier.inTransaction(void 0, this, function () {
return reply = sink(initialEvent(this.current.get().value()));
}, []);
return this.maybeSubSource(sink, reply);
}
} else {
return this.maybeSubSource(sink, reply);
}
};
return PropertyDispatcher;
}(Dispatcher);
Property = function (superClass) {
extend(Property, superClass);
function Property(desc, subscribe, handler) {
if (_.isFunction(desc)) {
handler = subscribe;
subscribe = desc;
desc = [];
}
Property.__super__.constructor.call(this, desc);
this.dispatcher = new PropertyDispatcher(this, subscribe, handler);
registerObs(this);
}
Property.prototype.changes = function () {
return new EventStream(describe(this, 'changes'), function (_this) {
return function (sink) {
return _this.dispatcher.subscribe(function (event) {
if (!event.isInitial()) {
return sink(event);
}
});
};
}(this));
};
Property.prototype.withHandler = function (handler) {
return new Property(describe(this, 'withHandler', handler), this.dispatcher.subscribe, handler);
};
Property.prototype.toProperty = function () {
return this;
};
Property.prototype.toEventStream = function () {
return new EventStream(describe(this, 'toEventStream'), function (_this) {
return function (sink) {
return _this.dispatcher.subscribe(function (event) {
if (event.isInitial()) {
event = event.toNext();
}
return sink(event);
});
};
}(this));
};
return Property;
}(Observable);
Bacon.Property = Property;
Bacon.constant = function (value) {
return new Property(describe(Bacon, 'constant', value), function (sink) {
sink(initialEvent(value));
sink(endEvent());
return nop;
});
};
Bacon.fromBinder = function (binder, eventTransformer) {
if (eventTransformer == null) {
eventTransformer = _.id;
}
return new EventStream(describe(Bacon, 'fromBinder', binder, eventTransformer), function (sink) {
var shouldUnbind, unbind, unbinder, unbound;
unbound = false;
shouldUnbind = false;
unbind = function () {
if (!unbound) {
if (typeof unbinder !== 'undefined' && unbinder !== null) {
unbinder();
return unbound = true;
} else {
return shouldUnbind = true;
}
}
};
unbinder = binder(function () {
var args, event, j, len1, reply, value;
args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
value = eventTransformer.apply(this, args);
if (!(isArray(value) && _.last(value) instanceof Event)) {
value = [value];
}
reply = Bacon.more;
for (j = 0, len1 = value.length; j < len1; j++) {
event = value[j];
reply = sink(event = toEvent(event));
if (reply === Bacon.noMore || event.isEnd()) {
unbind();
return reply;
}
}
return reply;
});
if (shouldUnbind) {
unbind();
}
return unbind;
});
};
eventMethods = [
[
'addEventListener',
'removeEventListener'
],
[
'addListener',
'removeListener'
],
[
'on',
'off'
],
[
'bind',
'unbind'
]
];
findHandlerMethods = function (target) {
var j, len1, methodPair, pair;
for (j = 0, len1 = eventMethods.length; j < len1; j++) {
pair = eventMethods[j];
methodPair = [
target[pair[0]],
target[pair[1]]
];
if (methodPair[0] && methodPair[1]) {
return methodPair;
}
}
throw new Error('No suitable event methods in ' + target);
};
Bacon.fromEventTarget = function (target, eventName, eventTransformer) {
var ref, sub, unsub;
ref = findHandlerMethods(target), sub = ref[0], unsub = ref[1];
return withDescription(Bacon, 'fromEvent', target, eventName, Bacon.fromBinder(function (handler) {
sub.call(target, eventName, handler);
return function () {
return unsub.call(target, eventName, handler);
};
}, eventTransformer));
};
Bacon.fromEvent = Bacon.fromEventTarget;
Bacon.Observable.prototype.map = function () {
var args, p;
p = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
return convertArgsToFunction(this, p, args, function (f) {
return withDescription(this, 'map', f, this.withHandler(function (event) {
return this.push(event.fmap(f));
}));
});
};
Bacon.combineAsArray = function () {
var index, j, len1, s, sources, stream, streams;
streams = 1 <= arguments.length ? slice.call(arguments, 0) : [];
if (streams.length === 1 && isArray(streams[0])) {
streams = streams[0];
}
for (index = j = 0, len1 = streams.length; j < len1; index = ++j) {
stream = streams[index];
if (!isObservable(stream)) {
streams[index] = Bacon.constant(stream);
}
}
if (streams.length) {
sources = function () {
var k, len2, results;
results = [];
for (k = 0, len2 = streams.length; k < len2; k++) {
s = streams[k];
results.push(new Source(s, true));
}
return results;
}();
return withDescription.apply(null, [
Bacon,
'combineAsArray'
].concat(slice.call(streams), [Bacon.when(sources, function () {
var xs;
xs = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return xs;
}).toProperty()]));
} else {
return Bacon.constant([]);
}
};
Bacon.onValues = function () {
var f, j, streams;
streams = 2 <= arguments.length ? slice.call(arguments, 0, j = arguments.length - 1) : (j = 0, []), f = arguments[j++];
return Bacon.combineAsArray(streams).onValues(f);
};
Bacon.combineWith = function () {
var f, streams;
f = arguments[0], streams = 2 <= arguments.length ? slice.call(arguments, 1) : [];
return withDescription.apply(null, [
Bacon,
'combineWith',
f
].concat(slice.call(streams), [Bacon.combineAsArray(streams).map(function (values) {
return f.apply(null, values);
})]));
};
Bacon.combineTemplate = function (template) {
var applyStreamValue, combinator, compile, compileTemplate, constantValue, current, funcs, mkContext, setValue, streams;
funcs = [];
streams = [];
current = function (ctxStack) {
return ctxStack[ctxStack.length - 1];
};
setValue = function (ctxStack, key, value) {
return current(ctxStack)[key] = value;
};
applyStreamValue = function (key, index) {
return function (ctxStack, values) {
return setValue(ctxStack, key, values[index]);
};
};
constantValue = function (key, value) {
return function (ctxStack) {
return setValue(ctxStack, key, value);
};
};
mkContext = function (template) {
if (isArray(template)) {
return [];
} else {
return {};
}
};
compile = function (key, value) {
var popContext, pushContext;
if (isObservable(value)) {
streams.push(value);
return funcs.push(applyStreamValue(key, streams.length - 1));
} else if (value === Object(value) && typeof value !== 'function' && !(value instanceof RegExp) && !(value instanceof Date)) {
pushContext = function (key) {
return function (ctxStack) {
var newContext;
newContext = mkContext(value);
setValue(ctxStack, key, newContext);
return ctxStack.push(newContext);
};
};
popContext = function (ctxStack) {
return ctxStack.pop();
};
funcs.push(pushContext(key));
compileTemplate(value);
return funcs.push(popContext);
} else {
return funcs.push(constantValue(key, value));
}
};
compileTemplate = function (template) {
return _.each(template, compile);
};
compileTemplate(template);
combinator = function (values) {
var ctxStack, f, j, len1, rootContext;
rootContext = mkContext(template);
ctxStack = [rootContext];
for (j = 0, len1 = funcs.length; j < len1; j++) {
f = funcs[j];
f(ctxStack, values);
}
return rootContext;
};
return withDescription(Bacon, 'combineTemplate', template, Bacon.combineAsArray(streams).map(combinator));
};
Bacon.Observable.prototype.combine = function (other, f) {
var combinator;
combinator = toCombinator(f);
return withDescription(this, 'combine', other, f, Bacon.combineAsArray(this, other).map(function (values) {
return combinator(values[0], values[1]);
}));
};
Bacon.Observable.prototype.decode = function (cases) {
return withDescription(this, 'decode', cases, this.combine(Bacon.combineTemplate(cases), function (key, values) {
return values[key];
}));
};
Bacon.Observable.prototype.withStateMachine = function (initState, f) {
var state;
state = initState;
return withDescription(this, 'withStateMachine', initState, f, this.withHandler(function (event) {
var fromF, j, len1, newState, output, outputs, reply;
fromF = f(state, event);
newState = fromF[0], outputs = fromF[1];
state = newState;
reply = Bacon.more;
for (j = 0, len1 = outputs.length; j < len1; j++) {
output = outputs[j];
reply = this.push(output);
if (reply === Bacon.noMore) {
return reply;
}
}
return reply;
}));
};
Bacon.Observable.prototype.skipDuplicates = function (isEqual) {
if (isEqual == null) {
isEqual = function (a, b) {
return a === b;
};
}
return withDescription(this, 'skipDuplicates', this.withStateMachine(None, function (prev, event) {
if (!event.hasValue()) {
return [
prev,
[event]
];
} else if (event.isInitial() || prev === None || !isEqual(prev.get(), event.value())) {
return [
new Some(event.value()),
[event]
];
} else {
return [
prev,
[]
];
}
}));
};
Bacon.Observable.prototype.awaiting = function (other) {
return withDescription(this, 'awaiting', other, Bacon.groupSimultaneous(this, other).map(function (arg) {
var myValues, otherValues;
myValues = arg[0], otherValues = arg[1];
return otherValues.length === 0;
}).toProperty(false).skipDuplicates());
};
Bacon.Observable.prototype.not = function () {
return withDescription(this, 'not', this.map(function (x) {
return !x;
}));
};
Bacon.Property.prototype.and = function (other) {
return withDescription(this, 'and', other, this.combine(other, function (x, y) {
return x && y;
}));
};
Bacon.Property.prototype.or = function (other) {
return withDescription(this, 'or', other, this.combine(other, function (x, y) {
return x || y;
}));
};
Bacon.scheduler = {
setTimeout: function (f, d) {
return setTimeout(f, d);
},
setInterval: function (f, i) {
return setInterval(f, i);
},
clearInterval: function (id) {
return clearInterval(id);
},
clearTimeout: function (id) {
return clearTimeout(id);
},
now: function () {
return new Date().getTime();
}
};
Bacon.EventStream.prototype.bufferWithTime = function (delay) {
return withDescription(this, 'bufferWithTime', delay, this.bufferWithTimeOrCount(delay, Number.MAX_VALUE));
};
Bacon.EventStream.prototype.bufferWithCount = function (count) {
return withDescription(this, 'bufferWithCount', count, this.bufferWithTimeOrCount(void 0, count));
};
Bacon.EventStream.prototype.bufferWithTimeOrCount = function (delay, count) {
var flushOrSchedule;
flushOrSchedule = function (buffer) {
if (buffer.values.length === count) {
return buffer.flush();
} else if (delay !== void 0) {
return buffer.schedule();
}
};
return withDescription(this, 'bufferWithTimeOrCount', delay, count, this.buffer(delay, flushOrSchedule, flushOrSchedule));
};
Bacon.EventStream.prototype.buffer = function (delay, onInput, onFlush) {
var buffer, delayMs, reply;
if (onInput == null) {
onInput = nop;
}
if (onFlush == null) {
onFlush = nop;
}
buffer = {
scheduled: null,
end: void 0,
values: [],
flush: function () {
var reply;
if (this.scheduled) {
Bacon.scheduler.clearTimeout(this.scheduled);
this.scheduled = null;
}
if (this.values.length > 0) {
reply = this.push(nextEvent(this.values));
this.values = [];
if (this.end != null) {
return this.push(this.end);
} else if (reply !== Bacon.noMore) {
return onFlush(this);
}
} else {
if (this.end != null) {
return this.push(this.end);
}
}
},
schedule: function () {
if (!this.scheduled) {
return this.scheduled = delay(function (_this) {
return function () {
return _this.flush();
};
}(this));
}
}
};
reply = Bacon.more;
if (!_.isFunction(delay)) {
delayMs = delay;
delay = function (f) {
return Bacon.scheduler.setTimeout(f, delayMs);
};
}
return withDescription(this, 'buffer', this.withHandler(function (event) {
buffer.push = function (_this) {
return function (event) {
return _this.push(event);
};
}(this);
if (event.isError()) {
reply = this.push(event);
} else if (event.isEnd()) {
buffer.end = event;
if (!buffer.scheduled) {
buffer.flush();
}
} else {
buffer.values.push(event.value());
onInput(buffer);
}
return reply;
}));
};
Bacon.Observable.prototype.filter = function () {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
return convertArgsToFunction(this, f, args, function (f) {
return withDescription(this, 'filter', f, this.withHandler(function (event) {
if (event.filter(f)) {
return this.push(event);
} else {
return Bacon.more;
}
}));
});
};
Bacon.once = function (value) {
return new EventStream(describe(Bacon, 'once', value), function (sink) {
sink(toEvent(value));
sink(endEvent());
return nop;
});
};
Bacon.EventStream.prototype.concat = function (right) {
var left;
left = this;
return new EventStream(describe(left, 'concat', right), function (sink) {
var unsubLeft, unsubRight;
unsubRight = nop;
unsubLeft = left.dispatcher.subscribe(function (e) {
if (e.isEnd()) {
return unsubRight = right.dispatcher.subscribe(sink);
} else {
return sink(e);
}
});
return function () {
unsubLeft();
return unsubRight();
};
});
};
Bacon.Observable.prototype.flatMap = function () {
return flatMap_(this, makeSpawner(arguments));
};
Bacon.Observable.prototype.flatMapFirst = function () {
return flatMap_(this, makeSpawner(arguments), true);
};
flatMap_ = function (root, f, firstOnly, limit) {
var childDeps, result, rootDep;
rootDep = [root];
childDeps = [];
result = new EventStream(describe(root, 'flatMap' + (firstOnly ? 'First' : ''), f), function (sink) {
var checkEnd, checkQueue, composite, queue, spawn;
composite = new CompositeUnsubscribe();
queue = [];
spawn = function (event) {
var child;
child = makeObservable(f(event.value()));
childDeps.push(child);
return composite.add(function (unsubAll, unsubMe) {
return child.dispatcher.subscribe(function (event) {
var reply;
if (event.isEnd()) {
_.remove(child, childDeps);
checkQueue();
checkEnd(unsubMe);
return Bacon.noMore;
} else {
if (event instanceof Initial) {
event = event.toNext();
}
reply = sink(event);
if (reply === Bacon.noMore) {
unsubAll();
}
return reply;
}
});
});
};
checkQueue = function () {
var event;
event = queue.shift();
if (event) {
return spawn(event);
}
};
checkEnd = function (unsub) {
unsub();
if (composite.empty()) {
return sink(endEvent());
}
};
composite.add(function (__, unsubRoot) {
return root.dispatcher.subscribe(function (event) {
if (event.isEnd()) {
return checkEnd(unsubRoot);
} else if (event.isError()) {
return sink(event);
} else if (firstOnly && composite.count() > 1) {
return Bacon.more;
} else {
if (composite.unsubscribed) {
return Bacon.noMore;
}
if (limit && composite.count() > limit) {
return queue.push(event);
} else {
return spawn(event);
}
}
});
});
return composite.unsubscribe;
});
result.internalDeps = function () {
if (childDeps.length) {
return rootDep.concat(childDeps);
} else {
return rootDep;
}
};
return result;
};
makeSpawner = function (args) {
if (args.length === 1 && isObservable(args[0])) {
return _.always(args[0]);
} else {
return makeFunctionArgs(args);
}
};
makeObservable = function (x) {
if (isObservable(x)) {
return x;
} else {
return Bacon.once(x);
}
};
Bacon.Observable.prototype.flatMapWithConcurrencyLimit = function () {
var args, limit;
limit = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
return withDescription.apply(null, [
this,
'flatMapWithConcurrencyLimit',
limit
].concat(slice.call(args), [flatMap_(this, makeSpawner(args), false, limit)]));
};
Bacon.Observable.prototype.flatMapConcat = function () {
return withDescription.apply(null, [
this,
'flatMapConcat'
].concat(slice.call(arguments), [this.flatMapWithConcurrencyLimit.apply(this, [1].concat(slice.call(arguments)))]));
};
Bacon.later = function (delay, value) {
return withDescription(Bacon, 'later', delay, value, Bacon.fromBinder(function (sink) {
var id, sender;
sender = function () {
return sink([
value,
endEvent()
]);
};
id = Bacon.scheduler.setTimeout(sender, delay);
return function () {
return Bacon.scheduler.clearTimeout(id);
};
}));
};
Bacon.Observable.prototype.bufferingThrottle = function (minimumInterval) {
return withDescription(this, 'bufferingThrottle', minimumInterval, this.flatMapConcat(function (x) {
return Bacon.once(x).concat(Bacon.later(minimumInterval).filter(false));
}));
};
Bacon.Property.prototype.bufferingThrottle = function () {
return Bacon.Observable.prototype.bufferingThrottle.apply(this, arguments).toProperty();
};
Bus = function (superClass) {
extend(Bus, superClass);
function Bus() {
this.guardedSink = bind(this.guardedSink, this);
this.subscribeAll = bind(this.subscribeAll, this);
this.unsubAll = bind(this.unsubAll, this);
this.sink = void 0;
this.subscriptions = [];
this.ended = false;
Bus.__super__.constructor.call(this, describe(Bacon, 'Bus'), this.subscribeAll);
}
Bus.prototype.unsubAll = function () {
var j, len1, ref, sub;
ref = this.subscriptions;
for (j = 0, len1 = ref.length; j < len1; j++) {
sub = ref[j];
if (typeof sub.unsub === 'function') {
sub.unsub();
}
}
return void 0;
};
Bus.prototype.subscribeAll = function (newSink) {
var j, len1, ref, subscription;
if (this.ended) {
newSink(endEvent());
} else {
this.sink = newSink;
ref = cloneArray(this.subscriptions);
for (j = 0, len1 = ref.length; j < len1; j++) {
subscription = ref[j];
this.subscribeInput(subscription);
}
}
return this.unsubAll;
};
Bus.prototype.guardedSink = function (input) {
return function (_this) {
return function (event) {
if (event.isEnd()) {
_this.unsubscribeInput(input);
return Bacon.noMore;
} else {
return _this.sink(event);
}
};
}(this);
};
Bus.prototype.subscribeInput = function (subscription) {
return subscription.unsub = subscription.input.dispatcher.subscribe(this.guardedSink(subscription.input));
};
Bus.prototype.unsubscribeInput = function (input) {
var i, j, len1, ref, sub;
ref = this.subscriptions;
for (i = j = 0, len1 = ref.length; j < len1; i = ++j) {
sub = ref[i];
if (sub.input === input) {
if (typeof sub.unsub === 'function') {
sub.unsub();
}
this.subscriptions.splice(i, 1);
return;
}
}
};
Bus.prototype.plug = function (input) {
var sub;
if (this.ended) {
return;
}
sub = { input: input };
this.subscriptions.push(sub);
if (this.sink != null) {
this.subscribeInput(sub);
}
return function (_this) {
return function () {
return _this.unsubscribeInput(input);
};
}(this);
};
Bus.prototype.end = function () {
this.ended = true;
this.unsubAll();
return typeof this.sink === 'function' ? this.sink(endEvent()) : void 0;
};
Bus.prototype.push = function (value) {
if (!this.ended) {
return typeof this.sink === 'function' ? this.sink(nextEvent(value)) : void 0;
}
};
Bus.prototype.error = function (error) {
return typeof this.sink === 'function' ? this.sink(new Error(error)) : void 0;
};
return Bus;
}(EventStream);
Bacon.Bus = Bus;
liftCallback = function (desc, wrapped) {
return withMethodCallSupport(function () {
var args, f, stream;
f = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
stream = partiallyApplied(wrapped, [function (values, callback) {
return f.apply(null, slice.call(values).concat([callback]));
}]);
return withDescription.apply(null, [
Bacon,
desc,
f
].concat(slice.call(args), [Bacon.combineAsArray(args).flatMap(stream)]));
});
};
Bacon.fromCallback = liftCallback('fromCallback', function () {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
return Bacon.fromBinder(function (handler) {
makeFunction(f, args)(handler);
return nop;
}, function (value) {
return [
value,
endEvent()
];
});
});
Bacon.fromNodeCallback = liftCallback('fromNodeCallback', function () {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
return Bacon.fromBinder(function (handler) {
makeFunction(f, args)(handler);
return nop;
}, function (error, value) {
if (error) {
return [
new Error(error),
endEvent()
];
}
return [
value,
endEvent()
];
});
});
addPropertyInitValueToStream = function (property, stream) {
var justInitValue;
justInitValue = new EventStream(describe(property, 'justInitValue'), function (sink) {
var unsub, value;
value = void 0;
unsub = property.dispatcher.subscribe(function (event) {
if (!event.isEnd()) {
value = event;
}
return Bacon.noMore;
});
UpdateBarrier.whenDoneWith(justInitValue, function () {
if (value != null) {
sink(value);
}
return sink(endEvent());
});
return unsub;
});
return justInitValue.concat(stream).toProperty();
};
Bacon.Observable.prototype.mapEnd = function () {
var f;
f = makeFunctionArgs(arguments);
return withDescription(this, 'mapEnd', f, this.withHandler(function (event) {
if (event.isEnd()) {
this.push(nextEvent(f(event)));
this.push(endEvent());
return Bacon.noMore;
} else {
return this.push(event);
}
}));
};
Bacon.Observable.prototype.skipErrors = function () {
return withDescription(this, 'skipErrors', this.withHandler(function (event) {
if (event.isError()) {
return Bacon.more;
} else {
return this.push(event);
}
}));
};
Bacon.EventStream.prototype.takeUntil = function (stopper) {
var endMarker;
endMarker = {};
return withDescription(this, 'takeUntil', stopper, Bacon.groupSimultaneous(this.mapEnd(endMarker), stopper.skipErrors()).withHandler(function (event) {
var data, j, len1, ref, reply, value;
if (!event.hasValue()) {
return this.push(event);
} else {
ref = event.value(), data = ref[0], stopper = ref[1];
if (stopper.length) {
return this.push(endEvent());
} else {
reply = Bacon.more;
for (j = 0, len1 = data.length; j < len1; j++) {
value = data[j];
if (value === endMarker) {
reply = this.push(endEvent());
} else {
reply = this.push(nextEvent(value));
}
}
return reply;
}
}
}));
};
Bacon.Property.prototype.takeUntil = function (stopper) {
var changes;
changes = this.changes().takeUntil(stopper);
return withDescription(this, 'takeUntil', stopper, addPropertyInitValueToStream(this, changes));
};
Bacon.Observable.prototype.flatMapLatest = function () {
var f, stream;
f = makeSpawner(arguments);
stream = this.toEventStream();
return withDescription(this, 'flatMapLatest', f, stream.flatMap(function (value) {
return makeObservable(f(value)).takeUntil(stream);
}));
};
Bacon.Property.prototype.delayChanges = function () {
var desc, f, j;
desc = 2 <= arguments.length ? slice.call(arguments, 0, j = arguments.length - 1) : (j = 0, []), f = arguments[j++];
return withDescription.apply(null, [this].concat(slice.call(desc), [addPropertyInitValueToStream(this, f(this.changes()))]));
};
Bacon.EventStream.prototype.delay = function (delay) {
return withDescription(this, 'delay', delay, this.flatMap(function (value) {
return Bacon.later(delay, value);
}));
};
Bacon.Property.prototype.delay = function (delay) {
return this.delayChanges('delay', delay, function (changes) {
return changes.delay(delay);
});
};
Bacon.EventStream.prototype.debounce = function (delay) {
return withDescription(this, 'debounce', delay, this.flatMapLatest(function (value) {
return Bacon.later(delay, value);
}));
};
Bacon.Property.prototype.debounce = function (delay) {
return this.delayChanges('debounce', delay, function (changes) {
return changes.debounce(delay);
});
};
Bacon.EventStream.prototype.debounceImmediate = function (delay) {
return withDescription(this, 'debounceImmediate', delay, this.flatMapFirst(function (value) {
return Bacon.once(value).concat(Bacon.later(delay).filter(false));
}));
};
Bacon.Observable.prototype.scan = function (seed, f) {
var acc, resultProperty, subscribe;
f = toCombinator(f);
acc = toOption(seed);
subscribe = function (_this) {
return function (sink) {
var initSent, reply, sendInit, unsub;
initSent = false;
unsub = nop;
reply = Bacon.more;
sendInit = function () {
if (!initSent) {
return acc.forEach(function (value) {
initSent = true;
reply = sink(new Initial(function () {
return value;
}));
if (reply === Bacon.noMore) {
unsub();
return unsub = nop;
}
});
}
};
unsub = _this.dispatcher.subscribe(function (event) {
var next, prev;
if (event.hasValue()) {
if (initSent && event.isInitial()) {
return Bacon.more;
} else {
if (!event.isInitial()) {
sendInit();
}
initSent = true;
prev = acc.getOrElse(void 0);
next = f(prev, event.value());
acc = new Some(next);
return sink(event.apply(function () {
return next;
}));
}
} else {
if (event.isEnd()) {
reply = sendInit();
}
if (reply !== Bacon.noMore) {
return sink(event);
}
}
});
UpdateBarrier.whenDoneWith(resultProperty, sendInit);
return unsub;
};
}(this);
return resultProperty = new Property(describe(this, 'scan', seed, f), subscribe);
};
Bacon.Observable.prototype.diff = function (start, f) {
f = toCombinator(f);
return withDescription(this, 'diff', start, f, this.scan([start], function (prevTuple, next) {
return [
next,
f(prevTuple[0], next)
];
}).filter(function (tuple) {
return tuple.length === 2;
}).map(function (tuple) {
return tuple[1];
}));
};
Bacon.Observable.prototype.doAction = function () {
var f;
f = makeFunctionArgs(arguments);
return withDescription(this, 'doAction', f, this.withHandler(function (event) {
if (event.hasValue()) {
f(event.value());
}
return this.push(event);
}));
};
Bacon.Observable.prototype.doError = function () {
var f;
f = makeFunctionArgs(arguments);
return withDescription(this, 'doError', f, this.withHandler(function (event) {
if (event.isError()) {
f(event.error);
}
return this.push(event);
}));
};
Bacon.Observable.prototype.endOnError = function () {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
if (f == null) {
f = true;
}
return convertArgsToFunction(this, f, args, function (f) {
return withDescription(this, 'endOnError', this.withHandler(function (event) {
if (event.isError() && f(event.error)) {
this.push(event);
return this.push(endEvent());
} else {
return this.push(event);
}
}));
});
};
Observable.prototype.errors = function () {
return withDescription(this, 'errors', this.filter(function () {
return false;
}));
};
valueAndEnd = function (value) {
return [
value,
endEvent()
];
};
Bacon.fromPromise = function (promise, abort) {
return withDescription(Bacon, 'fromPromise', promise, Bacon.fromBinder(function (handler) {
var ref;
if ((ref = promise.then(handler, function (e) {
return handler(new Error(e));
})) != null) {
if (typeof ref.done === 'function') {
ref.done();
}
}
return function () {
if (abort) {
return typeof promise.abort === 'function' ? promise.abort() : void 0;
}
};
}, valueAndEnd));
};
Bacon.Observable.prototype.mapError = function () {
var f;
f = makeFunctionArgs(arguments);
return withDescription(this, 'mapError', f, this.withHandler(function (event) {
if (event.isError()) {
return this.push(nextEvent(f(event.error)));
} else {
return this.push(event);
}
}));
};
Bacon.Observable.prototype.flatMapError = function (fn) {
return withDescription(this, 'flatMapError', fn, this.mapError(function (err) {
return new Error(err);
}).flatMap(function (x) {
if (x instanceof Error) {
return fn(x.error);
} else {
return Bacon.once(x);
}
}));
};
Bacon.EventStream.prototype.sampledBy = function (sampler, combinator) {
return withDescription(this, 'sampledBy', sampler, combinator, this.toProperty().sampledBy(sampler, combinator));
};
Bacon.Property.prototype.sampledBy = function (sampler, combinator) {
var lazy, result, samplerSource, stream, thisSource;
if (combinator != null) {
combinator = toCombinator(combinator);
} else {
lazy = true;
combinator = function (f) {
return f.value();
};
}
thisSource = new Source(this, false, lazy);
samplerSource = new Source(sampler, true, lazy);
stream = Bacon.when([
thisSource,
samplerSource
], combinator);
result = sampler instanceof Property ? stream.toProperty() : stream;
return withDescription(this, 'sampledBy', sampler, combinator, result);
};
Bacon.Property.prototype.sample = function (interval) {
return withDescription(this, 'sample', interval, this.sampledBy(Bacon.interval(interval, {})));
};
Bacon.Observable.prototype.map = function () {
var args, p;
p = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
if (p instanceof Property) {
return p.sampledBy(this, former);
} else {
return convertArgsToFunction(this, p, args, function (f) {
return withDescription(this, 'map', f, this.withHandler(function (event) {
return this.push(event.fmap(f));
}));
});
}
};
Bacon.Observable.prototype.fold = function (seed, f) {
return withDescription(this, 'fold', seed, f, this.scan(seed, f).sampledBy(this.filter(false).mapEnd().toProperty()));
};
Observable.prototype.reduce = Observable.prototype.fold;
Bacon.fromPoll = function (delay, poll) {
return withDescription(Bacon, 'fromPoll', delay, poll, Bacon.fromBinder(function (handler) {
var id;
id = Bacon.scheduler.setInterval(handler, delay);
return function () {
return Bacon.scheduler.clearInterval(id);
};
}, poll));
};
Bacon.EventStream.prototype.merge = function (right) {
var left;
left = this;
return withDescription(left, 'merge', right, Bacon.mergeAll(this, right));
};
Bacon.mergeAll = function () {
var streams;
streams = 1 <= arguments.length ? slice.call(arguments, 0) : [];
if (isArray(streams[0])) {
streams = streams[0];
}
if (streams.length) {
return new EventStream(describe.apply(null, [
Bacon,
'mergeAll'
].concat(slice.call(streams))), function (sink) {
var ends, sinks, smartSink;
ends = 0;
smartSink = function (obs) {
return function (unsubBoth) {
return obs.dispatcher.subscribe(function (event) {
var reply;
if (event.isEnd()) {
ends++;
if (ends === streams.length) {
return sink(endEvent());
} else {
return Bacon.more;
}
} else {
reply = sink(event);
if (reply === Bacon.noMore) {
unsubBoth();
}
return reply;
}
});
};
};
sinks = _.map(smartSink, streams);
return new Bacon.CompositeUnsubscribe(sinks).unsubscribe;
});
} else {
return Bacon.never();
}
};
Bacon.Observable.prototype.take = function (count) {
if (count <= 0) {
return Bacon.never();
}
return withDescription(this, 'take', count, this.withHandler(function (event) {
if (!event.hasValue()) {
return this.push(event);
} else {
count--;
if (count > 0) {
return this.push(event);
} else {
if (count === 0) {
this.push(event);
}
this.push(endEvent());
return Bacon.noMore;
}
}
}));
};
Bacon.fromArray = function (values) {
var i;
if (!values.length) {
return withDescription(Bacon, 'fromArray', values, Bacon.never());
} else {
i = 0;
return new EventStream(describe(Bacon, 'fromArray', values), function (sink) {
var push, pushNeeded, pushing, reply, unsubd;
unsubd = false;
reply = Bacon.more;
pushing = false;
pushNeeded = false;
push = function () {
var value;
pushNeeded = true;
if (pushing) {
return;
}
pushing = true;
while (pushNeeded) {
pushNeeded = false;
if (reply !== Bacon.noMore && !unsubd) {
value = values[i++];
reply = sink(toEvent(value));
if (reply !== Bacon.noMore) {
if (i === values.length) {
sink(endEvent());
} else {
UpdateBarrier.afterTransaction(push);
}
}
}
}
return pushing = false;
};
push();
return function () {
return unsubd = true;
};
});
}
};
Bacon.EventStream.prototype.holdWhen = function (valve) {
var putToHold, releaseHold, valve_;
valve_ = valve.startWith(false);
releaseHold = valve_.filter(function (x) {
return !x;
});
putToHold = valve_.filter(_.id);
return withDescription(this, 'holdWhen', valve, this.filter(false).merge(valve_.flatMapConcat(function (_this) {
return function (shouldHold) {
if (!shouldHold) {
return _this.takeUntil(putToHold);
} else {
return _this.scan([], function (xs, x) {
return xs.concat([x]);
}).sampledBy(releaseHold).take(1).flatMap(Bacon.fromArray);
}
};
}(this))));
};
Bacon.interval = function (delay, value) {
if (value == null) {
value = {};
}
return withDescription(Bacon, 'interval', delay, value, Bacon.fromPoll(delay, function () {
return nextEvent(value);
}));
};
Bacon.$ = {};
Bacon.$.asEventStream = function (eventName, selector, eventTransformer) {
var ref;
if (_.isFunction(selector)) {
ref = [
selector,
void 0
], eventTransformer = ref[0], selector = ref[1];
}
return withDescription(this.selector || this, 'asEventStream', eventName, Bacon.fromBinder(function (_this) {
return function (handler) {
_this.on(eventName, selector, handler);
return function () {
return _this.off(eventName, selector, handler);
};
};
}(this), eventTransformer));
};
if ((ref = typeof jQuery !== 'undefined' && jQuery !== null ? jQuery : typeof Zepto !== 'undefined' && Zepto !== null ? Zepto : void 0) != null) {
ref.fn.asEventStream = Bacon.$.asEventStream;
}
Bacon.Observable.prototype.log = function () {
var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
this.subscribe(function (event) {
return typeof console !== 'undefined' && console !== null ? typeof console.log === 'function' ? console.log.apply(console, slice.call(args).concat([event.log()])) : void 0 : void 0;
});
return this;
};
Bacon.repeatedly = function (delay, values) {
var index;
index = 0;
return withDescription(Bacon, 'repeatedly', delay, values, Bacon.fromPoll(delay, function () {
return values[index++ % values.length];
}));
};
Bacon.repeat = function (generator) {
var index;
index = 0;
return Bacon.fromBinder(function (sink) {
var flag, handleEvent, reply, subscribeNext, unsub;
flag = false;
reply = Bacon.more;
unsub = function () {
};
handleEvent = function (event) {
if (event.isEnd()) {
if (!flag) {
return flag = true;
} else {
return subscribeNext();
}
} else {
return reply = sink(event);
}
};
subscribeNext = function () {
var next;
flag = true;
while (flag && reply !== Bacon.noMore) {
next = generator(index++);
flag = false;
if (next) {
unsub = next.subscribeInternal(handleEvent);
} else {
sink(endEvent());
}
}
return flag = true;
};
subscribeNext();
return function () {
return unsub();
};
});
};
Bacon.retry = function (options) {
var delay, error, finished, isRetryable, maxRetries, retries, source;
if (!_.isFunction(options.source)) {
throw new Exception('\'source\' option has to be a function');
}
source = options.source;
retries = options.retries || 0;
maxRetries = options.maxRetries || retries;
delay = options.delay || function () {
return 0;
};
isRetryable = options.isRetryable || function () {
return true;
};
finished = false;
error = null;
return withDescription(Bacon, 'retry', options, Bacon.repeat(function () {
var context, pause, valueStream;
if (finished) {
return null;
} else {
valueStream = function () {
return source().endOnError().withHandler(function (event) {
if (event.isError()) {
error = event;
if (isRetryable(error.error) && retries > 0) {
} else {
finished = true;
return this.push(event);
}
} else {
if (event.hasValue()) {
error = null;
finished = true;
}
return this.push(event);
}
});
};
if (error) {
context = {
error: error.error,
retriesDone: maxRetries - retries
};
pause = Bacon.later(delay(context)).filter(false);
retries = retries - 1;
return pause.concat(Bacon.once().flatMap(valueStream));
} else {
return valueStream();
}
}
}));
};
Bacon.sequentially = function (delay, values) {
var index;
index = 0;
return withDescription(Bacon, 'sequentially', delay, values, Bacon.fromPoll(delay, function () {
var value;
value = values[index++];
if (index < values.length) {
return value;
} else if (index === values.length) {
return [
value,
endEvent()
];
} else {
return endEvent();
}
}));
};
Bacon.Observable.prototype.skip = function (count) {
return withDescription(this, 'skip', count, this.withHandler(function (event) {
if (!event.hasValue()) {
return this.push(event);
} else if (count > 0) {
count--;
return Bacon.more;
} else {
return this.push(event);
}
}));
};
Bacon.EventStream.prototype.skipUntil = function (starter) {
var started;
started = starter.take(1).map(true).toProperty(false);
return withDescription(this, 'skipUntil', starter, this.filter(started));
};
Bacon.EventStream.prototype.skipWhile = function () {
var args, f, ok;
f = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
ok = false;
return convertArgsToFunction(this, f, args, function (f) {
return withDescription(this, 'skipWhile', f, this.withHandler(function (event) {
if (ok || !event.hasValue() || !f(event.value())) {
if (event.hasValue()) {
ok = true;
}
return this.push(event);
} else {
return Bacon.more;
}
}));
});
};
Bacon.Observable.prototype.slidingWindow = function (n, minValues) {
if (minValues == null) {
minValues = 0;
}
return withDescription(this, 'slidingWindow', n, minValues, this.scan([], function (window, value) {
return window.concat([value]).slice(-n);
}).filter(function (values) {
return values.length >= minValues;
}));
};
Bacon.spy = function (spy) {
return spys.push(spy);
};
spys = [];
registerObs = function (obs) {
var j, len1, spy;
if (spys.length) {
if (!registerObs.running) {
try {
registerObs.running = true;
for (j = 0, len1 = spys.length; j < len1; j++) {
spy = spys[j];
spy(obs);
}
} finally {
delete registerObs.running;
}
}
}
return void 0;
};
Bacon.Property.prototype.startWith = function (seed) {
return withDescription(this, 'startWith', seed, this.scan(seed, function (prev, next) {
return next;
}));
};
Bacon.EventStream.prototype.startWith = function (seed) {
return withDescription(this, 'startWith', seed, Bacon.once(seed).concat(this));
};
Bacon.Observable.prototype.takeWhile = function () {
var args, f;
f = arguments[0], args = 2 <= arguments.length ? slice.call(arguments, 1) : [];
return convertArgsToFunction(this, f, args, function (f) {
return withDescription(this, 'takeWhile', f, this.withHandler(function (event) {
if (event.filter(f)) {
return this.push(event);
} else {
this.push(endEvent());
return Bacon.noMore;
}
}));
});
};
Bacon.update = function () {
var i, initial, lateBindFirst, patterns;
initial = arguments[0], patterns = 2 <= arguments.length ? slice.call(arguments, 1) : [];
lateBindFirst = function (f) {
return function () {
var args;
args = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return function (i) {
return f.apply(null, [i].concat(args));
};
};
};
i = patterns.length - 1;
while (i > 0) {
if (!(patterns[i] instanceof Function)) {
patterns[i] = function (x) {
return function () {
return x;
};
}(patterns[i]);
}
patterns[i] = lateBindFirst(patterns[i]);
i = i - 2;
}
return withDescription.apply(null, [
Bacon,
'update',
initial
].concat(slice.call(patterns), [Bacon.when.apply(Bacon, patterns).scan(initial, function (x, f) {
return f(x);
})]));
};
Bacon.zipAsArray = function () {
var streams;
streams = 1 <= arguments.length ? slice.call(arguments, 0) : [];
if (isArray(streams[0])) {
streams = streams[0];
}
return withDescription.apply(null, [
Bacon,
'zipAsArray'
].concat(slice.call(streams), [Bacon.zipWith(streams, function () {
var xs;
xs = 1 <= arguments.length ? slice.call(arguments, 0) : [];
return xs;
})]));
};
Bacon.zipWith = function () {
var f, ref1, streams;
f = arguments[0], streams = 2 <= arguments.length ? slice.call(arguments, 1) : [];
if (!_.isFunction(f)) {
ref1 = [
f,
streams[0]
], streams = ref1[0], f = ref1[1];
}
streams = _.map(function (s) {
return s.toEventStream();
}, streams);
return withDescription.apply(null, [
Bacon,
'zipWith',
f
].concat(slice.call(streams), [Bacon.when(streams, f)]));
};
Bacon.Observable.prototype.zip = function (other, f) {
if (f == null) {
f = Array;
}
return withDescription(this, 'zip', other, Bacon.zipWith([
this,
other
], f));
};
Bacon.Observable.prototype.first = function () {
return withDescription(this, 'first', this.take(1));
};
Bacon.Observable.prototype.last = function () {
var lastEvent;
return withDescription(this, 'last', this.withHandler(function (event) {
if (event.isEnd()) {
if (lastEvent) {
this.push(lastEvent);
}
this.push(endEvent());
return Bacon.noMore;
} else {
lastEvent = event;
}
}));
};
Bacon.EventStream.prototype.throttle = function (delay) {
return withDescription(this, 'throttle', delay, this.bufferWithTime(delay).map(function (values) {
return values[values.length - 1];
}));
};
Bacon.Property.prototype.throttle = function (delay) {
return this.delayChanges('throttle', delay, function (changes) {
return changes.throttle(delay);
});
};
Observable.prototype.firstToPromise = function (PromiseCtr) {
var _this = this;
if (typeof PromiseCtr !== 'function') {
if (typeof Promise === 'function') {
PromiseCtr = Promise;
} else {
throw new Exception('There isn\'t default Promise, use shim or parameter');
}
}
return new PromiseCtr(function (resolve, reject) {
return _this.subscribe(function (event) {
if (event.hasValue()) {
resolve(event.value());
}
if (event.isError()) {
reject(event.error);
}
return Bacon.noMore;
});
});
};
Observable.prototype.toPromise = function (PromiseCtr) {
return this.last().firstToPromise(PromiseCtr);
};
if (typeof define !== 'undefined' && define !== null && define.amd != null) {
define([], function () {
return Bacon;
});
this.Bacon = Bacon;
} else if (typeof module !== 'undefined' && module !== null && module.exports != null) {
module.exports = Bacon;
Bacon.Bacon = Bacon;
} else {
this.Bacon = Bacon;
}
}.call(this));
| luhad/cdnjs | ajax/libs/bacon.js/0.7.59/Bacon.noAssert.js | JavaScript | mit | 112,286 |
// vim:set ts=4 sts=4 sw=4 st:
// -- kriskowal Kris Kowal Copyright (C) 2009-2010 MIT License
// -- tlrobinson Tom Robinson Copyright (C) 2009-2010 MIT License (Narwhal Project)
// -- dantman Daniel Friesen Copyright(C) 2010 XXX No License Specified
// -- fschaefer Florian Schäfer Copyright (C) 2010 MIT License
// -- Irakli Gozalishvili Copyright (C) 2010 MIT License
// -- kitcambridge Kit Cambridge Copyright (C) 2011 MIT License
/*!
Copyright (c) 2009, 280 North Inc. http://280north.com/
MIT License. http://github.com/280north/narwhal/blob/master/README.md
*/
(function (definition) {
// RequireJS
if (typeof define == "function") {
define(function () {
definition();
});
// CommonJS and <script>
} else {
definition();
}
})(function (undefined) {
/**
* Brings an environment as close to ECMAScript 5 compliance
* as is possible with the facilities of erstwhile engines.
*
* ES5 Draft
* http://www.ecma-international.org/publications/files/drafts/tc39-2009-050.pdf
*
* NOTE: this is a draft, and as such, the URL is subject to change. If the
* link is broken, check in the parent directory for the latest TC39 PDF.
* http://www.ecma-international.org/publications/files/drafts/
*
* Previous ES5 Draft
* http://www.ecma-international.org/publications/files/drafts/tc39-2009-025.pdf
* This is a broken link to the previous draft of ES5 on which most of the
* numbered specification references and quotes herein were taken. Updating
* these references and quotes to reflect the new document would be a welcome
* volunteer project.
*
* @module
*/
/*whatsupdoc*/
//
// Function
// ========
//
// ES-5 15.3.4.5
// http://www.ecma-international.org/publications/files/drafts/tc39-2009-025.pdf
if (!Function.prototype.bind) {
Function.prototype.bind = function bind(that) { // .length is 1
// 1. Let Target be the this value.
var target = this;
// 2. If IsCallable(Target) is false, throw a TypeError exception.
// XXX this gets pretty close, for all intents and purposes, letting
// some duck-types slide
if (typeof target.apply != "function" || typeof target.call != "function")
return new TypeError();
// 3. Let A be a new (possibly empty) internal list of all of the
// argument values provided after thisArg (arg1, arg2 etc), in order.
// XXX slicedArgs will stand in for "A" if used
var args = slice.call(arguments, 1); // for normal call
// 4. Let F be a new native ECMAScript object.
// 9. Set the [[Prototype]] internal property of F to the standard
// built-in Function prototype object as specified in 15.3.3.1.
// 10. Set the [[Call]] internal property of F as described in
// 15.3.4.5.1.
// 11. Set the [[Construct]] internal property of F as described in
// 15.3.4.5.2.
// 12. Set the [[HasInstance]] internal property of F as described in
// 15.3.4.5.3.
// 13. The [[Scope]] internal property of F is unused and need not
// exist.
var bound = function () {
if (this instanceof bound) {
// 15.3.4.5.2 [[Construct]]
// When the [[Construct]] internal method of a function object,
// F that was created using the bind function is called with a
// list of arguments ExtraArgs the following steps are taken:
// 1. Let target be the value of F's [[TargetFunction]]
// internal property.
// 2. If target has no [[Construct]] internal method, a
// TypeError exception is thrown.
// 3. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 4. Let args be a new list containing the same values as the
// list boundArgs in the same order followed by the same
// values as the list ExtraArgs in the same order.
var self = Object.create(target.prototype);
var result = target.apply(
self,
args.concat(slice.call(arguments))
);
if (result !== null && Object(result) === result)
return result;
return self;
} else {
// 15.3.4.5.1 [[Call]]
// When the [[Call]] internal method of a function object, F,
// which was created using the bind function is called with a
// this value and a list of arguments ExtraArgs the following
// steps are taken:
// 1. Let boundArgs be the value of F's [[BoundArgs]] internal
// property.
// 2. Let boundThis be the value of F's [[BoundThis]] internal
// property.
// 3. Let target be the value of F's [[TargetFunction]] internal
// property.
// 4. Let args be a new list containing the same values as the list
// boundArgs in the same order followed by the same values as
// the list ExtraArgs in the same order. 5. Return the
// result of calling the [[Call]] internal method of target
// providing boundThis as the this value and providing args
// as the arguments.
// equiv: target.call(this, ...boundArgs, ...args)
return target.apply(
that,
args.concat(slice.call(arguments))
);
}
};
// XXX bound.length is never writable, so don't even try
//
// 16. The length own property of F is given attributes as specified in
// 15.3.5.1.
// TODO
// 17. Set the [[Extensible]] internal property of F to true.
// TODO
// 18. Call the [[DefineOwnProperty]] internal method of F with
// arguments "caller", PropertyDescriptor {[[Value]]: null,
// [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]:
// false}, and false.
// TODO
// 19. Call the [[DefineOwnProperty]] internal method of F with
// arguments "arguments", PropertyDescriptor {[[Value]]: null,
// [[Writable]]: false, [[Enumerable]]: false, [[Configurable]]:
// false}, and false.
// TODO
// NOTE Function objects created using Function.prototype.bind do not
// have a prototype property.
// XXX can't delete it in pure-js.
return bound;
};
}
// Shortcut to an often accessed properties, in order to avoid multiple
// dereference that costs universally.
// _Please note: Shortcuts are defined after `Function.prototype.bind` as we
// us it in defining shortcuts.
var call = Function.prototype.call;
var prototypeOfArray = Array.prototype;
var prototypeOfObject = Object.prototype;
var slice = prototypeOfArray.slice;
var toString = prototypeOfObject.toString;
var owns = call.bind(prototypeOfObject.hasOwnProperty);
var defineGetter, defineSetter, lookupGetter, lookupSetter, supportsAccessors;
// If JS engine supports accessors creating shortcuts.
if ((supportsAccessors = owns(prototypeOfObject, '__defineGetter__'))) {
defineGetter = call.bind(prototypeOfObject.__defineGetter__);
defineSetter = call.bind(prototypeOfObject.__defineSetter__);
lookupGetter = call.bind(prototypeOfObject.__lookupGetter__);
lookupSetter = call.bind(prototypeOfObject.__lookupSetter__);
}
//
// Array
// =====
//
// ES5 15.4.3.2
if (!Array.isArray) {
Array.isArray = function isArray(obj) {
return Object.prototype.toString.call(obj) == "[object Array]";
};
}
// ES5 15.4.4.18
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/array/foreach
if (!Array.prototype.forEach) {
Array.prototype.forEach = function forEach(fun /*, thisp*/) {
var self = Object(this),
thisp = arguments[1],
i = 0,
length = self.length >>> 0;
// If no callback function or if callback is not a callable function
if (!fun || !fun.call) {
throw new TypeError();
}
while (i < length) {
if (i in self) {
// Invoke the callback function with call, passing arguments:
// context, property value, property key, thisArg object context
fun.call(thisp, self[i], i, self);
}
i++;
}
};
}
// ES5 15.4.4.19
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var self = Object(this);
var length = self.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var result = new Array(length);
var thisp = arguments[1];
for (var i = 0; i < length; i++) {
if (i in self)
result[i] = fun.call(thisp, self[i], i, self);
}
return result;
};
}
// ES5 15.4.4.20
if (!Array.prototype.filter) {
Array.prototype.filter = function filter(fun /*, thisp */) {
var self = Object(this);
var length = self.length >>> 0;
if (typeof fun != "function")
throw new TypeError();
var result = [];
var thisp = arguments[1];
for (var i = 0; i < length; i++)
if (i in self && fun.call(thisp, self[i], i, self))
result.push(self[i]);
return result;
};
}
// ES5 15.4.4.16
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
if (this === void 0 || this === null)
throw new TypeError();
if (typeof fun !== "function")
throw new TypeError();
var self = Object(this);
var length = self.length >>> 0;
var thisp = arguments[1];
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, self))
return false;
}
return true;
};
}
// ES5 15.4.4.17
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some
if (!Array.prototype.some) {
Array.prototype.some = function some(fun /*, thisp */) {
if (this === void 0 || this === null)
throw new TypeError();
if (typeof fun !== "function")
throw new TypeError();
var self = Object(this);
var length = self.length >>> 0;
var thisp = arguments[1];
for (var i = 0; i < length; i++) {
if (i in self && fun.call(thisp, self[i], i, self))
return true;
}
return false;
};
}
// ES5 15.4.4.21
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduce
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(fun /*, initial*/) {
var self = Object(this);
var length = self.length >>> 0;
// Whether to include (... || fun instanceof RegExp)
// in the following expression to trap cases where
// the provided function was actually a regular
// expression literal, which in V8 and
// JavaScriptCore is a typeof "function". Only in
// V8 are regular expression literals permitted as
// reduce parameters, so it is desirable in the
// general case for the shim to match the more
// strict and common behavior of rejecting regular
// expressions. However, the only case where the
// shim is applied is IE's Trident (and perhaps very
// old revisions of other engines). In Trident,
// regular expressions are a typeof "object", so the
// following guard alone is sufficient.
if (Object.prototype.toString.call(fun) != "[object Function]")
throw new TypeError();
// no value to return if no initial value and an empty array
if (!length && arguments.length == 1)
throw new TypeError();
var i = 0;
var result;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i++];
break;
}
// if array contains no values, no initial value to return
if (++i >= length)
throw new TypeError();
} while (true);
}
for (; i < length; i++) {
if (i in self)
result = fun.call(null, result, self[i], i, self);
}
return result;
};
}
// ES5 15.4.4.22
// https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight
if (!Array.prototype.reduceRight) {
Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) {
var self = Object(this);
var length = self.length >>> 0;
if (Object.prototype.toString.call(fun) != "[object Function]")
throw new TypeError();
// no value to return if no initial value, empty array
if (!length && arguments.length == 1)
throw new TypeError();
var result, i = length - 1;
if (arguments.length >= 2) {
result = arguments[1];
} else {
do {
if (i in self) {
result = self[i--];
break;
}
// if array contains no values, no initial value to return
if (--i < 0)
throw new TypeError();
} while (true);
}
do {
if (i in this)
result = fun.call(null, result, self[i], i, self);
} while (i--);
return result;
};
}
// ES5 15.4.4.14
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) {
if (this === void 0 || this === null)
throw new TypeError();
var self = Object(this);
var length = self.length >>> 0;
if (!length)
return -1;
var i = 0;
if (arguments.length > 1)
i = toInteger(arguments[1]);
// handle negative indicies
i = i >= 0 ? i : length - Math.abs(i);
for (; i < length; i++) {
if (i in self && self[i] === sought) {
return i;
}
}
return -1;
}
}
// ES5 15.4.4.15
if (!Array.prototype.lastIndexOf) {
Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) {
if (this === void 0 || this === null)
throw new TypeError();
var self = Object(this);
var length = self.length >>> 0;
if (!length)
return -1;
var i = length - 1;
if (arguments.length > 1)
i = toInteger(arguments[1]);
// handle negative indicies
i = i >= 0 ? i : length - Math.abs(i);
for (; i >= 0; i--) {
if (i in self && sought === self[i])
return i;
}
return -1;
};
}
//
// Object
// ======
//
// ES5 15.2.3.2
if (!Object.getPrototypeOf) {
// https://github.com/kriskowal/es5-shim/issues#issue/2
// http://ejohn.org/blog/objectgetprototypeof/
// recommended by fschaefer on github
Object.getPrototypeOf = function getPrototypeOf(object) {
return object.__proto__ || object.constructor.prototype;
// or undefined if not available in this engine
};
}
// ES5 15.2.3.3
if (!Object.getOwnPropertyDescriptor) {
var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " +
"non-object: ";
Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) {
if ((typeof object != "object" && typeof object != "function") || object === null)
throw new TypeError(ERR_NON_OBJECT + object);
// If object does not owns property return undefined immediately.
if (!owns(object, property))
return undefined;
var descriptor, getter, setter;
// If object has a property then it's for sure both `enumerable` and
// `configurable`.
descriptor = { enumerable: true, configurable: true };
// If JS engine supports accessor properties then property may be a
// getter or setter.
if (supportsAccessors) {
// Unfortunately `__lookupGetter__` will return a getter even
// if object has own non getter property along with a same named
// inherited getter. To avoid misbehavior we temporary remove
// `__proto__` so that `__lookupGetter__` will return getter only
// if it's owned by an object.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
var getter = lookupGetter(object, property);
var setter = lookupSetter(object, property);
// Once we have getter and setter we can put values back.
object.__proto__ = prototype;
if (getter || setter) {
if (getter) descriptor.get = getter;
if (setter) descriptor.set = setter;
// If it was accessor property we're done and return here
// in order to avoid adding `value` to the descriptor.
return descriptor;
}
}
// If we got this far we know that object has an own property that is
// not an accessor so we set it as a value and return descriptor.
descriptor.value = object[property];
return descriptor;
};
}
// ES5 15.2.3.4
if (!Object.getOwnPropertyNames) {
Object.getOwnPropertyNames = function getOwnPropertyNames(object) {
return Object.keys(object);
};
}
// ES5 15.2.3.5
if (!Object.create) {
Object.create = function create(prototype, properties) {
var object;
if (prototype === null) {
object = { "__proto__": null };
} else {
if (typeof prototype != "object")
throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'");
var Type = function () {};
Type.prototype = prototype;
object = new Type();
// IE has no built-in implementation of `Object.getPrototypeOf`
// neither `__proto__`, but this manually setting `__proto__` will
// guarantee that `Object.getPrototypeOf` will work as expected with
// objects created using `Object.create`
object.__proto__ = prototype;
}
if (typeof properties != "undefined")
Object.defineProperties(object, properties);
return object;
};
}
// ES5 15.2.3.6
var oldDefineProperty = Object.defineProperty;
var defineProperty = !!oldDefineProperty;
if (defineProperty) {
// detect IE 8's DOM-only implementation of defineProperty;
var subject = {};
Object.defineProperty(subject, "", {});
defineProperty = "" in subject;
}
if (!defineProperty) {
var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: ";
var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: "
var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " +
"on this javascript engine";
Object.defineProperty = function defineProperty(object, property, descriptor) {
if (typeof object != "object" && typeof object != "function")
throw new TypeError(ERR_NON_OBJECT_TARGET + object);
if (typeof descriptor != "object" || descriptor === null)
throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor);
// make a valiant attempt to use the real defineProperty
// for I8's DOM elements.
if (oldDefineProperty && object.nodeType)
return oldDefineProperty(object, property, descriptor);
// If it's a data property.
if (owns(descriptor, "value")) {
// fail silently if "writable", "enumerable", or "configurable"
// are requested but not supported
/*
// alternate approach:
if ( // can't implement these features; allow false but not true
!(owns(descriptor, "writable") ? descriptor.writable : true) ||
!(owns(descriptor, "enumerable") ? descriptor.enumerable : true) ||
!(owns(descriptor, "configurable") ? descriptor.configurable : true)
)
throw new RangeError(
"This implementation of Object.defineProperty does not " +
"support configurable, enumerable, or writable."
);
*/
if (supportsAccessors && (lookupGetter(object, property) ||
lookupSetter(object, property)))
{
// As accessors are supported only on engines implementing
// `__proto__` we can safely override `__proto__` while defining
// a property to make sure that we don't hit an inherited
// accessor.
var prototype = object.__proto__;
object.__proto__ = prototypeOfObject;
// Deleting a property anyway since getter / setter may be
// defined on object itself.
delete object[property];
object[property] = descriptor.value;
// Setting original `__proto__` back now.
object.__proto__ = prototype;
} else {
object[property] = descriptor.value;
}
} else {
if (!supportsAccessors)
throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED);
// If we got that far then getters and setters can be defined !!
if (owns(descriptor, "get"))
defineGetter(object, property, descriptor.get);
if (owns(descriptor, "set"))
defineSetter(object, property, descriptor.set);
}
return object;
};
}
// ES5 15.2.3.7
if (!Object.defineProperties) {
Object.defineProperties = function defineProperties(object, properties) {
for (var property in properties) {
if (owns(properties, property))
Object.defineProperty(object, property, properties[property]);
}
return object;
};
}
// ES5 15.2.3.8
if (!Object.seal) {
Object.seal = function seal(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.9
if (!Object.freeze) {
Object.freeze = function freeze(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// detect a Rhino bug and patch it
try {
Object.freeze(function () {});
} catch (exception) {
Object.freeze = (function freeze(freezeObject) {
return function freeze(object) {
if (typeof object == "function") {
return object;
} else {
return freezeObject(object);
}
};
})(Object.freeze);
}
// ES5 15.2.3.10
if (!Object.preventExtensions) {
Object.preventExtensions = function preventExtensions(object) {
// this is misleading and breaks feature-detection, but
// allows "securable" code to "gracefully" degrade to working
// but insecure code.
return object;
};
}
// ES5 15.2.3.11
if (!Object.isSealed) {
Object.isSealed = function isSealed(object) {
return false;
};
}
// ES5 15.2.3.12
if (!Object.isFrozen) {
Object.isFrozen = function isFrozen(object) {
return false;
};
}
// ES5 15.2.3.13
if (!Object.isExtensible) {
Object.isExtensible = function isExtensible(object) {
return true;
};
}
// ES5 15.2.3.14
// http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation
if (!Object.keys) {
var hasDontEnumBug = true,
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
for (var key in {"toString": null})
hasDontEnumBug = false;
Object.keys = function keys(object) {
if (
typeof object != "object" && typeof object != "function"
|| object === null
)
throw new TypeError("Object.keys called on a non-object");
var keys = [];
for (var name in object) {
if (owns(object, name)) {
keys.push(name);
}
}
if (hasDontEnumBug) {
for (var i = 0, ii = dontEnumsLength; i < ii; i++) {
var dontEnum = dontEnums[i];
if (owns(object, dontEnum)) {
keys.push(dontEnum);
}
}
}
return keys;
};
}
//
// Date
// ====
//
// ES5 15.9.5.43
// Format a Date object as a string according to a simplified subset of the ISO 8601
// standard as defined in 15.9.1.15.
if (!Date.prototype.toISOString) {
Date.prototype.toISOString = function toISOString() {
var result, length, value;
if (!isFinite(this))
throw new RangeError;
// the date time string format is specified in 15.9.1.15.
result = [this.getUTCFullYear(), this.getUTCMonth() + 1, this.getUTCDate(),
this.getUTCHours(), this.getUTCMinutes(), this.getUTCSeconds()];
length = result.length;
while (length--) {
value = result[length];
// pad months, days, hours, minutes, and seconds to have two digits.
if (value < 10)
result[length] = '0' + value;
}
// pad milliseconds to have three digits.
return result.slice(0, 3).join('-') + 'T' + result.slice(3).join(':') + '.' +
('000' + this.getUTCMilliseconds()).slice(-3) + 'Z';
}
}
// ES5 15.9.4.4
if (!Date.now) {
Date.now = function now() {
return new Date().getTime();
};
}
// ES5 15.9.5.44
if (!Date.prototype.toJSON) {
Date.prototype.toJSON = function toJSON(key) {
// This function provides a String representation of a Date object for
// use by JSON.stringify (15.12.3). When the toJSON method is called
// with argument key, the following steps are taken:
// 1. Let O be the result of calling ToObject, giving it the this
// value as its argument.
// 2. Let tv be ToPrimitive(O, hint Number).
// 3. If tv is a Number and is not finite, return null.
// XXX
// 4. Let toISO be the result of calling the [[Get]] internal method of
// O with argument "toISOString".
// 5. If IsCallable(toISO) is false, throw a TypeError exception.
// XXX this gets pretty close, for all intents and purposes, letting
// some duck-types slide
if (typeof this.toISOString.call != "function")
throw new TypeError();
// 6. Return the result of calling the [[Call]] internal method of
// toISO with O as the this value and an empty argument list.
return this.toISOString.call(this);
// NOTE 1 The argument is ignored.
// NOTE 2 The toJSON function is intentionally generic; it does not
// require that its this value be a Date object. Therefore, it can be
// transferred to other kinds of objects for use as a method. However,
// it does require that any such object have a toISOString method. An
// object is free to use the argument key to filter its
// stringification.
};
}
// 15.9.4.2 Date.parse (string)
// 15.9.1.15 Date Time String Format
// Date.parse
// based on work shared by Daniel Friesen (dantman)
// http://gist.github.com/303249
if (isNaN(Date.parse("2011-06-15T21:40:05+06:00"))) {
// XXX global assignment won't work in embeddings that use
// an alternate object for the context.
Date = (function(NativeDate) {
// Date.length === 7
var Date = function(Y, M, D, h, m, s, ms) {
var length = arguments.length;
if (this instanceof NativeDate) {
var date = length == 1 && String(Y) === Y ? // isString(Y)
// We explicitly pass it through parse:
new NativeDate(Date.parse(Y)) :
// We have to manually make calls depending on argument
// length here
length >= 7 ? new NativeDate(Y, M, D, h, m, s, ms) :
length >= 6 ? new NativeDate(Y, M, D, h, m, s) :
length >= 5 ? new NativeDate(Y, M, D, h, m) :
length >= 4 ? new NativeDate(Y, M, D, h) :
length >= 3 ? new NativeDate(Y, M, D) :
length >= 2 ? new NativeDate(Y, M) :
length >= 1 ? new NativeDate(Y) :
new NativeDate();
// Prevent mixups with unfixed Date object
date.constructor = Date;
return date;
}
return NativeDate.apply(this, arguments);
};
// 15.9.1.15 Date Time String Format. This pattern does not implement
// extended years ((15.9.1.15.1), as `Date.UTC` cannot parse them.
var isoDateExpression = new RegExp("^" +
"(\d{4})" + // four-digit year capture
"(?:-(\d{2})" + // optional month capture
"(?:-(\d{2})" + // optional day capture
"(?:" + // capture hours:minutes:seconds.milliseconds
"T(\d{2})" + // hours capture
":(\d{2})" + // minutes capture
"(?:" + // optional :seconds.milliseconds
":(\d{2})" + // seconds capture
"(?:\.(\d{3}))?" + // milliseconds capture
")?" +
"(?:" + // capture UTC offset component
"Z|" + // UTC capture
"(?:" + // offset specifier +/-hours:minutes
"([-+])" + // sign capture
"(\d{2})" + // hours offset capture
":(\d{2})" + // minutes offest capture
")" +
")?)?)?)?" +
"$");
// Copy any custom methods a 3rd party library may have added
for (var key in NativeDate)
Date[key] = NativeDate[key];
// Copy "native" methods explicitly; they may be non-enumerable
Date.now = NativeDate.now;
Date.UTC = NativeDate.UTC;
Date.prototype = NativeDate.prototype;
Date.prototype.constructor = Date;
// Upgrade Date.parse to handle simplified ISO 8601 strings
Date.parse = function parse(string) {
var match = isoDateExpression.exec(string);
if (match) {
match.shift(); // kill match[0], the full match
// parse months, days, hours, minutes, seconds, and milliseconds
for (var i = 1; i < 7; i++) {
// provide default values if necessary
match[i] = +(match[i] || (i < 3 ? 1 : 0));
// match[1] is the month. Months are 0-11 in JavaScript
// `Date` objects, but 1-12 in ISO notation, so we
// decrement.
if (i == 1)
match[i]--;
}
// parse the UTC offset component
var minutesOffset = +match.pop(), hourOffset = +match.pop(), sign = match.pop();
// compute the explicit time zone offset if specified
var offset = 0;
if (sign) {
// detect invalid offsets and return early
if (hourOffset > 23 || minuteOffset > 59)
return NaN;
// express the provided time zone offset in minutes. The offset is
// negative for time zones west of UTC; positive otherwise.
offset = (hourOffset * 60 + minuteOffset) * 6e4 * (sign == "+" ? -1 : 1);
}
// compute a new UTC date value, accounting for the optional offset
return NativeDate.UTC.apply(this, match) + offset;
}
return NativeDate.parse.apply(this, arguments);
};
return Date;
})(Date);
}
//
// String
// ======
//
// ES5 15.5.4.20
if (!String.prototype.trim) {
// http://blog.stevenlevithan.com/archives/faster-trim-javascript
// http://perfectionkills.com/whitespace-deviations/
var s = "[\x09\x0A\-\x0D\x20\xA0\u1680\u180E\u2000-\u200A\u202F" +
"\u205F\u3000\u2028\u2029\uFEFF]"
var trimBeginRegexp = new RegExp("^" + s + s + "*");
var trimEndRegexp = new RegExp(s + s + "*$");
String.prototype.trim = function trim() {
return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, "");
};
}
//
// Util
// ======
//
// http://jsperf.com/to-integer
var toInteger = function (n) {
n = +n;
if (n !== n) // isNaN
n = -1;
else if (n !== 0 && n !== (1/0) && n !== -(1/0))
n = (n > 0 || -1) * Math.floor(Math.abs(n));
return n;
};
});
| RizkyAdiSaputra/cdnjs | ajax/libs/es5-shim/1.2.9/es5-shim.js | JavaScript | mit | 34,072 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Bundle\FrameworkBundle\Controller;
use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
/**
* Redirects a request to another URL.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class RedirectController extends ContainerAware
{
/**
* Redirects to another route with the given name.
*
* The response status code is 302 if the permanent parameter is false (default),
* and 301 if the redirection is permanent.
*
* In case the route name is empty, the status code will be 404 when permanent is false
* and 410 otherwise.
*
* @param Request $request The request instance
* @param string $route The route name to redirect to
* @param Boolean $permanent Whether the redirection is permanent
* @param Boolean|array $ignoreAttributes Whether to ignore attributes or an array of attributes to ignore
*
* @return Response A Response instance
*/
public function redirectAction(Request $request, $route, $permanent = false, $ignoreAttributes = false)
{
if ('' == $route) {
return new Response(null, $permanent ? 410 : 404);
}
$attributes = array();
if (false === $ignoreAttributes || is_array($ignoreAttributes)) {
$attributes = $request->attributes->get('_route_params');
unset($attributes['route'], $attributes['permanent'], $attributes['ignoreAttributes']);
if ($ignoreAttributes) {
$attributes = array_diff_key($attributes, array_flip($ignoreAttributes));
}
}
return new RedirectResponse($this->container->get('router')->generate($route, $attributes, UrlGeneratorInterface::ABSOLUTE_URL), $permanent ? 301 : 302);
}
/**
* Redirects to a URL.
*
* The response status code is 302 if the permanent parameter is false (default),
* and 301 if the redirection is permanent.
*
* In case the path is empty, the status code will be 404 when permanent is false
* and 410 otherwise.
*
* @param Request $request The request instance
* @param string $path The absolute path or URL to redirect to
* @param Boolean $permanent Whether the redirect is permanent or not
* @param string|null $scheme The URL scheme (null to keep the current one)
* @param integer|null $httpPort The HTTP port (null to keep the current one for the same scheme or the configured port in the container)
* @param integer|null $httpsPort The HTTPS port (null to keep the current one for the same scheme or the configured port in the container)
*
* @return Response A Response instance
*/
public function urlRedirectAction(Request $request, $path, $permanent = false, $scheme = null, $httpPort = null, $httpsPort = null)
{
if ('' == $path) {
return new Response(null, $permanent ? 410 : 404);
}
$statusCode = $permanent ? 301 : 302;
// redirect if the path is a full URL
if (parse_url($path, PHP_URL_SCHEME)) {
return new RedirectResponse($path, $statusCode);
}
if (null === $scheme) {
$scheme = $request->getScheme();
}
$qs = $request->getQueryString();
if ($qs) {
$qs = '?'.$qs;
}
$port = '';
if ('http' === $scheme) {
if (null === $httpPort) {
if ('http' === $request->getScheme()) {
$httpPort = $request->getPort();
} elseif ($this->container->hasParameter('request_listener.http_port')) {
$httpPort = $this->container->getParameter('request_listener.http_port');
}
}
if (null !== $httpPort && 80 != $httpPort) {
$port = ":$httpPort";
}
} elseif ('https' === $scheme) {
if (null === $httpsPort) {
if ('https' === $request->getScheme()) {
$httpsPort = $request->getPort();
} elseif ($this->container->hasParameter('request_listener.https_port')) {
$httpsPort = $this->container->getParameter('request_listener.https_port');
}
}
if (null !== $httpsPort && 443 != $httpsPort) {
$port = ":$httpsPort";
}
}
$url = $scheme.'://'.$request->getHost().$port.$request->getBaseUrl().$path.$qs;
return new RedirectResponse($url, $statusCode);
}
}
| francoisrai/raibanh_template | vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/RedirectController.php | PHP | mit | 5,062 |
/**
* Cross-Origin Resource Sharing (CORS) Settings
* (sails.config.cors)
*
* CORS is like a more modern version of JSONP-- it allows your server/API
* to successfully respond to requests from client-side JavaScript code
* running on some other domain (e.g. google.com)
* Unlike JSONP, it works with POST, PUT, and DELETE requests
*
* For more information on CORS, check out:
* http://en.wikipedia.org/wiki/Cross-origin_resource_sharing
*
* Note that any of these settings (besides 'allRoutes') can be changed on a per-route basis
* by adding a "cors" object to the route configuration:
*
* '/get foo': {
* controller: 'foo',
* action: 'bar',
* cors: {
* origin: 'http://foobar.com,https://owlhoot.com'
* }
* }
*
* For more information on this configuration file, see:
* http://sailsjs.org/#!/documentation/reference/sails.config/sails.config.cors.html
*
*/
module.exports.cors = {
/***************************************************************************
* *
* Allow CORS on all routes by default? If not, you must enable CORS on a *
* per-route basis by either adding a "cors" configuration object to the *
* route config, or setting "cors:true" in the route config to use the *
* default settings below. *
* *
***************************************************************************/
// allRoutes: false,
/***************************************************************************
* *
* Which domains which are allowed CORS access? This can be a *
* comma-delimited list of hosts (beginning with http:// or https://) or *
* "*" to allow all domains CORS access. *
* *
***************************************************************************/
// origin: '*',
/***************************************************************************
* *
* Allow cookies to be shared for CORS requests? *
* *
***************************************************************************/
// credentials: true,
/***************************************************************************
* *
* Which methods should be allowed for CORS requests? This is only used in *
* response to preflight requests (see article linked above for more info) *
* *
***************************************************************************/
// methods: 'GET, POST, PUT, DELETE, OPTIONS, HEAD',
/***************************************************************************
* *
* Which headers should be allowed for CORS requests? This is only used in *
* response to preflight requests. *
* *
***************************************************************************/
// headers: 'content-type'
};
| albi34/help-me-choose | config/cors.js | JavaScript | mit | 3,615 |
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
<html lang="en" xmlns="http://www.w3.org/1999/html"> <!--<![endif]-->
<head>
<!-- Basic Page Needs
================================================== -->
<meta charset="utf-8" />
<title>icon-sort-by-alphabet-alt: Font Awesome Icons</title>
<meta name="description" content="Font Awesome, the iconic font designed for Bootstrap">
<meta name="author" content="Dave Gandy">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--<meta name="viewport" content="initial-scale=1; maximum-scale=1">-->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- CSS
================================================== -->
<link rel="stylesheet" href="../../assets/css/site.css">
<link rel="stylesheet" href="../../assets/css/pygments.css">
<link rel="stylesheet" href="../../assets/font-awesome/css/font-awesome.css">
<!--[if IE 7]>
<link rel="stylesheet" href="../../assets/font-awesome/css/font-awesome-ie7.css">
<![endif]-->
<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="../../assets/ico/favicon.ico">
<script type="text/javascript" src="//use.typekit.net/wnc7ioh.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-30136587-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body data-spy="scroll" data-target=".navbar">
<div class="wrapper"> <!-- necessary for sticky footer. wrap all content except footer -->
<div class="navbar navbar-inverse navbar-static-top hidden-print">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="../../"><i class="icon-flag"></i> Font Awesome</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="hidden-tablet "><a href="../../">Home</a></li>
<li><a href="../../get-started/">Get Started</a></li>
<li class="dropdown-split-left"><a href="../../icons/">Icons</a></li>
<li class="dropdown dropdown-split-right hidden-phone">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-caret-down"></i>
</a>
<ul class="dropdown-menu pull-right">
<li><a href="../../icons/"><i class="icon-flag icon-fixed-width"></i> Icons</a></li>
<li class="divider"></li>
<li><a href="../../icons/#new"><i class="icon-shield icon-fixed-width"></i> New Icons in 3.2.1</a></li>
<li><a href="../../icons/#web-application"><i class="icon-camera-retro icon-fixed-width"></i> Web Application Icons</a></li>
<li><a href="../../icons/#currency"><i class="icon-won icon-fixed-width"></i> Currency Icons</a></li>
<li><a href="../../icons/#text-editor"><i class="icon-file-text-alt icon-fixed-width"></i> Text Editor Icons</a></li>
<li><a href="../../icons/#directional"><i class="icon-hand-right icon-fixed-width"></i> Directional Icons</a></li>
<li><a href="../../icons/#video-player"><i class="icon-play-sign icon-fixed-width"></i> Video Player Icons</a></li>
<li><a href="../../icons/#brand"><i class="icon-github icon-fixed-width"></i> Brand Icons</a></li>
<li><a href="../../icons/#medical"><i class="icon-medkit icon-fixed-width"></i> Medical Icons</a></li>
</ul>
</li>
<li class="dropdown-split-left"><a href="../../examples/">Examples</a></li>
<li class="dropdown dropdown-split-right hidden-phone">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-caret-down"></i>
</a>
<ul class="dropdown-menu pull-right">
<li><a href="../../examples/">Examples</a></li>
<li class="divider"></li>
<li><a href="../../examples/#new-styles">New Styles</a></li>
<li><a href="../../examples/#inline-icons">Inline Icons</a></li>
<li><a href="../../examples/#larger-icons">Larger Icons</a></li>
<li><a href="../../examples/#bordered-pulled">Bordered & Pulled</a></li>
<li><a href="../../examples/#buttons">Buttons</a></li>
<li><a href="../../examples/#button-groups">Button Groups</a></li>
<li><a href="../../examples/#button-dropdowns">Button Dropdowns</a></li>
<li><a href="../../examples/#bulleted-lists">Bulleted Lists</a></li>
<li><a href="../../examples/#navigation">Navigation</a></li>
<li><a href="../../examples/#form-inputs">Form Inputs</a></li>
<li><a href="../../examples/#animated-spinner">Animated Spinner</a></li>
<li><a href="../../examples/#rotated-flipped">Rotated & Flipped</a></li>
<li><a href="../../examples/#stacked">Stacked</a></li>
<li><a href="../../examples/#custom">Custom CSS</a></li>
</ul>
</li>
<li><a href="../../whats-new/">
<span class="hidden-tablet">What's </span>New</a>
</li>
<li><a href="../../community/">Community</a></li>
<li><a href="../../license/">License</a></li>
</ul>
<ul class="nav pull-right">
<li><a href="http://blog.fontawesome.io">Blog</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="jumbotron jumbotron-icon">
<div class="container">
<div class="info-icons">
<i class="icon-sort-by-alphabet-alt icon-6"></i>
<span class="hidden-phone">
<i class="icon-sort-by-alphabet-alt icon-5"></i>
<span class="hidden-tablet"><i class="icon-sort-by-alphabet-alt icon-4"></i> </span>
<i class="icon-sort-by-alphabet-alt icon-3"></i>
<i class="icon-sort-by-alphabet-alt icon-2"></i>
</span>
<i class="icon-sort-by-alphabet-alt icon-1"></i>
</div>
<h1 class="info-class">
icon-sort-by-alphabet-alt
<small>
<i class="icon-sort-by-alphabet-alt"></i> ·
Unicode: <span class="upper">f15e</span> ·
Created: v3.2 ·
Categories:
Web Application Icons
</small>
</h1>
</div>
</div>
<div class="container">
<section>
<div class="row-fluid">
<div class="span9">
<p>After you get <a href="../../integration/">up and running</a>, you can place Font Awesome icons just about anywhere with the <code><i></code> tag:</p>
<div class="well well-transparent">
<div style="font-size: 24px; line-height: 1.5em;">
<i class="icon-sort-by-alphabet-alt"></i> icon-sort-by-alphabet-alt
</div>
</div>
<div class="highlight"><pre><code class="html"><span class="nt"><i</span> <span class="na">class=</span><span class="s">"icon-sort-by-alphabet-alt"</span><span class="nt">></i></span> icon-sort-by-alphabet-alt
</code></pre></div>
<br>
<div class="lead"><i class="icon-info-sign"></i> Looking for more? Check out the <a href="../../examples/">examples</a>.</div>
</div>
<div class="span3">
<div class="info-ad"><div id="carbonads-container"><div class="carbonad"><div id="azcarbon"></div><script type="text/javascript">var z = document.createElement("script"); z.type = "text/javascript"; z.async = true; z.src = "http://engine.carbonads.com/z/32291/azcarbon_2_1_0_VERT"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(z, s);</script></div></div>
</div>
</div>
</div>
</section>
</div>
<div class="push"><!-- necessary for sticky footer --></div>
</div>
<footer class="footer hidden-print">
<div class="container text-center">
<div>
<i class="icon-flag"></i> Font Awesome 3.2.1
<span class="hidden-phone">·</span><br class="visible-phone">
Created and Maintained by <a href="http://twitter.com/davegandy">Dave Gandy</a>
</div>
<div>
Font Awesome licensed under <a href="http://scripts.sil.org/OFL">SIL OFL 1.1</a>
<span class="hidden-phone">·</span><br class="visible-phone">
Code licensed under <a href="http://opensource.org/licenses/mit-license.html">MIT License</a>
<span class="hidden-phone hidden-tablet">·</span><br class="visible-phone visible-tablet">
Documentation licensed under <a href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a>
</div>
<div>
Thanks to <a href="http://maxcdn.com"><i class="icon-maxcdn"></i> MaxCDN</a> for providing the excellent <a href="http://www.bootstrapcdn.com/#tab_fontawesome">BootstrapCDN for Font Awesome</a>
</div>
<div class="project">
<a href="https://github.com/FortAwesome/Font-Awesome">GitHub Project</a> ·
<a href="https://github.com/FortAwesome/Font-Awesome/issues">Issues</a>
</div>
</div>
</footer>
<script src="http://platform.twitter.com/widgets.js"></script>
<script src="../../assets/js/jquery-1.7.1.min.js"></script>
<script src="../../assets/js/ZeroClipboard-1.1.7.min.js"></script>
<script src="../../assets/js/bootstrap-2.3.1.min.js"></script>
<script src="../../assets/js/site.js"></script>
</body>
</html>
| nishant8BITS/video-exercises | in-video-exercises/M6/font-awesome/src/3.2.1/icon/sort-by-alphabet-alt/index.html | HTML | mit | 10,238 |
.ui-rangeSlider{height:22px}.ui-rangeSlider .ui-rangeSlider-innerBar{height:16px;margin:3px 6px;background:#DDD}.ui-rangeSlider .ui-rangeSlider-handle{width:6px;height:22px;background:#AAA;background:rgba(100,100,100,0.3);cursor:col-resize}.ui-rangeSlider .ui-rangeSlider-bar{margin:1px 0;background:#CCC;background:rgba(100,100,150,0.2);height:20px;cursor:move;cursor:grab;cursor:-moz-grab}.ui-rangeSlider .ui-rangeSlider-bar.ui-draggable-dragging{cursor:-moz-grabbing;cursor:grabbing}.ui-rangeSlider-arrow{height:16px;margin:2px 0;width:16px;background-repeat:no-repeat;cursor:pointer}.ui-rangeSlider-arrow.ui-rangeSlider-leftArrow{background-image:url('icons/resultset_previous.png');background-position:center left}.ui-rangeSlider-arrow.ui-rangeSlider-rightArrow{background-image:url('icons/resultset_next.png');background-position:center right}.ui-rangeSlider-container{height:22px}.ui-rangeSlider-withArrows .ui-rangeSlider-container{margin:0 11px}.ui-rangeSlider-noArrow .ui-rangeSlider-container{margin:0}.ui-rangeSlider-label{padding:2px 5px 6px;margin:0 2px 2px;background-image:url('icons/label.png');background-position:bottom center;background-repeat:no-repeat;white-space:nowrap}input.ui-editRangeSlider-inputValue{width:3em;vertical-align:middle;text-align:center} | Piicksarn/cdnjs | ajax/libs/jQRangeSlider/4.0/css/dev.min.css | CSS | mit | 1,279 |
/*!
* jQuery JavaScript Library v1.7.2
* http://jquery.com/
*
* Copyright 2011, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Wed Mar 21 12:46:34 2012 -0700
*/
(function( window, undefined ) {
'use strict';
// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
navigator = window.navigator,
location = window.location;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Matches dashed string for camelizing
rdashAlpha = /-([a-z]|[0-9])/ig,
rmsPrefix = /^-ms-/,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// The deferred used on DOM ready
readyList,
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context ? context.ownerDocument || context : document );
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.7.2",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.add( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.fireWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).off( "ready" );
}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery.Callbacks( "once memory" );
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
isWindow: function( obj ) {
return obj != null && obj == obj.window;
},
isNumeric: function( obj ) {
return !isNaN( parseFloat(obj) ) && isFinite( obj );
},
type: function( obj ) {
return obj == null ?
String( obj ) :
class2type[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
var xml, tmp;
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array );
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array, i ) {
var len;
if ( array ) {
if ( indexOf ) {
return indexOf.call( array, elem, i );
}
len = array.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in array && array[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
if ( typeof context === "string" ) {
var tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ),
proxy = function() {
return fn.apply( context, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can optionally be executed if it's a function
access: function( elems, fn, key, value, chainable, emptyGet, pass ) {
var exec,
bulk = key == null,
i = 0,
length = elems.length;
// Sets many values
if ( key && typeof key === "object" ) {
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], 1, emptyGet, value );
}
chainable = 1;
// Sets one value
} else if ( value !== undefined ) {
// Optionally, function values get executed if exec is true
exec = pass === undefined && jQuery.isFunction( value );
if ( bulk ) {
// Bulk operations only iterate when executing function values
if ( exec ) {
exec = fn;
fn = function( elem, key, value ) {
return exec.call( jQuery( elem ), value );
};
// Otherwise they run against the entire set
} else {
fn.call( elems, value );
fn = null;
}
}
if ( fn ) {
for (; i < length; i++ ) {
fn( elems[i], key, exec ? value.call( elems[i], i, fn( elems[i], key ) ) : value, pass );
}
}
chainable = 1;
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
length ? fn( elems[0], key ) : emptyGet;
},
now: function() {
return ( new Date() ).getTime();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
return jQuery;
})();
// String to Object flags format cache
var flagsCache = {};
// Convert String-formatted flags into Object-formatted ones and store in cache
function createFlags( flags ) {
var object = flagsCache[ flags ] = {},
i, length;
flags = flags.split( /\s+/ );
for ( i = 0, length = flags.length; i < length; i++ ) {
object[ flags[i] ] = true;
}
return object;
}
/*
* Create a callback list using the following parameters:
*
* flags: an optional list of space-separated flags that will change how
* the callback list behaves
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible flags:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( flags ) {
// Convert flags from String-formatted to Object-formatted
// (we check in cache first)
flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};
var // Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = [],
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Add one or several callbacks to the list
add = function( args ) {
var i,
length,
elem,
type,
actual;
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
// Inspect recursively
add( elem );
} else if ( type === "function" ) {
// Add if not in unique mode and callback is not in
if ( !flags.unique || !self.has( elem ) ) {
list.push( elem );
}
}
}
},
// Fire callbacks
fire = function( context, args ) {
args = args || [];
memory = !flags.memory || [ context, args ];
fired = true;
firing = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) {
memory = true; // Mark as halted
break;
}
}
firing = false;
if ( list ) {
if ( !flags.once ) {
if ( stack && stack.length ) {
memory = stack.shift();
self.fireWith( memory[ 0 ], memory[ 1 ] );
}
} else if ( memory === true ) {
self.disable();
} else {
list = [];
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
var length = list.length;
add( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away, unless previous
// firing was halted (stopOnFalse)
} else if ( memory && memory !== true ) {
firingStart = length;
fire( memory[ 0 ], memory[ 1 ] );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
var args = arguments,
argIndex = 0,
argLength = args.length;
for ( ; argIndex < argLength ; argIndex++ ) {
for ( var i = 0; i < list.length; i++ ) {
if ( args[ argIndex ] === list[ i ] ) {
// Handle firingIndex and firingLength
if ( firing ) {
if ( i <= firingLength ) {
firingLength--;
if ( i <= firingIndex ) {
firingIndex--;
}
}
}
// Remove the element
list.splice( i--, 1 );
// If we have some unicity property then
// we only need to do this once
if ( flags.unique ) {
break;
}
}
}
}
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
if ( list ) {
var i = 0,
length = list.length;
for ( ; i < length; i++ ) {
if ( fn === list[ i ] ) {
return true;
}
}
}
return false;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory || memory === true ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( stack ) {
if ( firing ) {
if ( !flags.once ) {
stack.push( [ context, args ] );
}
} else if ( !( flags.once && memory ) ) {
fire( context, args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
var // Static reference to slice
sliceDeferred = [].slice;
jQuery.extend({
Deferred: function( func ) {
var doneList = jQuery.Callbacks( "once memory" ),
failList = jQuery.Callbacks( "once memory" ),
progressList = jQuery.Callbacks( "memory" ),
state = "pending",
lists = {
resolve: doneList,
reject: failList,
notify: progressList
},
promise = {
done: doneList.add,
fail: failList.add,
progress: progressList.add,
state: function() {
return state;
},
// Deprecated
isResolved: doneList.fired,
isRejected: failList.fired,
then: function( doneCallbacks, failCallbacks, progressCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks );
return this;
},
always: function() {
deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments );
return this;
},
pipe: function( fnDone, fnFail, fnProgress ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ],
progress: [ fnProgress, "notify" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
if ( obj == null ) {
obj = promise;
} else {
for ( var key in promise ) {
obj[ key ] = promise[ key ];
}
}
return obj;
}
},
deferred = promise.promise({}),
key;
for ( key in lists ) {
deferred[ key ] = lists[ key ].fire;
deferred[ key + "With" ] = lists[ key ].fireWith;
}
// Handle state
deferred.done( function() {
state = "resolved";
}, failList.disable, progressList.lock ).fail( function() {
state = "rejected";
}, doneList.disable, progressList.lock );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = sliceDeferred.call( arguments, 0 ),
i = 0,
length = args.length,
pValues = new Array( length ),
count = length,
pCount = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred(),
promise = deferred.promise();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
deferred.resolveWith( deferred, args );
}
};
}
function progressFunc( i ) {
return function( value ) {
pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
deferred.notifyWith( promise, pValues );
};
}
if ( length > 1 ) {
for ( ; i < length; i++ ) {
if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return promise;
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
tds,
events,
eventName,
i,
isSupported,
div = document.createElement( "div" ),
documentElement = document.documentElement;
// Preliminary tests
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName( "*" );
a = div.getElementsByTagName( "a" )[ 0 ];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return {};
}
// First batch of supports tests
select = document.createElement( "select" );
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName( "input" )[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form(#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
pixelMargin: true
};
// jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead
jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat");
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent( "onclick" );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked");
// #11217 - WebKit loses check when the name is after the checked attribute
input.setAttribute( "name", "t" );
div.appendChild( input );
fragment = document.createDocumentFragment();
fragment.appendChild( div.lastChild );
// WebKit doesn't clone checked state correctly in fragments
support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Check if a disconnected checkbox will retain its checked
// value of true after appended to the DOM (IE6/7)
support.appendChecked = input.checked;
fragment.removeChild( input );
fragment.appendChild( div );
// Technique from Juriy Zaytsev
// http://perfectionkills.com/detecting-event-support-without-browser-sniffing/
// We only care about the case where non-standard event systems
// are used, namely in IE. Short-circuiting here helps us to
// avoid an eval call (in setAttribute) which can cause CSP
// to go haywire. See: https://developer.mozilla.org/en/Security/CSP
if ( div.attachEvent ) {
for ( i in {
submit: 1,
change: 1,
focusin: 1
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
fragment.removeChild( div );
// Null elements to avoid leaks in IE
fragment = select = opt = div = input = null;
// Run tests that need a body at doc ready
jQuery(function() {
var container, outer, inner, table, td, offsetSupport,
marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight,
paddingMarginBorderVisibility, paddingMarginBorder,
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
conMarginTop = 1;
paddingMarginBorder = "padding:0;margin:0;border:";
positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;";
paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;";
style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;";
html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" +
"<table " + style + "' cellpadding='0' cellspacing='0'>" +
"<tr><td></td></tr></table>";
container = document.createElement("div");
container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( window.getComputedStyle ) {
div.innerHTML = "";
marginDiv = document.createElement( "div" );
marginDiv.style.width = "0";
marginDiv.style.marginRight = "0";
div.style.width = "2px";
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
}
if ( typeof div.style.zoom !== "undefined" ) {
// Check if natively block-level elements act like inline-block
// elements when setting their display to 'inline' and giving
// them layout
// (IE < 8 does this)
div.innerHTML = "";
div.style.width = div.style.padding = "1px";
div.style.border = 0;
div.style.overflow = "hidden";
div.style.display = "inline";
div.style.zoom = 1;
support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 );
// Check if elements with layout shrink-wrap their children
// (IE 6 does this)
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div style='width:5px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
}
div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility;
div.innerHTML = html;
outer = div.firstChild;
inner = outer.firstChild;
td = outer.nextSibling.firstChild.firstChild;
offsetSupport = {
doesNotAddBorder: ( inner.offsetTop !== 5 ),
doesAddBorderForTableAndCells: ( td.offsetTop === 5 )
};
inner.style.position = "fixed";
inner.style.top = "20px";
// safari subtracts parent border width here which is 5px
offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 );
inner.style.position = inner.style.top = "";
outer.style.overflow = "hidden";
outer.style.position = "relative";
offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
if ( window.getComputedStyle ) {
div.style.marginTop = "1%";
support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%";
}
if ( typeof container.style.zoom !== "undefined" ) {
container.style.zoom = 1;
}
body.removeChild( container );
marginDiv = div = container = null;
jQuery.extend( support, offsetSupport );
});
return support;
})();
var rbrace = /^(?:\{.*\}|\[.*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var privateCache, thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey,
isEvents = name === "events";
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = ++jQuery.uuid;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
privateCache = thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Users should not attempt to inspect the internal events object using jQuery.data,
// it is undocumented and subject to change. But does anyone listen? No.
if ( isEvents && !thisCache[ name ] ) {
return privateCache.events;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
// Reference to internal data cache key
internalKey = jQuery.expando,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ internalKey ] : internalKey;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split( " " );
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
// Ensure that `cache` is not a window object #10080
if ( jQuery.support.deleteExpando || !cache.setInterval ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the cache and need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, part, attr, name, l,
elem = this[0],
i = 0,
data = null;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = jQuery.data( elem );
if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
attr = elem.attributes;
for ( l = attr.length; i < l; i++ ) {
name = attr[i].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.substring(5) );
dataAttr( elem, name, data[ name ] );
}
}
jQuery._data( elem, "parsedAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
jQuery.data( this, key );
});
}
parts = key.split( ".", 2 );
parts[1] = parts[1] ? "." + parts[1] : "";
part = parts[1] + "!";
return jQuery.access( this, function( value ) {
if ( value === undefined ) {
data = this.triggerHandler( "getData" + part, [ parts[0] ] );
// Try to fetch any internally stored data first
if ( data === undefined && elem ) {
data = jQuery.data( elem, key );
data = dataAttr( elem, key, data );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
}
parts[1] = value;
this.each(function() {
var self = jQuery( this );
self.triggerHandler( "setData" + part, parts );
jQuery.data( this, key, value );
self.triggerHandler( "changeData" + part, parts );
});
}, null, value, arguments.length > 1, null, false );
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
function dataAttr( elem, key, data ) {
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
jQuery.isNumeric( data ) ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
jQuery.data( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
// checks a cache object for emptiness
function isEmptyDataObject( obj ) {
for ( var name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function handleQueueMarkDefer( elem, type, src ) {
var deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
defer = jQuery._data( elem, deferDataKey );
if ( defer &&
( src === "queue" || !jQuery._data(elem, queueDataKey) ) &&
( src === "mark" || !jQuery._data(elem, markDataKey) ) ) {
// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout( function() {
if ( !jQuery._data( elem, queueDataKey ) &&
!jQuery._data( elem, markDataKey ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.fire();
}
}, 0 );
}
}
jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = ( type || "fx" ) + "mark";
jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 );
}
},
_unmark: function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 );
if ( count ) {
jQuery._data( elem, key, count );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) {
var q;
if ( elem ) {
type = ( type || "fx" ) + "queue";
q = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
}
}
return q || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
hooks = {};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
jQuery._data( elem, type + ".run", hooks );
fn.call( elem, function() {
jQuery.dequeue( elem, type );
}, hooks );
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue " + type + ".run", true );
handleQueueMarkDefer( elem, type, "queue" );
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, object ) {
if ( typeof type !== "string" ) {
object = type;
type = undefined;
}
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
tmp;
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) {
count++;
tmp.add( resolve );
}
}
resolve();
return defer.promise( object );
}
});
var rclass = /[\n\t\r]/g,
rspace = /\s+/,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
nodeHook, boolHook, fixSpecified;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
},
prop: function( name, value ) {
return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
name = jQuery.propFix[ name ] || name;
return this.each(function() {
// try/catch handles cases where IE balks (such as removing a property on window)
try {
this[ name ] = undefined;
delete this[ name ];
} catch( e ) {}
});
},
addClass: function( value ) {
var classNames, i, l, elem,
setClass, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call(this, j, this.className) );
});
}
if ( value && typeof value === "string" ) {
classNames = value.split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classNames, i, l, elem, className, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
classNames = ( value || "" ).split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
className = (" " + elem.className + " ").replace( rclass, " " );
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[ c ] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
// attributes.value is undefined in Blackberry 4.7 but
// uses .value. See #6932
var val = elem.attributes.value;
return !val || val.specified ? elem.value : elem.text;
}
},
select: {
get: function( elem ) {
var value, i, max, option,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
i = one ? index : 0;
max = one ? index + 1 : options.length;
for ( ; i < max; i++ ) {
option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, l, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.toLowerCase().split( rspace );
l = attrNames.length;
for ( ; i < l; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
isBool = rboolean.test( name );
// See #9699 for explanation of this approach (setting first, then removal)
// Do not do this for boolean attributes (see #10870)
if ( !isBool ) {
jQuery.attr( elem, name, "" );
}
elem.removeAttribute( getSetAttribute ? name : propName );
// Set corresponding property to false for boolean attributes
if ( isBool && propName in elem ) {
elem[ propName ] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
// We can't allow the type property to be changed (since it causes problems in IE)
if ( rtype.test( elem.nodeName ) && elem.parentNode ) {
jQuery.error( "type property can't be changed" );
} else if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to it's default in case type is set after value
// This is for element creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
},
// Use the value property for back compat
// Use the nodeHook for button elements in IE6/7 (#1954)
value: {
get: function( elem, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.get( elem, name );
}
return name in elem ?
elem.value :
null;
},
set: function( elem, value, name ) {
if ( nodeHook && jQuery.nodeName( elem, "button" ) ) {
return nodeHook.set( elem, value, name );
}
// Does not return so that setAttribute is also used
elem.value = value;
}
}
},
propFix: {
tabindex: "tabIndex",
readonly: "readOnly",
"for": "htmlFor",
"class": "className",
maxlength: "maxLength",
cellspacing: "cellSpacing",
cellpadding: "cellPadding",
rowspan: "rowSpan",
colspan: "colSpan",
usemap: "useMap",
frameborder: "frameBorder",
contenteditable: "contentEditable"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
return ( elem[ name ] = value );
}
} else {
if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
return elem[ name ];
}
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
// elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
// http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
var attributeNode = elem.getAttributeNode("tabindex");
return attributeNode && attributeNode.specified ?
parseInt( attributeNode.value, 10 ) :
rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
0 :
undefined;
}
}
}
});
// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional)
jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
coords: true
};
// Use this for any attribute in IE6/7
// This fixes almost every IE6/7 issue
nodeHook = jQuery.valHooks.button = {
get: function( elem, name ) {
var ret;
ret = elem.getAttributeNode( name );
return ret && ( fixSpecified[ name ] ? ret.nodeValue !== "" : ret.specified ) ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.nodeValue = value + "" );
}
};
// Apply the nodeHook to tabindex
jQuery.attrHooks.tabindex.set = nodeHook.set;
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = "" + value );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
rhoverHack = /(?:^|\s)hover(\.\S+)?\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,
quickParse = function( selector ) {
var quick = rquickIs.exec( selector );
if ( quick ) {
// 0 1 2 3
// [ _, tag, id, class ]
quick[1] = ( quick[1] || "" ).toLowerCase();
quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" );
}
return quick;
},
quickIs = function( elem, m ) {
var attrs = elem.attributes || {};
return (
(!m[1] || elem.nodeName.toLowerCase() === m[1]) &&
(!m[2] || (attrs.id || {}).value === m[2]) &&
(!m[3] || m[3].test( (attrs[ "class" ] || {}).value ))
);
},
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, quick, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
events = elemData.events;
if ( !events ) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if ( !eventHandle ) {
elemData.handle = eventHandle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ?
jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
undefined;
};
// Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
eventHandle.elem = elem;
}
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = jQuery.trim( hoverHack(types) ).split( " " );
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = tns[1];
namespaces = ( tns[2] || "" ).split( "." ).sort();
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
quick: selector && quickParse( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
t, tns, type, origType, namespaces, origCount,
j, events, special, handle, eventType, handleObj;
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, [ "events", "handle" ], true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var type = event.type || event,
namespaces = [],
cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
old = null;
for ( ; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old && old === elem.ownerDocument ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = [].slice.call( arguments, 0 ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [],
i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers that should run if there are delegated events
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {
// Pregenerate a single jQuery object for reuse with .is()
jqcur = jQuery(this);
jqcur.context = this.ownerDocument || this;
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process events on disabled elements (#6911, #8165)
if ( cur.disabled !== true ) {
selMatch = {};
matches = [];
jqcur[0] = cur;
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = (
handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
);
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
// Includes some event props shared by KeyEvent and MouseEvent
// *** attrChange attrName relatedNode srcElement are not normalized, non-W3C, deprecated, will be removed in 1.8 ***
props: "attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button,
fromElement = original.fromElement;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add relatedTarget, if necessary
if ( !event.relatedTarget && fromElement ) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop,
originalEvent = event,
fixHook = jQuery.event.fixHooks[ event.type ] || {},
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = jQuery.Event( originalEvent );
for ( i = copy.length; i; ) {
prop = copy[ --i ];
event[ prop ] = originalEvent[ prop ];
}
// Fix target property, if necessary (#1925, IE 6/7/8 & Safari2)
if ( !event.target ) {
event.target = originalEvent.srcElement || document;
}
// Target should not be a text node (#504, Safari)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
// For mouse/key events; add metaKey if it's not there (#3368, IE6/7/8)
if ( event.metaKey === undefined ) {
event.metaKey = event.ctrlKey;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady
},
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector,
ret;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !form._submit_attached ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
form._submit_attached = true;
}
});
// return undefined since we don't need an event listener
},
postDispatch: function( event ) {
// If form was submitted by the user, bubble the event up the tree
if ( event._submit_bubble ) {
delete event._submit_bubble;
if ( this.parentNode && !event.isTrigger ) {
jQuery.event.simulate( "submit", this.parentNode, event, true );
}
}
},
teardown: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Remove delegated handlers; cleanData eventually reaps submit handlers attached above
jQuery.event.remove( this, "._submit" );
}
};
}
// IE change delegation and checkbox/radio fix
if ( !jQuery.support.changeBubbles ) {
jQuery.event.special.change = {
setup: function() {
if ( rformElems.test( this.nodeName ) ) {
// IE doesn't fire change on a check/radio until blur; trigger it on click
// after a propertychange. Eat the blur-change in special.change.handle.
// This still fires onchange a second time for check/radio after blur.
if ( this.type === "checkbox" || this.type === "radio" ) {
jQuery.event.add( this, "propertychange._change", function( event ) {
if ( event.originalEvent.propertyName === "checked" ) {
this._just_changed = true;
}
});
jQuery.event.add( this, "click._change", function( event ) {
if ( this._just_changed && !event.isTrigger ) {
this._just_changed = false;
jQuery.event.simulate( "change", this, event, true );
}
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
elem._change_attached = true;
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && selector != null
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
var handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( var type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 2011, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
expando = "sizcache" + (Math.random() + '').replace('.', ''),
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
rBackslash = /\\/g,
rReturn = /\r\n/g,
rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context, seed );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set, seed );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set, i, len, match, type, left;
if ( !expr ) {
return [];
}
for ( i = 0, len = Expr.order.length; i < len; i++ ) {
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
type, found, item, filter, left,
i, pass,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
filter = Expr.filter[ type ];
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
pass = not ^ found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Utility function for retreiving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
var getText = Sizzle.getText = function( elem ) {
var i, node,
nodeType = elem.nodeType,
ret = "";
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent || innerText for elements
if ( typeof elem.textContent === 'string' ) {
return elem.textContent;
} else if ( typeof elem.innerText === 'string' ) {
// Replace IE's carriage returns
return elem.innerText.replace( rReturn, '' );
} else {
// Traverse it's children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
} else {
// If no nodeType, this is expected to be an array
for ( i = 0; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
if ( node.nodeType !== 8 ) {
ret += getText( node );
}
}
}
return ret;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !rNonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( match[1] );
}
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace( rBackslash, "" ) + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rBackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rBackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace(/^\+|\s*/g, '');
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1] = match[1].replace( rBackslash, "" );
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
},
focus: function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var first, last,
doneName, parent, cache,
count, diff,
type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
first = match[2];
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
doneName = match[0];
parent = elem.parentNode;
if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent[ expando ] = doneName;
}
diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Sizzle.attr ?
Sizzle.attr( elem, name ) :
Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
!type && Sizzle.attr ?
result != null :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
// Expose origPOS
// "global" as in regardless of relation to brackets/parens
Expr.match.globalPOS = origPOS;
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
if ( matches ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9 fails this)
var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
var ret = matches.call( node, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || !disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9, so check for that
node.document && node.document.nodeType !== 11 ) {
return ret;
}
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context, seed ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet, seed );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
Sizzle.selectors.attrMap = {};
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.globalPOS,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ),
length, n, r;
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
POS.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
// Array (deprecated as of jQuery 1.7)
if ( jQuery.isArray( selectors ) ) {
var level = 1;
while ( cur && cur.ownerDocument && cur !== context ) {
for ( i = 0; i < selectors.length; i++ ) {
if ( jQuery( cur ).is( selectors[ i ] ) ) {
ret.push({ selector: selectors[ i ], elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
return ret;
}
// String
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
nth: function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( value ) {
return jQuery.access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
}, null, value, arguments.length );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function(i) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery.clean( arguments );
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery.clean(arguments) );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return jQuery.access( this, function( value ) {
var elem = this[0] || {},
i = 0,
l = this.length;
if ( value === undefined ) {
return elem.nodeType === 1 ?
elem.innerHTML.replace( rinlinejQuery, "" ) :
null;
}
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; i < l; i++ ) {
// Remove element nodes and prevent memory leaks
elem = this[i] || {};
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName( "*" ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch(e) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function( value ) {
if ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || ( l > 1 && i < lastIndex ) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
type: "GET",
global: false,
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML;
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// IE blanks contents when cloning scripts
} else if ( nodeName === "script" && dest.text !== src.text ) {
dest.text = src.text;
}
// Event data gets referenced instead of copied if the expando
// gets copied too
dest.removeAttribute( jQuery.expando );
// Clear flags for bubbling special change/submit events, they must
// be reattached when the newly cloned events are first activated
dest.removeAttribute( "_submit_attached" );
dest.removeAttribute( "_change_attached" );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, doc,
first = args[ 0 ];
// nodes may contain either an explicit document object,
// a jQuery collection or context object.
// If nodes[0] contains a valid object to assign to doc
if ( nodes && nodes[0] ) {
doc = nodes[0].ownerDocument || nodes[0];
}
// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if ( !doc.createDocumentFragment ) {
doc = document;
}
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ first ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ first ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "input" ) {
fixDefaultChecked( elem );
// Skip scripts, get other children
} else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
// Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js
function shimCloneNode( elem ) {
var div = document.createElement( "div" );
safeFragment.appendChild( div );
div.innerHTML = elem.outerHTML;
return div.firstChild;
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
// IE<=8 does not properly clone detached, unknown element nodes
clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ?
elem.cloneNode( true ) :
shimCloneNode( elem );
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var checkScriptType, script, j,
ret = [];
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div"),
safeChildNodes = safeFragment.childNodes,
remove;
// Append wrapper element to unknown element safe doc fragment
if ( context === document ) {
// Use the fragment we've already created for this document
safeFragment.appendChild( div );
} else {
// Use a fragment created with the owner document
createSafeFragment( context ).appendChild( div );
}
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Clear elements from DocumentFragment (safeFragment or otherwise)
// to avoid hoarding elements. Fixes #11356
if ( div ) {
div.parentNode.removeChild( div );
// Guard against -1 index exceptions in FF3.6
if ( safeChildNodes.length > 0 ) {
remove = safeChildNodes[ safeChildNodes.length - 1 ];
if ( remove && remove.parentNode ) {
remove.parentNode.removeChild( remove );
}
}
}
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
script = ret[i];
if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) {
scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script );
} else {
if ( script.nodeType === 1 ) {
var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( script );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id,
cache = jQuery.cache,
special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnum = /^[\-+]?(?:\d*\.)?\d+$/i,
rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,
rrelNum = /^([\-+])=([\-+.\de]+)/,
rmargin = /^margin/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
// order is important!
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
curCSS,
getComputedStyle,
currentStyle;
jQuery.fn.css = function( name, value ) {
return jQuery.access( this, function( elem, name, value ) {
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
};
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {},
ret, name;
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.call( elem );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
}
});
// DEPRECATED in 1.3, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle, width,
style = elem.style;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( (defaultView = elem.ownerDocument.defaultView) &&
(computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
// A tribute to the "awesome hack by Dean Edwards"
// WebKit uses "computed value (percentage if specified)" instead of "used value" for margins
// which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) {
width = style.width;
style.width = ret;
ret = computedStyle.width;
style.width = width;
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, rsLeft, uncomputed,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && (uncomputed = style[ name ]) ) {
ret = uncomputed;
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( rnumnonpx.test( ret ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
if ( rsLeft ) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
curCSS = getComputedStyle || currentStyle;
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
i = name === "width" ? 1 : 0,
len = 4;
if ( val > 0 ) {
if ( extra !== "border" ) {
for ( ; i < len; i += 2 ) {
if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0;
} else {
val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val + "px";
}
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
for ( ; i < len; i += 2 ) {
val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0;
}
}
}
return val + "px";
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
return getWidthOrHeight( elem, name, extra );
} else {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
}
}
},
set: function( elem, value ) {
return rnum.test( value ) ?
value + "px" :
value;
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( parseFloat( RegExp.$1 ) / 100 ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery(function() {
// This hook cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "margin-right" );
} else {
return elem.style.marginRight;
}
});
}
};
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i,
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ],
expanded = {};
for ( i = 0; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts,
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
var isSuccess,
success,
error,
statusText = nativeStatusText,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = "" + ( nativeStatusText || statusText );
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for ( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for ( key in s.converters ) {
if ( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if ( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for ( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType );
if ( s.dataTypes[ 0 ] === "jsonp" ||
s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2";
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( inspectData ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Clean-up function
jqXHR.always(function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0,
xhrCallbacks;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( _ ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
],
fxNow;
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback );
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( (display === "" && jQuery.css(elem, "display") === "none") ||
!jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data( elem, "olddisplay" ) || "";
}
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
var elem, display,
i = 0,
j = this.length;
for ( ; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = jQuery.css( elem, "display" );
if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none";
}
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed( speed, easing, callback );
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
function doAnimation() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p, e, hooks, replace,
parts, start, end, unit,
method;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
// first pass over propertys to expand / normalize
for ( p in prop ) {
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) {
replace = hooks.expand( prop[ name ] );
delete prop[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'p' from above because we have the correct "name"
for ( p in replace ) {
if ( ! ( p in prop ) ) {
prop[ p ] = replace[ p ];
}
}
}
}
for ( name in prop ) {
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.zoom = 1;
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test( val ) ) {
// Tracks whether to show or hide based on private
// data attached to the element
method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 );
if ( method ) {
jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" );
e[ method ]();
} else {
e[ val ]();
}
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ( (end || 1) / e.cur() ) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
}
return optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var index,
hadTimers = false,
timers = jQuery.timers,
data = jQuery._data( this );
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
function stopQueue( elem, data, index ) {
var hooks = data[ index ];
jQuery.removeData( elem, index, true );
hooks.stop( gotoEnd );
}
if ( type == null ) {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) {
stopQueue( this, data, index );
}
}
} else if ( data[ index = type + ".run" ] && data[ index ].stop ){
stopQueue( this, data, index );
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
if ( gotoEnd ) {
// force the next step to be the last
timers[ index ]( true );
} else {
timers[ index ].saveState();
}
hadTimers = true;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( !( gotoEnd && hadTimers ) ) {
jQuery.dequeue( this, type );
}
});
}
});
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout( clearFxNow, 0 );
return ( fxNow = jQuery.now() );
}
function clearFxNow() {
fxNow = undefined;
}
// Generate parameters to create a standard animation
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx( "show", 1 ),
slideUp: genFx( "hide", 1 ),
slideToggle: genFx( "toggle", 1 ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.extend({
speed: function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function( noUnmark ) {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
};
return opt;
},
easing: {
linear: function( p ) {
return p;
},
swing: function( p ) {
return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this );
},
// Get the current size
cur: function() {
if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) {
return this.elem[ this.prop ];
}
var parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
this.startTime = fxNow || createFxNow();
this.end = to;
this.now = this.start = from;
this.pos = this.state = 0;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
function t( gotoEnd ) {
return self.step( gotoEnd );
}
t.queue = this.options.queue;
t.elem = this.elem;
t.saveState = function() {
if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
if ( self.options.hide ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.start );
} else if ( self.options.show ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.end );
}
}
};
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval( fx.tick, fx.interval );
}
},
// Simple 'show' function
show: function() {
var dataShow = jQuery._data( this.elem, "fxshow" + this.prop );
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any flash of content
if ( dataShow !== undefined ) {
// This show is picking up where a previous hide or show left off
this.custom( this.cur(), dataShow );
} else {
this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() );
}
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom( this.cur(), 0 );
},
// Each step of an animation
step: function( gotoEnd ) {
var p, n, complete,
t = fxNow || createFxNow(),
done = true,
elem = this.elem,
options = this.options;
if ( gotoEnd || t >= options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
options.animatedProperties[ this.prop ] = true;
for ( p in options.animatedProperties ) {
if ( options.animatedProperties[ p ] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
jQuery.each( [ "", "X", "Y" ], function( index, value ) {
elem.style[ "overflow" + value ] = options.overflow[ index ];
});
}
// Hide the element if the "hide" operation was done
if ( options.hide ) {
jQuery( elem ).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show ) {
for ( p in options.animatedProperties ) {
jQuery.style( elem, p, options.orig[ p ] );
jQuery.removeData( elem, "fxshow" + p, true );
// Toggle data is no longer needed
jQuery.removeData( elem, "toggle" + p, true );
}
}
// Execute the complete function
// in the event that the complete function throws an exception
// we must ensure it won't be called twice. #5684
complete = options.complete;
if ( complete ) {
options.complete = false;
complete.call( elem );
}
}
return false;
} else {
// classical easing cannot be used with an Infinity duration
if ( options.duration == Infinity ) {
this.now = t;
} else {
n = t - this.startTime;
this.state = n / options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration );
this.now = this.start + ( (this.end - this.start) * this.pos );
}
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
var timer,
timers = jQuery.timers,
i = 0;
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
// Ensure props that can't be negative don't go there on undershoot easing
jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) {
// exclude marginTop, marginLeft, marginBottom and marginRight from this list
if ( prop.indexOf( "margin" ) ) {
jQuery.fx.step[ prop ] = function( fx ) {
jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
};
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var body = document.body,
elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
display = elem.css( "display" );
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// No iframe to use yet, so create it
if ( !iframe ) {
iframe = document.createElement( "iframe" );
iframe.frameBorder = iframe.width = iframe.height = 0;
}
body.appendChild( iframe );
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" );
iframeDoc.close();
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var getOffset,
rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
getOffset = function( elem, doc, docElem, box ) {
try {
box = elem.getBoundingClientRect();
} catch(e) {}
// Make sure we're not dealing with a disconnected DOM node
if ( !box || !jQuery.contains( docElem, elem ) ) {
return box ? { top: box.top, left: box.left } : { top: 0, left: 0 };
}
var body = doc.body,
win = getWindow( doc ),
clientTop = docElem.clientTop || body.clientTop || 0,
clientLeft = docElem.clientLeft || body.clientLeft || 0,
scrollTop = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop,
scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
top = box.top + scrollTop - clientTop,
left = box.left + scrollLeft - clientLeft;
return { top: top, left: left };
};
} else {
getOffset = function( elem, doc, docElem ) {
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var elem = this[0],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return null;
}
if ( elem === doc.body ) {
return jQuery.offset.bodyOffset( elem );
}
return getOffset( elem, doc, doc.documentElement );
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) {
var top = /Y/.test( prop );
jQuery.fn[ method ] = function( val ) {
return jQuery.access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? (prop in win) ? win[ prop ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ method ] :
elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : jQuery( win ).scrollLeft(),
top ? val : jQuery( win ).scrollTop()
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
function getWindow( elem ) {
return jQuery.isWindow( elem ) ?
elem :
elem.nodeType === 9 ?
elem.defaultView || elem.parentWindow :
false;
}
// Create width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
var clientProp = "client" + name,
scrollProp = "scroll" + name,
offsetProp = "offset" + name;
// innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, "padding" ) ) :
this[ type ]() :
null;
};
// outerHeight and outerWidth
jQuery.fn[ "outer" + name ] = function( margin ) {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
this[ type ]() :
null;
};
jQuery.fn[ type ] = function( value ) {
return jQuery.access( this, function( elem, type, value ) {
var doc, docElemProp, orig, ret;
if ( jQuery.isWindow( elem ) ) {
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
doc = elem.document;
docElemProp = doc.documentElement[ clientProp ];
return jQuery.support.boxModel && docElemProp ||
doc.body && doc.body[ clientProp ] || docElemProp;
}
// Get document width or height
if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
doc = elem.documentElement;
// when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height]
// so we can't use max, as it'll choose the incorrect offset[Width/Height]
// instead we use the correct client[Width/Height]
// support:IE6
if ( doc[ clientProp ] >= doc[ scrollProp ] ) {
return doc[ clientProp ];
}
return Math.max(
elem.body[ scrollProp ], doc[ scrollProp ],
elem.body[ offsetProp ], doc[ offsetProp ]
);
}
// Get width or height on the element
if ( value === undefined ) {
orig = jQuery.css( elem, type );
ret = parseFloat( orig );
return jQuery.isNumeric( ret ) ? ret : orig;
}
// Set the width or height on the element
jQuery( elem ).css( type, value );
}, type, value, arguments.length, null );
};
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
// Expose jQuery as an AMD module, but only for AMD loaders that
// understand the issues with loading multiple versions of jQuery
// in a page that all might call define(). The loader will indicate
// they have special allowances for multiple jQuery versions by
// specifying define.amd.jQuery = true. Register as a named module,
// since jQuery can be concatenated with other files that may use define,
// but not use a proper concatenation script that understands anonymous
// AMD modules. A named AMD is safest and most robust way to register.
// Lowercase jquery is used because AMD module names are derived from
// file names, and jQuery is normally delivered in a lowercase file name.
// Do this after creating the global so that if an AMD module wants to call
// noConflict to hide this version of jQuery, it will work.
if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
define( "jquery", [], function () { return jQuery; } );
}
})( window );
/**
* @license AngularJS v1.0.7
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document){
var _jQuery = window.jQuery.noConflict(true);
////////////////////////////////////
/**
* @ngdoc function
* @name angular.lowercase
* @function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
/**
* @ngdoc function
* @name angular.uppercase
* @function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
var manualLowercase = function(s) {
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
: s;
};
var manualUppercase = function(s) {
return isString(s)
? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
: s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
lowercase = manualLowercase;
uppercase = manualUppercase;
}
var /** holds major version number for IE or NaN for real browsers */
msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]),
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
push = [].push,
toString = Object.prototype.toString,
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
nodeName_,
uid = ['0', '0', '0'];
/**
* @private
* @param {*} obj
* @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments, ...)
*/
function isArrayLike(obj) {
if (!obj || (typeof obj.length !== 'number')) return false;
// We have on object which has length property. Should we treat it as array?
if (typeof obj.hasOwnProperty != 'function' &&
typeof obj.constructor != 'function') {
// This is here for IE8: it is a bogus object treat it as array;
return true;
} else {
return obj instanceof JQLite || // JQLite
(jQuery && obj instanceof jQuery) || // jQuery
toString.call(obj) !== '[object Object]' || // some browser native object
typeof obj.callee === 'function'; // arguments (on IE8 looks like regular obj)
}
}
/**
* @ngdoc function
* @name angular.forEach
* @function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
* is the value of an object property or an array element and `key` is the object property key or
* array element index. Specifying a `context` for the function is optional.
*
* Note: this function was previously known as `angular.foreach`.
*
<pre>
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key){
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender:male']);
</pre>
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key;
if (obj) {
if (isFunction(obj)){
for (key in obj) {
if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context);
} else if (isArrayLike(obj)) {
for (key = 0; key < obj.length; key++)
iterator.call(context, obj[key], key);
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
}
}
return obj;
}
function sortedKeys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys.sort();
}
function forEachSorted(obj, iterator, context) {
var keys = sortedKeys(obj);
for ( var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) { iteratorFn(key, value) };
}
/**
* A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
* characters such as '012ABC'. The reason why we are not using simply a number counter is that
* the number string gets longer over time, and it can also overflow, where as the nextId
* will grow much slower, it is a string, and it will never overflow.
*
* @returns an unique alpha-numeric string
*/
function nextUid() {
var index = uid.length;
var digit;
while(index) {
index--;
digit = uid[index].charCodeAt(0);
if (digit == 57 /*'9'*/) {
uid[index] = 'A';
return uid.join('');
}
if (digit == 90 /*'Z'*/) {
uid[index] = '0';
} else {
uid[index] = String.fromCharCode(digit + 1);
return uid.join('');
}
}
uid.unshift('0');
return uid.join('');
}
/**
* Set or clear the hashkey for an object.
* @param obj object
* @param h the hashkey (!truthy to delete the hashkey)
*/
function setHashKey(obj, h) {
if (h) {
obj.$$hashKey = h;
}
else {
delete obj.$$hashKey;
}
}
/**
* @ngdoc function
* @name angular.extend
* @function
*
* @description
* Extends the destination object `dst` by copying all of the properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*/
function extend(dst) {
var h = dst.$$hashKey;
forEach(arguments, function(obj){
if (obj !== dst) {
forEach(obj, function(value, key){
dst[key] = value;
});
}
});
setHashKey(dst,h);
return dst;
}
function int(str) {
return parseInt(str, 10);
}
function inherit(parent, extra) {
return extend(new (extend(function() {}, {prototype:parent}))(), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
<pre>
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
</pre>
*/
function noop() {}
noop.$inject = [];
/**
* @ngdoc function
* @name angular.identity
* @function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
<pre>
function transformer(transformationFn, value) {
return (transformationFn || identity)(value);
};
</pre>
*/
function identity($) {return $;}
identity.$inject = [];
function valueFn(value) {return function() {return value;};}
/**
* @ngdoc function
* @name angular.isUndefined
* @function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value){return typeof value == 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value){return typeof value != 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value){return value != null && typeof value == 'object';}
/**
* @ngdoc function
* @name angular.isString
* @function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value){return typeof value == 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @function
*
* @description
* Determines if a reference is a `Number`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value){return typeof value == 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value){
return toString.apply(value) == '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
function isArray(value) {
return toString.apply(value) == '[object Array]';
}
/**
* @ngdoc function
* @name angular.isFunction
* @function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value){return typeof value == 'function';}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.document && obj.location && obj.alert && obj.setInterval;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.apply(obj) === '[object File]';
}
function isBoolean(value) {
return typeof value == 'boolean';
}
function trim(value) {
return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
}
/**
* @ngdoc function
* @name angular.isElement
* @function
*
* @description
* Determines if a reference is a DOM element (or wrapped jQuery element).
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
*/
function isElement(node) {
return node &&
(node.nodeName // we are a direct element
|| (node.bind && node.find)); // we have a bind and find method part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str){
var obj = {}, items = str.split(","), i;
for ( i = 0; i < items.length; i++ )
obj[ items[i] ] = true;
return obj;
}
if (msie < 9) {
nodeName_ = function(element) {
element = element.nodeName ? element : element[0];
return (element.scopeName && element.scopeName != 'HTML')
? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
};
} else {
nodeName_ = function(element) {
return element.nodeName ? element.nodeName : element[0].nodeName;
};
}
function map(obj, iterator, context) {
var results = [];
forEach(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
}
/**
* @description
* Determines the number of elements in an array, the number of properties an object has, or
* the length of a string.
*
* Note: This function is used to augment the Object type in Angular expressions. See
* {@link angular.Object} for more information about Angular arrays.
*
* @param {Object|Array|string} obj Object, array, or string to inspect.
* @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
* @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
*/
function size(obj, ownPropsOnly) {
var size = 0, key;
if (isArray(obj) || isString(obj)) {
return obj.length;
} else if (isObject(obj)){
for (key in obj)
if (!ownPropsOnly || obj.hasOwnProperty(key))
size++;
}
return size;
}
function includes(array, obj) {
return indexOf(array, obj) != -1;
}
function indexOf(array, obj) {
if (array.indexOf) return array.indexOf(obj);
for ( var i = 0; i < array.length; i++) {
if (obj === array[i]) return i;
}
return -1;
}
function arrayRemove(array, value) {
var index = indexOf(array, value);
if (index >=0)
array.splice(index, 1);
return value;
}
function isLeafNode (node) {
if (node) {
switch (node.nodeName) {
case "OPTION":
case "PRE":
case "TITLE":
return true;
}
}
return false;
}
/**
* @ngdoc function
* @name angular.copy
* @function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for array) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array, `source` is returned.
*
* Note: this function is used to augment the Object type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*/
function copy(source, destination){
if (isWindow(source) || isScope(source)) throw Error("Can't copy Window or Scope");
if (!destination) {
destination = source;
if (source) {
if (isArray(source)) {
destination = copy(source, []);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isObject(source)) {
destination = copy(source, {});
}
}
} else {
if (source === destination) throw Error("Can't copy equivalent objects or arrays");
if (isArray(source)) {
destination.length = 0;
for ( var i = 0; i < source.length; i++) {
destination.push(copy(source[i]));
}
} else {
var h = destination.$$hashKey;
forEach(destination, function(value, key){
delete destination[key];
});
for ( var key in source) {
destination[key] = copy(source[key]);
}
setHashKey(destination,h);
}
}
return destination;
}
/**
* Create a shallow copy of an object
*/
function shallowCopy(src, dst) {
dst = dst || {};
for(var key in src) {
if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
dst[key] = src[key];
}
}
return dst;
}
/**
* @ngdoc function
* @name angular.equals
* @function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, arrays and
* objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties pass `===` comparison.
* * Both values are NaN. (In JavasScript, NaN == NaN => false. But we consider two NaN as equal)
*
* During a property comparision, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only by identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if ((length = o1.length) == o2.length) {
for(key=0; key<length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
return isDate(o2) && o1.getTime() == o2.getTime();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2)) return false;
keySet = {};
for(key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
if (!equals(o1[key], o2[key])) return false;
keySet[key] = true;
}
for(key in o2) {
if (!keySet[key] &&
key.charAt(0) !== '$' &&
o2[key] !== undefined &&
!isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/**
* @ngdoc function
* @name angular.bind
* @function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are prebound to the function. This feature is also
* known as [function currying](http://en.wikipedia.org/wiki/Currying).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
return fn;
}
}
function toJsonReplacer(key, value) {
var val = value;
if (/^\$+/.test(key)) {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @function
*
* @description
* Serializes input into a JSON-formatted string.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
* @returns {string} Jsonified string representing `obj`.
*/
function toJson(obj, pretty) {
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
/**
* @ngdoc function
* @name angular.fromJson
* @function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|Date|string|number} Deserialized thingy.
*/
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
function toBoolean(value) {
if (value && value.length !== 0) {
var v = lowercase("" + value);
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
} else {
value = false;
}
return value;
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element = jqLite(element).clone();
try {
// turns out IE does not let you set .html() on elements which
// are not allowed to have children. So we just ignore it.
element.html('');
} catch(e) {}
// As Per DOM Standards
var TEXT_NODE = 3;
var elemHtml = jqLite('<div>').append(element).html();
try {
return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
elemHtml.
match(/^(<[^>]+>)/)[1].
replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
} catch(e) {
return lowercase(elemHtml);
}
}
/////////////////////////////////////////////////
/**
* Parses an escaped url query string into key-value pairs.
* @returns Object.<(string|boolean)>
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue){
if (keyValue) {
key_value = keyValue.split('=');
key = decodeURIComponent(key_value[0]);
obj[key] = isDefined(key_value[1]) ? decodeURIComponent(key_value[1]) : true;
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
parts.push(encodeUriQuery(key, true) + (value === true ? '' : '=' + encodeUriQuery(value, true)));
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom method because encodeURIComponent is too agressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method becuase encodeURIComponent is too agressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
/**
* @ngdoc directive
* @name ng.directive:ngApp
*
* @element ANY
* @param {angular.Module} ngApp an optional application
* {@link angular.module module} name to load.
*
* @description
*
* Use this directive to auto-bootstrap an application. Only
* one directive can be used per HTML document. The directive
* designates the root of the application and is typically placed
* at the root of the page.
*
* In the example below if the `ngApp` directive would not be placed
* on the `html` element then the document would not be compiled
* and the `{{ 1+2 }}` would not be resolved to `3`.
*
* `ngApp` is the easiest way to bootstrap an application.
*
<doc:example>
<doc:source>
I can add: 1 + 2 = {{ 1+2 }}
</doc:source>
</doc:example>
*
*/
function angularInit(element, bootstrap) {
var elements = [element],
appElement,
module,
names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
function append(element) {
element && elements.push(element);
}
forEach(names, function(name) {
names[name] = true;
append(document.getElementById(name));
name = name.replace(':', '\\:');
if (element.querySelectorAll) {
forEach(element.querySelectorAll('.' + name), append);
forEach(element.querySelectorAll('.' + name + '\\:'), append);
forEach(element.querySelectorAll('[' + name + ']'), append);
}
});
forEach(elements, function(element) {
if (!appElement) {
var className = ' ' + element.className + ' ';
var match = NG_APP_CLASS_REGEXP.exec(className);
if (match) {
appElement = element;
module = (match[2] || '').replace(/\s+/g, ',');
} else {
forEach(element.attributes, function(attr) {
if (!appElement && names[attr.name]) {
appElement = element;
module = attr.value;
}
});
}
}
});
if (appElement) {
bootstrap(appElement, module ? [module] : []);
}
}
/**
* @ngdoc function
* @name angular.bootstrap
* @description
* Use this function to manually start up angular application.
*
* See: {@link guide/bootstrap Bootstrap}
*
* @param {Element} element DOM element which is the root of angular application.
* @param {Array<String|Function>=} modules an array of module declarations. See: {@link angular.module modules}
* @returns {AUTO.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules) {
var resumeBootstrapInternal = function() {
element = jqLite(element);
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
modules.unshift('ng');
var injector = createInjector(modules);
injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
function(scope, element, compile, injector) {
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}]
);
return injector;
};
var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
return resumeBootstrapInternal();
}
window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
angular.resumeBootstrap = function(extraModules) {
forEach(extraModules, function(module) {
modules.push(module);
});
resumeBootstrapInternal();
};
}
var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator){
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
function bindJQuery() {
// bind to jQuery if present;
jQuery = window.jQuery;
// reset to jQuery or default to us.
if (jQuery) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
JQLitePatchJQueryRemove('remove', true);
JQLitePatchJQueryRemove('empty');
JQLitePatchJQueryRemove('html');
} else {
jqLite = JQLite;
}
angular.element = jqLite;
}
/**
* throw error if the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw new Error("Argument '" + (name || '?') + "' is " + (reason || "required"));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
return arg;
}
/**
* @ngdoc interface
* @name angular.Module
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
return ensure(ensure(window, 'angular', Object), 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @description
*
* The `angular.module` is a global place for creating and registering Angular modules. All
* modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
*
* # Module
*
* A module is a collocation of services, directives, filters, and configuration information. Module
* is used to configure the {@link AUTO.$injector $injector}.
*
* <pre>
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* });
* </pre>
*
* Then you can create an injector and load your modules like this:
*
* <pre>
* var injector = angular.injector(['ng', 'MyModule'])
* </pre>
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {Array.<string>=} requires If specified then new module is being created. If unspecified then the
* the module is being retrieved for further configuration.
* @param {Function} configFn Optional configuration function for the module. Same as
* {@link angular.Module#config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw Error('No module: ' + name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke');
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @propertyOf angular.Module
* @returns {Array.<string>} List of module names which must be loaded before this module.
* @description
* Holds the list of modules which the injector will load before the current module is loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @propertyOf angular.Module
* @returns {string} Name of the module.
* @description
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#provider $provide.provider()}.
*/
provider: invokeLater('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#factory $provide.factory()}.
*/
factory: invokeLater('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link AUTO.$provide#service $provide.service()}.
*/
service: invokeLater('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @methodOf angular.Module
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link AUTO.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @methodOf angular.Module
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other provide methods.
* See {@link AUTO.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#filter
* @methodOf angular.Module
* @param {string} name Filter name.
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*/
filter: invokeLater('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @methodOf angular.Module
* @param {string} name Controller name.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLater('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @methodOf angular.Module
* @param {string} name directive name
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#directive $compileProvider.directive()}.
*/
directive: invokeLater('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @methodOf angular.Module
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @methodOf angular.Module
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod) {
return function() {
invokeQueue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
}
}
});
};
});
}
/**
* @ngdoc property
* @name angular.version
* @description
* An object that contains information about the current AngularJS version. This object has the
* following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
full: '1.0.7', // all of these placeholder strings will be replaced by grunt's
major: 1, // package task
minor: 0,
dot: 7,
codeName: 'monochromatic-rainbow'
};
function publishExternalAPI(angular){
extend(angular, {
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop':noop,
'bind':bind,
'toJson': toJson,
'fromJson': fromJson,
'identity':identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'version': version,
'isDate': isDate,
'lowercase': lowercase,
'uppercase': uppercase,
'callbacks': {counter: 0}
});
angularModule = setupModuleLoader(window);
try {
angularModule('ngLocale');
} catch (e) {
angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
}
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
style: styleDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtmlUnsafe: ngBindHtmlUnsafeDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCsp: ngCspDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngSubmit: ngSubmitDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngView: ngViewDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
required: requiredDirective,
ngRequired: requiredDirective,
ngValue: ngValueDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$interpolate: $InterpolateProvider,
$http: $HttpProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$route: $RouteProvider,
$routeParams: $RouteParamsProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider
});
}
]);
}
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
* `angular.element` can be either an alias for [jQuery](http://api.jquery.com/jQuery/) function, if
* jQuery is available, or a function that wraps the element or string in Angular's jQuery lite
* implementation (commonly referred to as jqLite).
*
* Real jQuery always takes precedence over jqLite, provided it was loaded before `DOMContentLoaded`
* event fired.
*
* jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM. jqLite implements only the most commonly needed functionality
* within a very small footprint, so only a subset of the jQuery API - methods, arguments and
* invocation styles - are supported.
*
* Note: All element references in Angular are always wrapped with jQuery or jqLite; they are never
* raw DOM references.
*
* ## Angular's jQuery lite provides the following methods:
*
* - [addClass()](http://api.jquery.com/addClass/)
* - [after()](http://api.jquery.com/after/)
* - [append()](http://api.jquery.com/append/)
* - [attr()](http://api.jquery.com/attr/)
* - [bind()](http://api.jquery.com/bind/) - Does not support namespaces
* - [children()](http://api.jquery.com/children/) - Does not support selectors
* - [clone()](http://api.jquery.com/clone/)
* - [contents()](http://api.jquery.com/contents/)
* - [css()](http://api.jquery.com/css/)
* - [data()](http://api.jquery.com/data/)
* - [eq()](http://api.jquery.com/eq/)
* - [find()](http://api.jquery.com/find/) - Limited to lookups by tag name
* - [hasClass()](http://api.jquery.com/hasClass/)
* - [html()](http://api.jquery.com/html/)
* - [next()](http://api.jquery.com/next/) - Does not support selectors
* - [parent()](http://api.jquery.com/parent/) - Does not support selectors
* - [prepend()](http://api.jquery.com/prepend/)
* - [prop()](http://api.jquery.com/prop/)
* - [ready()](http://api.jquery.com/ready/)
* - [remove()](http://api.jquery.com/remove/)
* - [removeAttr()](http://api.jquery.com/removeAttr/)
* - [removeClass()](http://api.jquery.com/removeClass/)
* - [removeData()](http://api.jquery.com/removeData/)
* - [replaceWith()](http://api.jquery.com/replaceWith/)
* - [text()](http://api.jquery.com/text/)
* - [toggleClass()](http://api.jquery.com/toggleClass/)
* - [triggerHandler()](http://api.jquery.com/triggerHandler/) - Doesn't pass native event objects to handlers.
* - [unbind()](http://api.jquery.com/unbind/) - Does not support namespaces
* - [val()](http://api.jquery.com/val/)
* - [wrap()](http://api.jquery.com/wrap/)
*
* ## In addtion to the above, Angular provides additional methods to both jQuery and jQuery lite:
*
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
* element or its parent.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
var jqCache = JQLite.cache = {},
jqName = JQLite.expando = 'ng-' + new Date().getTime(),
jqId = 1,
addEventListenerFn = (window.document.addEventListener
? function(element, type, fn) {element.addEventListener(type, fn, false);}
: function(element, type, fn) {element.attachEvent('on' + type, fn);}),
removeEventListenerFn = (window.document.removeEventListener
? function(element, type, fn) {element.removeEventListener(type, fn, false); }
: function(element, type, fn) {element.detachEvent('on' + type, fn); });
function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
/////////////////////////////////////////////
// jQuery mutation patch
//
// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
// $destroy event on all DOM nodes being removed.
//
/////////////////////////////////////////////
function JQLitePatchJQueryRemove(name, dispatchThis) {
var originalJqFn = jQuery.fn[name];
originalJqFn = originalJqFn.$original || originalJqFn;
removePatch.$original = originalJqFn;
jQuery.fn[name] = removePatch;
function removePatch() {
var list = [this],
fireEvent = dispatchThis,
set, setIndex, setLength,
element, childIndex, childLength, children,
fns, events;
while(list.length) {
set = list.shift();
for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
element = jqLite(set[setIndex]);
if (fireEvent) {
element.triggerHandler('$destroy');
} else {
fireEvent = !fireEvent;
}
for(childIndex = 0, childLength = (children = element.children()).length;
childIndex < childLength;
childIndex++) {
list.push(jQuery(children[childIndex]));
}
}
}
return originalJqFn.apply(this, arguments);
}
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
if (!(this instanceof JQLite)) {
if (isString(element) && element.charAt(0) != '<') {
throw Error('selectors not implemented');
}
return new JQLite(element);
}
if (isString(element)) {
var div = document.createElement('div');
// Read about the NoScope elements here:
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
div.innerHTML = '<div> </div>' + element; // IE insanity to make NoScope elements work!
div.removeChild(div.firstChild); // remove the superfluous div
JQLiteAddNodes(this, div.childNodes);
this.remove(); // detach the elements from the temporary DOM div.
} else {
JQLiteAddNodes(this, element);
}
}
function JQLiteClone(element) {
return element.cloneNode(true);
}
function JQLiteDealoc(element){
JQLiteRemoveData(element);
for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
JQLiteDealoc(children[i]);
}
}
function JQLiteUnbind(element, type, fn) {
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!handle) return; //no listeners registered
if (isUndefined(type)) {
forEach(events, function(eventHandler, type) {
removeEventListenerFn(element, type, eventHandler);
delete events[type];
});
} else {
if (isUndefined(fn)) {
removeEventListenerFn(element, type, events[type]);
delete events[type];
} else {
arrayRemove(events[type], fn);
}
}
}
function JQLiteRemoveData(element) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId];
if (expandoStore) {
if (expandoStore.handle) {
expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
JQLiteUnbind(element);
}
delete jqCache[expandoId];
element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
}
}
function JQLiteExpandoStore(element, key, value) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId || -1];
if (isDefined(value)) {
if (!expandoStore) {
element[jqName] = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {};
}
expandoStore[key] = value;
} else {
return expandoStore && expandoStore[key];
}
}
function JQLiteData(element, key, value) {
var data = JQLiteExpandoStore(element, 'data'),
isSetter = isDefined(value),
keyDefined = !isSetter && isDefined(key),
isSimpleGetter = keyDefined && !isObject(key);
if (!data && !isSimpleGetter) {
JQLiteExpandoStore(element, 'data', data = {});
}
if (isSetter) {
data[key] = value;
} else {
if (keyDefined) {
if (isSimpleGetter) {
// don't create data in this case.
return data && data[key];
} else {
extend(data, key);
}
} else {
return data;
}
}
}
function JQLiteHasClass(element, selector) {
return ((" " + element.className + " ").replace(/[\n\t]/g, " ").
indexOf( " " + selector + " " ) > -1);
}
function JQLiteRemoveClass(element, cssClasses) {
if (cssClasses) {
forEach(cssClasses.split(' '), function(cssClass) {
element.className = trim(
(" " + element.className + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " ")
);
});
}
}
function JQLiteAddClass(element, cssClasses) {
if (cssClasses) {
forEach(cssClasses.split(' '), function(cssClass) {
if (!JQLiteHasClass(element, cssClass)) {
element.className = trim(element.className + ' ' + trim(cssClass));
}
});
}
}
function JQLiteAddNodes(root, elements) {
if (elements) {
elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
? elements
: [ elements ];
for(var i=0; i < elements.length; i++) {
root.push(elements[i]);
}
}
}
function JQLiteController(element, name) {
return JQLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
}
function JQLiteInheritedData(element, name, value) {
element = jqLite(element);
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if(element[0].nodeType == 9) {
element = element.find('html');
}
while (element.length) {
if (value = element.data(name)) return value;
element = element.parent();
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
this.bind('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
JQLite(window).bind('load', trigger); // fallback to window.onload for others
},
toString: function() {
var value = [];
forEach(this, function(e){ value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form'.split(','), function(value) {
BOOLEAN_ELEMENTS[uppercase(value)] = true;
});
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
}
forEach({
data: JQLiteData,
inheritedData: JQLiteInheritedData,
scope: function(element) {
return JQLiteInheritedData(element, '$scope');
},
controller: JQLiteController ,
injector: function(element) {
return JQLiteInheritedData(element, '$injector');
},
removeAttr: function(element,name) {
element.removeAttribute(name);
},
hasClass: JQLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
var val;
if (msie <= 8) {
// this is some IE specific weirdness that jQuery 1.6.4 does not sure why
val = element.currentStyle && element.currentStyle[name];
if (val === '') val = 'auto';
}
val = val || element.style[name];
if (msie <= 8) {
// jquery weirdness :-/
val = (val === '') ? undefined : val;
}
return val;
}
},
attr: function(element, name, value){
var lowercasedName = lowercase(name);
if (BOOLEAN_ATTR[lowercasedName]) {
if (isDefined(value)) {
if (!!value) {
element[name] = true;
element.setAttribute(name, lowercasedName);
} else {
element[name] = false;
element.removeAttribute(lowercasedName);
}
} else {
return (element[name] ||
(element.attributes.getNamedItem(name)|| noop).specified)
? lowercasedName
: undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
// some elements (e.g. Document) don't have get attribute, so return undefined
var ret = element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: extend((msie < 9)
? function(element, value) {
if (element.nodeType == 1 /** Element */) {
if (isUndefined(value))
return element.innerText;
element.innerText = value;
} else {
if (isUndefined(value))
return element.nodeValue;
element.nodeValue = value;
}
}
: function(element, value) {
if (isUndefined(value)) {
return element.textContent;
}
element.textContent = value;
}, {$dv:''}),
val: function(element, value) {
if (isUndefined(value)) {
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
JQLiteDealoc(childNodes[i]);
}
element.innerHTML = value;
}
}, function(fn, name){
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
// JQLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
if (((fn.length == 2 && (fn !== JQLiteHasClass && fn !== JQLiteController)) ? arg1 : arg2) === undefined) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for(i=0; i < this.length; i++) {
if (fn === JQLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
if (this.length)
return fn(this[0], arg1, arg2);
}
} else {
// we are a write, so apply to all children
for(i=0; i < this.length; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
return fn.$dv;
};
});
function createEventHandler(element, events) {
var eventHandler = function (event, type) {
if (!event.preventDefault) {
event.preventDefault = function() {
event.returnValue = false; //ie
};
}
if (!event.stopPropagation) {
event.stopPropagation = function() {
event.cancelBubble = true; //ie
};
}
if (!event.target) {
event.target = event.srcElement || document;
}
if (isUndefined(event.defaultPrevented)) {
var prevent = event.preventDefault;
event.preventDefault = function() {
event.defaultPrevented = true;
prevent.call(event);
};
event.defaultPrevented = false;
}
event.isDefaultPrevented = function() {
return event.defaultPrevented;
};
forEach(events[type || event.type], function(fn) {
fn.call(element, event);
});
// Remove monkey-patched methods (IE),
// as they would cause memory leaks in IE8.
if (msie <= 8) {
// IE7/8 does not allow to delete property on native object
event.preventDefault = null;
event.stopPropagation = null;
event.isDefaultPrevented = null;
} else {
// It shouldn't affect normal browsers (native methods are defined on prototype).
delete event.preventDefault;
delete event.stopPropagation;
delete event.isDefaultPrevented;
}
};
eventHandler.elem = element;
return eventHandler;
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: JQLiteRemoveData,
dealoc: JQLiteDealoc,
bind: function bindFn(element, type, fn){
var events = JQLiteExpandoStore(element, 'events'),
handle = JQLiteExpandoStore(element, 'handle');
if (!events) JQLiteExpandoStore(element, 'events', events = {});
if (!handle) JQLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
forEach(type.split(' '), function(type){
var eventFns = events[type];
if (!eventFns) {
if (type == 'mouseenter' || type == 'mouseleave') {
var contains = document.body.contains || document.body.compareDocumentPosition ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
events[type] = [];
// Refer to jQuery's implementation of mouseenter & mouseleave
// Read about mouseenter and mouseleave:
// http://www.quirksmode.org/js/events_mouse.html#link8
var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"}
bindFn(element, eventmap[type], function(event) {
var ret, target = this, related = event.relatedTarget;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !contains(target, related)) ){
handle(event, type);
}
});
} else {
addEventListenerFn(element, type, handle);
events[type] = [];
}
eventFns = events[type]
}
eventFns.push(fn);
});
},
unbind: JQLiteUnbind,
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
JQLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node){
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element){
if (element.nodeType === 1)
children.push(element);
});
return children;
},
contents: function(element) {
return element.childNodes || [];
},
append: function(element, node) {
forEach(new JQLite(node), function(child){
if (element.nodeType === 1)
element.appendChild(child);
});
},
prepend: function(element, node) {
if (element.nodeType === 1) {
var index = element.firstChild;
forEach(new JQLite(node), function(child){
if (index) {
element.insertBefore(child, index);
} else {
element.appendChild(child);
index = child;
}
});
}
},
wrap: function(element, wrapNode) {
wrapNode = jqLite(wrapNode)[0];
var parent = element.parentNode;
if (parent) {
parent.replaceChild(wrapNode, element);
}
wrapNode.appendChild(element);
},
remove: function(element) {
JQLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
forEach(new JQLite(newElement), function(node){
parent.insertBefore(node, index.nextSibling);
index = node;
});
},
addClass: JQLiteAddClass,
removeClass: JQLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (isUndefined(condition)) {
condition = !JQLiteHasClass(element, selector);
}
(condition ? JQLiteAddClass : JQLiteRemoveClass)(element, selector);
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
next: function(element) {
if (element.nextElementSibling) {
return element.nextElementSibling;
}
// IE8 doesn't have nextElementSibling
var elm = element.nextSibling;
while (elm != null && elm.nodeType !== 1) {
elm = elm.nextSibling;
}
return elm;
},
find: function(element, selector) {
return element.getElementsByTagName(selector);
},
clone: JQLiteClone,
triggerHandler: function(element, eventName) {
var eventFns = (JQLiteExpandoStore(element, 'events') || {})[eventName];
forEach(eventFns, function(fn) {
fn.call(element, null);
});
}
}, function(fn, name){
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2) {
var value;
for(var i=0; i < this.length; i++) {
if (value == undefined) {
value = fn(this[i], arg1, arg2);
if (value !== undefined) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
JQLiteAddNodes(value, fn(this[i], arg1, arg2));
}
}
return value == undefined ? this : value;
};
});
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj) {
var objType = typeof obj,
key;
if (objType == 'object' && obj !== null) {
if (typeof (key = obj.$$hashKey) == 'function') {
// must invoke on object to keep the right this
key = obj.$$hashKey();
} else if (key === undefined) {
key = obj.$$hashKey = nextUid();
}
} else {
key = obj;
}
return objType + ':' + key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(array){
forEach(array, this.put, this);
}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
this[hashKey(key)] = value;
},
/**
* @param key
* @returns the value for the key
*/
get: function(key) {
return this[hashKey(key)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
var value = this[key = hashKey(key)];
delete this[key];
return value;
}
};
/**
* A map where multiple values can be added to the same key such that they form a queue.
* @returns {HashQueueMap}
*/
function HashQueueMap() {}
HashQueueMap.prototype = {
/**
* Same as array push, but using an array as the value for the hash
*/
push: function(key, value) {
var array = this[key = hashKey(key)];
if (!array) {
this[key] = [value];
} else {
array.push(value);
}
},
/**
* Same as array shift, but using an array as the value for the hash
*/
shift: function(key) {
var array = this[key = hashKey(key)];
if (array) {
if (array.length == 1) {
delete this[key];
return array[0];
} else {
return array.shift();
}
}
},
/**
* return the first item without deleting it
*/
peek: function(key) {
var array = this[hashKey(key)];
if (array) {
return array[0];
}
}
};
/**
* @ngdoc function
* @name angular.injector
* @function
*
* @description
* Creates an injector function that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.<string|Function>} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
*
* @example
* Typical usage
* <pre>
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick off your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document){
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* </pre>
*/
/**
* @ngdoc overview
* @name AUTO
* @description
*
* Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
*/
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function annotate(fn) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn == 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
arg.replace(FN_ARG, function(all, underscore, name){
$inject.push(name);
});
});
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn');
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc object
* @name AUTO.$injector
* @function
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link AUTO.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* <pre>
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector){
* return $injector;
* }).toBe($injector);
* </pre>
*
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following are all valid ways of annotating function with injection arguments and are equivalent.
*
* <pre>
* // inferred (only works if code not minified/obfuscated)
* $injector.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $injector.invoke(explicit);
*
* // inline
* $injector.invoke(['serviceA', function(serviceA){}]);
* </pre>
*
* ## Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition can then be
* parsed and the function arguments can be extracted. *NOTE:* This does not work with minification, and obfuscation
* tools since these tools change the argument names.
*
* ## `$inject` Annotation
* By adding a `$inject` property onto a function the injection parameters can be specified.
*
* ## Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc method
* @name AUTO.$injector#get
* @methodOf AUTO.$injector
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name AUTO.$injector#invoke
* @methodOf AUTO.$injector
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {!function} fn The function to invoke. The function arguments come form the function annotation.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name AUTO.$injector#instantiate
* @methodOf AUTO.$injector
* @description
* Create a new instance of JS type. The method takes a constructor function invokes the new operator and supplies
* all of the arguments to the constructor function as specified by the constructor annotation.
*
* @param {function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this object first, before
* the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name AUTO.$injector#annotate
* @methodOf AUTO.$injector
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is used by the injector
* to determine which services need to be injected into the function when the function is invoked. There are three
* ways in which the function can be annotated with the needed dependencies.
*
* # Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done by converting
* the function into a string using `toString()` method and extracting the argument names.
* <pre>
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* This method does not work with code minfication / obfuscation. For this reason the following annotation strategies
* are supported.
*
* # The `$inject` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings represent names of
* services to be injected into the function.
* <pre>
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController.$inject = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* # The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property is very
* inconvenient. In these situations using the array notation to specify the dependencies in a way that survives
* minification is a better choice:
*
* <pre>
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tmpFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* </pre>
*
* @param {function|Array.<string|Function>} fn Function for which dependent service names need to be retrieved as described
* above.
*
* @returns {Array.<string>} The names of the services which the function requires.
*/
/**
* @ngdoc object
* @name AUTO.$provide
*
* @description
*
* Use `$provide` to register new providers with the `$injector`. The providers are the factories for the instance.
* The providers share the same name as the instance they create with `Provider` suffixed to them.
*
* A provider is an object with a `$get()` method. The injector calls the `$get` method to create a new instance of
* a service. The Provider can have additional methods which would allow for configuration of the provider.
*
* <pre>
* function GreetProvider() {
* var salutation = 'Hello';
*
* this.salutation = function(text) {
* salutation = text;
* };
*
* this.$get = function() {
* return function (name) {
* return salutation + ' ' + name + '!';
* };
* };
* }
*
* describe('Greeter', function(){
*
* beforeEach(module(function($provide) {
* $provide.provider('greet', GreetProvider);
* }));
*
* it('should greet', inject(function(greet) {
* expect(greet('angular')).toEqual('Hello angular!');
* }));
*
* it('should allow configuration of salutation', function() {
* module(function(greetProvider) {
* greetProvider.salutation('Ahoj');
* });
* inject(function(greet) {
* expect(greet('angular')).toEqual('Ahoj angular!');
* });
* });
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#provider
* @methodOf AUTO.$provide
* @description
*
* Register a provider for a service. The providers can be retrieved and can have additional configuration methods.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be created.
* - `Constructor`: a new instance of the provider will be created using
* {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as `object`.
*
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#factory
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if only `$get` method is required.
*
* @param {string} name The name of the instance.
* @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for
* `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#service
* @methodOf AUTO.$provide
* @description
*
* A short hand for registering service of given class.
*
* @param {string} name The name of the instance.
* @param {Function} constructor A class (constructor function) that will be instantiated.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#value
* @methodOf AUTO.$provide
* @description
*
* A short hand for configuring services if the `$get` method is a constant.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#constant
* @methodOf AUTO.$provide
* @description
*
* A constant value, but unlike {@link AUTO.$provide#value value} it can be injected
* into configuration function (other modules) and it is not interceptable by
* {@link AUTO.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*/
/**
* @ngdoc method
* @name AUTO.$provide#decorator
* @methodOf AUTO.$provide
* @description
*
* Decoration of service, allows the decorator to intercept the service instance creation. The
* returned instance may be the original instance, or a new instance which delegates to the
* original instance.
*
* @param {string} name The name of the service to decorate.
* @param {function()} decorator This function will be invoked when the service needs to be
* instantiated. The function is called using the {@link AUTO.$injector#invoke
* injector.invoke} method and is therefore fully injectable. Local injection arguments:
*
* * `$delegate` - The original service instance, which can be monkey patched, configured,
* decorated or delegated to.
*/
function createInjector(modulesToLoad) {
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap(),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = createInternalInjector(providerCache, function() {
throw Error("Unknown provider: " + path.join(' <- '));
}),
instanceCache = {},
instanceInjector = (instanceCache.$injector =
createInternalInjector(instanceCache, function(servicename) {
var provider = providerInjector.get(servicename + providerSuffix);
return instanceInjector.invoke(provider.$get, provider);
}));
forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
}
}
function provider(name, provider_) {
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw Error('Provider ' + name + ' must define $get factory method.');
}
return providerCache[name + providerSuffix] = provider_;
}
function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, value) { return factory(name, valueFn(value)); }
function constant(name, value) {
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad){
var runBlocks = [];
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
if (isString(module)) {
var moduleFn = angularModule(module);
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
try {
for(var invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
var invokeArgs = invokeQueue[i],
provider = invokeArgs[0] == '$injector'
? providerInjector
: providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isFunction(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + module;
throw e;
}
} else if (isArray(module)) {
try {
runBlocks.push(providerInjector.invoke(module));
} catch (e) {
if (e.message) e.message += ' from ' + String(module[module.length - 1]);
throw e;
}
} else {
assertArgFn(module, 'module');
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName) {
if (typeof serviceName !== 'string') {
throw Error('Service name expected');
}
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw Error('Circular dependency: ' + path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName);
} finally {
path.shift();
}
}
}
function invoke(fn, self, locals){
var args = [],
$inject = annotate(fn),
length, i,
key;
for(i = 0, length = $inject.length; i < length; i++) {
key = $inject[i];
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key)
);
}
if (!fn.$inject) {
// this means that we must be an array.
fn = fn[length];
}
// Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
switch (self ? -1 : args.length) {
case 0: return fn();
case 1: return fn(args[0]);
case 2: return fn(args[0], args[1]);
case 3: return fn(args[0], args[1], args[2]);
case 4: return fn(args[0], args[1], args[2], args[3]);
case 5: return fn(args[0], args[1], args[2], args[3], args[4]);
case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8]);
case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7], args[8], args[9]);
default: return fn.apply(self, args);
}
}
function instantiate(Type, locals) {
var Constructor = function() {},
instance, returnedValue;
// Check if Type is annotated and use just the given function at n-1 as parameter
// e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
instance = new Constructor();
returnedValue = invoke(Type, instance, locals);
return isObject(returnedValue) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: annotate
};
}
}
/**
* @ngdoc function
* @name ng.$anchorScroll
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it checks current value of `$location.hash()` and scroll to related element,
* according to rules specified in
* {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}.
*
* It also watches the `$location.hash()` and scroll whenever it changes to match any anchor.
* This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled = true;
this.disableAutoScrolling = function() {
autoScrollingEnabled = false;
};
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
var document = $window.document;
// helper function to get first anchor from a NodeList
// can't use filter.filter, as it accepts only instances of Array
// and IE can't convert NodeList to an array using [].slice
// TODO(vojta): use filter if we change it to accept lists as well
function getFirstAnchor(list) {
var result = null;
forEach(list, function(element) {
if (!result && lowercase(element.nodeName) === 'a') result = element;
});
return result;
}
function scroll() {
var hash = $location.hash(), elm;
// empty hash, scroll to the top of the page
if (!hash) $window.scrollTo(0, 0);
// element with given id
else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
// first anchor with given name :-D
else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
// no element and hash == 'top', scroll to the top of the page
else if (hash === 'top') $window.scrollTo(0, 0);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $location.hash() change), browser native does scroll
if (autoScrollingEnabled) {
$rootScope.$watch(function autoScrollWatch() {return $location.hash();},
function autoScrollWatchAction() {
$rootScope.$evalAsync(scroll);
});
}
return scroll;
}];
}
/**
* ! This is a private undocumented service !
*
* @name ng.$browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {function()} XHR XMLHttpRequest constructor.
* @param {object} $log console.log or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer) {
var self = this,
rawDocument = document[0],
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {};
self.isMock = false;
var outstandingRequestCount = 0;
var outstandingRequestCallbacks = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = completeOutstandingRequest;
self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
/**
* Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
* counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
*/
function completeOutstandingRequest(fn) {
try {
fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount === 0) {
while(outstandingRequestCallbacks.length) {
try {
outstandingRequestCallbacks.pop()();
} catch (e) {
$log.error(e);
}
}
}
}
}
/**
* @private
* Note: this method is used only by scenario runner
* TODO(vojta): prefix this method with $$ ?
* @param {function()} callback Function that will be called when no outstanding request
*/
self.notifyWhenNoOutstandingRequests = function(callback) {
// force browser to execute all pollFns - this is needed so that cookies and other pollers fire
// at some deterministic time in respect to the test runner's actions. Leaving things up to the
// regular poller would result in flaky tests.
forEach(pollFns, function(pollFn){ pollFn(); });
if (outstandingRequestCount === 0) {
callback();
} else {
outstandingRequestCallbacks.push(callback);
}
};
//////////////////////////////////////////////////////////////
// Poll Watcher API
//////////////////////////////////////////////////////////////
var pollFns = [],
pollTimeout;
/**
* @name ng.$browser#addPollFn
* @methodOf ng.$browser
*
* @param {function()} fn Poll function to add
*
* @description
* Adds a function to the list of functions that poller periodically executes,
* and starts polling if not started yet.
*
* @returns {function()} the added function
*/
self.addPollFn = function(fn) {
if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
pollFns.push(fn);
return fn;
};
/**
* @param {number} interval How often should browser call poll functions (ms)
* @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
*
* @description
* Configures the poller to run in the specified intervals, using the specified
* setTimeout fn and kicks it off.
*/
function startPoller(interval, setTimeout) {
(function check() {
forEach(pollFns, function(pollFn){ pollFn(); });
pollTimeout = setTimeout(check, interval);
})();
}
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var lastBrowserUrl = location.href,
baseElement = document.find('base');
/**
* @name ng.$browser#url
* @methodOf ng.$browser
*
* @description
* GETTER:
* Without any argument, this method just returns current value of location.href.
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, pushState/replaceState is used, otherwise
* location.href/location.replace is used.
* Returns its own instance to allow chaining
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record ?
*/
self.url = function(url, replace) {
// setter
if (url) {
if (lastBrowserUrl == url) return;
lastBrowserUrl = url;
if ($sniffer.history) {
if (replace) history.replaceState(null, '', url);
else {
history.pushState(null, '', url);
// Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
baseElement.attr('href', baseElement.attr('href'));
}
} else {
if (replace) location.replace(url);
else location.href = url;
}
return self;
// getter
} else {
// the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
return location.href.replace(/%27/g,"'");
}
};
var urlChangeListeners = [],
urlChangeInit = false;
function fireUrlChange() {
if (lastBrowserUrl == self.url()) return;
lastBrowserUrl = self.url();
forEach(urlChangeListeners, function(listener) {
listener(self.url());
});
}
/**
* @name ng.$browser#onUrlChange
* @methodOf ng.$browser
* @TODO(vojta): refactor to use node's syntax for events
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed by outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to monitor url changes in angular apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
// don't fire popstate when user change the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).bind('popstate', fireUrlChange);
// hashchange event
if ($sniffer.hashchange) jqLite(window).bind('hashchange', fireUrlChange);
// polling
else self.addPollFn(fireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string=}
*/
self.baseHref = function() {
var href = baseElement.attr('href');
return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : '';
};
//////////////////////////////////////////////////////////////
// Cookies API
//////////////////////////////////////////////////////////////
var lastCookies = {};
var lastCookieString = '';
var cookiePath = self.baseHref();
/**
* @name ng.$browser#cookies
* @methodOf ng.$browser
*
* @param {string=} name Cookie name
* @param {string=} value Cokkie value
*
* @description
* The cookies method provides a 'private' low level access to browser cookies.
* It is not meant to be used directly, use the $cookie service instead.
*
* The return values vary depending on the arguments that the method was called with as follows:
* <ul>
* <li>cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it</li>
* <li>cookies(name, value) -> set name to value, if value is undefined delete the cookie</li>
* <li>cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)</li>
* </ul>
*
* @returns {Object} Hash of all cookies (if called without any parameter)
*/
self.cookies = function(name, value) {
var cookieLength, cookieArray, cookie, i, index;
if (name) {
if (value === undefined) {
rawDocument.cookie = escape(name) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
} else {
if (isString(value)) {
cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) + ';path=' + cookiePath).length + 1;
// per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
// - 300 cookies
// - 20 cookies per unique domain
// - 4096 bytes per cookie
if (cookieLength > 4096) {
$log.warn("Cookie '"+ name +"' possibly not set or overflowed because it was too large ("+
cookieLength + " > 4096 bytes)!");
}
}
}
} else {
if (rawDocument.cookie !== lastCookieString) {
lastCookieString = rawDocument.cookie;
cookieArray = lastCookieString.split("; ");
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
var name = unescape(cookie.substring(0, index));
// the first value that is seen for a cookie is the most
// specific one. values for the same cookie name that
// follow are for less specific paths.
if (lastCookies[name] === undefined) {
lastCookies[name] = unescape(cookie.substring(index + 1));
}
}
}
}
return lastCookies;
}
};
/**
* @name ng.$browser#defer
* @methodOf ng.$browser
* @param {function()} fn A function, who's execution should be defered.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchroniously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay) {
var timeoutId;
outstandingRequestCount++;
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
completeOutstandingRequest(fn);
}, delay || 0);
pendingDeferIds[timeoutId] = true;
return timeoutId;
};
/**
* @name ng.$browser#defer.cancel
* @methodOf ng.$browser.defer
*
* @description
* Cancels a defered task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfuly canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds[deferId]) {
delete pendingDeferIds[deferId];
clearTimeout(deferId);
completeOutstandingRequest(noop);
return true;
}
return false;
};
}
function $BrowserProvider(){
this.$get = ['$window', '$log', '$sniffer', '$document',
function( $window, $log, $sniffer, $document){
return new Browser($window, $document, $log, $sniffer);
}];
}
/**
* @ngdoc object
* @name ng.$cacheFactory
*
* @description
* Factory that constructs cache objects.
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=} options Options object that specifies the cache behavior. Properties:
*
* - `{number=}` `capacity` — turns the cache into LRU cache.
*
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
* - `{void}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache.
* - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
* - `{void}` `removeAll()` — Removes all cached values.
* - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
*
*/
function $CacheFactoryProvider() {
this.$get = function() {
var caches = {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw Error('cacheId ' + cacheId + ' taken');
}
var size = 0,
stats = extend({}, options, {id: cacheId}),
data = {},
capacity = (options && options.capacity) || Number.MAX_VALUE,
lruHash = {},
freshEnd = null,
staleEnd = null;
return caches[cacheId] = {
put: function(key, value) {
var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
refresh(lruEntry);
if (isUndefined(value)) return;
if (!(key in data)) size++;
data[key] = value;
if (size > capacity) {
this.remove(staleEnd.key);
}
},
get: function(key) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
return data[key];
},
remove: function(key) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
if (lruEntry == freshEnd) freshEnd = lruEntry.p;
if (lruEntry == staleEnd) staleEnd = lruEntry.n;
link(lruEntry.n,lruEntry.p);
delete lruHash[key];
delete data[key];
size--;
},
removeAll: function() {
data = {};
size = 0;
lruHash = {};
freshEnd = staleEnd = null;
},
destroy: function() {
data = null;
stats = null;
lruHash = null;
delete caches[cacheId];
},
info: function() {
return extend({}, stats, {size: size});
}
};
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry != freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd == entry) {
staleEnd = entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry != prevEntry) {
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc object
* @name ng.$templateCache
*
* @description
* Cache used for storing html templates.
*
* See {@link ng.$cacheFactory $cacheFactory}.
*
*/
function $TemplateCacheProvider() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('templates');
}];
}
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
*/
var NON_ASSIGNABLE_MODEL_EXPRESSION = 'Non-assignable model expression: ';
/**
* @ngdoc function
* @name ng.$compile
* @function
*
* @description
* Compiles a piece of HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link ng.$rootScope.Scope scope} and the template together.
*
* The compilation is a process of walking the DOM tree and trying to match DOM elements to
* {@link ng.$compileProvider#directive directives}. For each match it
* executes corresponding template function and collects the
* instance functions into a single template function which is then returned.
*
* The template function can then be used once to produce the view or as it is the case with
* {@link ng.directive:ngRepeat repeater} many-times, in which
* case each call results in a view that is a DOM clone of the original template.
*
<doc:example module="compile">
<doc:source>
<script>
// declare a new module, and inject the $compileProvider
angular.module('compile', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
})
});
function Ctrl($scope) {
$scope.name = 'Angular';
$scope.html = 'Hello {{name}}';
}
</script>
<div ng-controller="Ctrl">
<input ng-model="name"> <br>
<textarea ng-model="html"></textarea> <br>
<div compile="html"></div>
</div>
</doc:source>
<doc:scenario>
it('should auto compile', function() {
expect(element('div[compile]').text()).toBe('Hello Angular');
input('html').enter('{{name}}!');
expect(element('div[compile]').text()).toBe('Angular!');
});
</doc:scenario>
</doc:example>
*
*
* @param {string|DOMElement} element Element or HTML string to compile into a template function.
* @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
* @param {number} maxPriority only apply directives lower then given priority (Only effects the
* root element(s), not their children)
* @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
* (a DOM element/tree) to a scope. Where:
*
* * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
* `template` and call the `cloneAttachFn` function allowing the caller to attach the
* cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
* called as: <br> `cloneAttachFn(clonedElement, scope)` where:
*
* * `clonedElement` - is a clone of the original `element` passed into the compiler.
* * `scope` - is the current scope with which the linking function is working with.
*
* Calling the linking function returns the element of the template. It is either the original element
* passed in, or the clone of the element if the `cloneAttachFn` is provided.
*
* After linking the view is not updated until after a call to $digest which typically is done by
* Angular automatically.
*
* If you need access to the bound view, there are two ways to do it:
*
* - If you are not asking the linking function to clone the template, create the DOM element(s)
* before you send them to the compiler and keep this reference around.
* <pre>
* var element = $compile('<p>{{total}}</p>')(scope);
* </pre>
*
* - if on the other hand, you need the element to be cloned, the view reference from the original
* example would not point to the clone, but rather to the original template that was cloned. In
* this case, you can access the clone via the cloneAttachFn:
* <pre>
* var templateHTML = angular.element('<p>{{total}}</p>'),
* scope = ....;
*
* var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
* //attach the clone to DOM document at the right place
* });
*
* //now we have reference to the cloned DOM via `clone`
* </pre>
*
*
* For information on how the compiler works, see the
* {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
*/
/**
* @ngdoc service
* @name ng.$compileProvider
* @function
*
* @description
*/
$CompileProvider.$inject = ['$provide'];
function $CompileProvider($provide) {
var hasDirectives = {},
Suffix = 'Directive',
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
MULTI_ROOT_TEMPLATE_ERROR = 'Template must have exactly one root element. was: ',
urlSanitizationWhitelist = /^\s*(https?|ftp|mailto|file):/;
/**
* @ngdoc function
* @name ng.$compileProvider#directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register a new directives with the compiler.
*
* @param {string} name Name of the directive in camel-case. (ie <code>ngBind</code> which will match as
* <code>ng-bind</code>).
* @param {function} directiveFactory An injectable directive factroy function. See {@link guide/directive} for more
* info.
* @returns {ng.$compileProvider} Self for chaining.
*/
this.directive = function registerDirective(name, directiveFactory) {
if (isString(name)) {
assertArg(directiveFactory, 'directive');
if (!hasDirectives.hasOwnProperty(name)) {
hasDirectives[name] = [];
$provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
function($injector, $exceptionHandler) {
var directives = [];
forEach(hasDirectives[name], function(directiveFactory) {
try {
var directive = $injector.invoke(directiveFactory);
if (isFunction(directive)) {
directive = { compile: valueFn(directive) };
} else if (!directive.compile && directive.link) {
directive.compile = valueFn(directive.link);
}
directive.priority = directive.priority || 0;
directive.name = directive.name || name;
directive.require = directive.require || (directive.controller && directive.name);
directive.restrict = directive.restrict || 'A';
directives.push(directive);
} catch (e) {
$exceptionHandler(e);
}
});
return directives;
}]);
}
hasDirectives[name].push(directiveFactory);
} else {
forEach(name, reverseParams(registerDirective));
}
return this;
};
/**
* @ngdoc function
* @name ng.$compileProvider#urlSanitizationWhitelist
* @methodOf ng.$compileProvider
* @function
*
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during a[href] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to a[href] via data-binding is first normalized and turned into an
* absolute url. Afterwards the url is matched against the `urlSanitizationWhitelist` regular
* expression. If a match is found the original url is written into the dom. Otherwise the
* absolute url is prefixed with `'unsafe:'` string and only then it is written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.urlSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
urlSanitizationWhitelist = regexp;
return this;
}
return urlSanitizationWhitelist;
};
this.$get = [
'$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
'$controller', '$rootScope', '$document',
function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
$controller, $rootScope, $document) {
var Attributes = function(element, attr) {
this.$$element = element;
this.$attr = attr || {};
};
Attributes.prototype = {
$normalize: directiveNormalize,
/**
* Set a normalized attribute on the element in a way such that all directives
* can share the attribute. This function properly handles boolean attributes.
* @param {string} key Normalized key. (ie ngAttribute)
* @param {string|boolean} value The value to set. If `null` attribute will be deleted.
* @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
* Defaults to true.
* @param {string=} attrName Optional none normalized name. Defaults to key.
*/
$set: function(key, value, writeAttr, attrName) {
var booleanKey = getBooleanAttrName(this.$$element[0], key),
$$observers = this.$$observers,
normalizedVal;
if (booleanKey) {
this.$$element.prop(key, value);
attrName = booleanKey;
}
this[key] = value;
// translate normalized key to actual key
if (attrName) {
this.$attr[key] = attrName;
} else {
attrName = this.$attr[key];
if (!attrName) {
this.$attr[key] = attrName = snake_case(key, '-');
}
}
// sanitize a[href] values
if (nodeName_(this.$$element[0]) === 'A' && key === 'href') {
urlSanitizationNode.setAttribute('href', value);
// href property always returns normalized absolute url, so we can match against that
normalizedVal = urlSanitizationNode.href;
if (!normalizedVal.match(urlSanitizationWhitelist)) {
this[key] = value = 'unsafe:' + normalizedVal;
}
}
if (writeAttr !== false) {
if (value === null || value === undefined) {
this.$$element.removeAttr(attrName);
} else {
this.$$element.attr(attrName, value);
}
}
// fire observers
$$observers && forEach($$observers[key], function(fn) {
try {
fn(value);
} catch (e) {
$exceptionHandler(e);
}
});
},
/**
* Observe an interpolated attribute.
* The observer will never be called, if given attribute is not interpolated.
*
* @param {string} key Normalized key. (ie ngAttribute) .
* @param {function(*)} fn Function that will be called whenever the attribute value changes.
* @returns {function(*)} the `fn` Function passed in.
*/
$observe: function(key, fn) {
var attrs = this,
$$observers = (attrs.$$observers || (attrs.$$observers = {})),
listeners = ($$observers[key] || ($$observers[key] = []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter) {
// no one registered attribute interpolation function, so lets call it manually
fn(attrs[key]);
}
});
return fn;
}
};
var urlSanitizationNode = $document[0].createElement('a'),
startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
? identity
: function denormalizeTemplate(template) {
return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
};
return compile;
//================================
function compile($compileNodes, transcludeFn, maxPriority) {
if (!($compileNodes instanceof jqLite)) {
// jquery always rewraps, whereas we need to preserve the original selector so that we can modify it.
$compileNodes = jqLite($compileNodes);
}
// We can not compile top level text elements since text nodes can be merged and we will
// not be able to attach scope data to them, so we will wrap them in <span>
forEach($compileNodes, function(node, index){
if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
$compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
}
});
var compositeLinkFn = compileNodes($compileNodes, transcludeFn, $compileNodes, maxPriority);
return function publicLinkFn(scope, cloneConnectFn){
assertArg(scope, 'scope');
// important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
// and sometimes changes the structure of the DOM.
var $linkNode = cloneConnectFn
? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
: $compileNodes;
// Attach scope only to non-text nodes.
for(var i = 0, ii = $linkNode.length; i<ii; i++) {
var node = $linkNode[i];
if (node.nodeType == 1 /* element */ || node.nodeType == 9 /* document */) {
$linkNode.eq(i).data('$scope', scope);
}
}
safeAddClass($linkNode, 'ng-scope');
if (cloneConnectFn) cloneConnectFn($linkNode, scope);
if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
return $linkNode;
};
}
function wrongMode(localName, mode) {
throw Error("Unsupported '" + mode + "' for '" + localName + "'.");
}
function safeAddClass($element, className) {
try {
$element.addClass(className);
} catch(e) {
// ignore, since it means that we are trying to set class on
// SVG element, where class name is read-only.
}
}
/**
* Compile function matches each node in nodeList against the directives. Once all directives
* for a particular node are collected their compile functions are executed. The compile
* functions return values - the linking functions - are combined into a composite linking
* function, which is the a linking function for the node.
*
* @param {NodeList} nodeList an array of nodes or NodeList to compile
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then the
* rootElement must be set the jqLite collection of the compile root. This is
* needed so that the jqLite collection items can be replaced with widgets.
* @param {number=} max directive priority
* @returns {?function} A composite linking function of all of the matched directives or null.
*/
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority) {
var linkFns = [],
nodeLinkFn, childLinkFn, directives, attrs, linkFnFound;
for(var i = 0; i < nodeList.length; i++) {
attrs = new Attributes();
// we must always refer to nodeList[i] since the nodes can be replaced underneath us.
directives = collectDirectives(nodeList[i], [], attrs, maxPriority);
nodeLinkFn = (directives.length)
? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement)
: null;
childLinkFn = (nodeLinkFn && nodeLinkFn.terminal || !nodeList[i].childNodes || !nodeList[i].childNodes.length)
? null
: compileNodes(nodeList[i].childNodes,
nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
linkFns.push(nodeLinkFn);
linkFns.push(childLinkFn);
linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn);
}
// return a linking function if we have found anything, null otherwise
return linkFnFound ? compositeLinkFn : null;
function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
var nodeLinkFn, childLinkFn, node, childScope, childTranscludeFn, i, ii, n;
// copy nodeList so that linking doesn't break due to live list updates.
var stableNodeList = [];
for (i = 0, ii = nodeList.length; i < ii; i++) {
stableNodeList.push(nodeList[i]);
}
for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
node = stableNodeList[n];
nodeLinkFn = linkFns[i++];
childLinkFn = linkFns[i++];
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope = scope.$new(isObject(nodeLinkFn.scope));
jqLite(node).data('$scope', childScope);
} else {
childScope = scope;
}
childTranscludeFn = nodeLinkFn.transclude;
if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
nodeLinkFn(childLinkFn, childScope, node, $rootElement,
(function(transcludeFn) {
return function(cloneFn) {
var transcludeScope = scope.$new();
transcludeScope.$$transcluded = true;
return transcludeFn(transcludeScope, cloneFn).
bind('$destroy', bind(transcludeScope, transcludeScope.$destroy));
};
})(childTranscludeFn || transcludeFn)
);
} else {
nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn);
}
} else if (childLinkFn) {
childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
}
}
}
}
/**
* Looks for directives on the given node and adds them to the directive collection which is
* sorted.
*
* @param node Node to search.
* @param directives An array to which the directives are added to. This array is sorted before
* the function returns.
* @param attrs The shared attrs object which is used to populate the normalized attributes.
* @param {number=} maxPriority Max directive priority.
*/
function collectDirectives(node, directives, attrs, maxPriority) {
var nodeType = node.nodeType,
attrsMap = attrs.$attr,
match,
className;
switch(nodeType) {
case 1: /* Element */
// use the node name: <directive>
addDirective(directives,
directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority);
// iterate over the attributes
for (var attr, name, nName, value, nAttrs = node.attributes,
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
attr = nAttrs[j];
if (attr.specified) {
name = attr.name;
nName = directiveNormalize(name.toLowerCase());
attrsMap[nName] = name;
attrs[nName] = value = trim((msie && name == 'href')
? decodeURIComponent(node.getAttribute(name, 2))
: attr.value);
if (getBooleanAttrName(node, nName)) {
attrs[nName] = true; // presence means true
}
addAttrInterpolateDirective(node, directives, value, nName);
addDirective(directives, nName, 'A', maxPriority);
}
}
// use class as directive
className = node.className;
if (isString(className) && className !== '') {
while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
nName = directiveNormalize(match[2]);
if (addDirective(directives, nName, 'C', maxPriority)) {
attrs[nName] = trim(match[3]);
}
className = className.substr(match.index + match[0].length);
}
}
break;
case 3: /* Text Node */
addTextInterpolateDirective(directives, node.nodeValue);
break;
case 8: /* Comment */
try {
match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
if (match) {
nName = directiveNormalize(match[1]);
if (addDirective(directives, nName, 'M', maxPriority)) {
attrs[nName] = trim(match[2]);
}
}
} catch (e) {
// turns out that under some circumstances IE9 throws errors when one attempts to read comment's node value.
// Just ignore it and continue. (Can't seem to reproduce in test case.)
}
break;
}
directives.sort(byPriority);
return directives;
}
/**
* Once the directives have been collected, their compile functions are executed. This method
* is responsible for inlining directive templates as well as terminating the application
* of the directives if the terminal directive has been reached.
*
* @param {Array} directives Array of collected directives to execute their compile function.
* this needs to be pre-sorted by priority order.
* @param {Node} compileNode The raw DOM node to apply the compile functions to
* @param {Object} templateAttrs The shared attribute function
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {JQLite} jqCollection If we are working on the root of the compile tree then this
* argument has the root jqLite array so that we can replace nodes on it.
* @returns linkFn
*/
function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn, jqCollection) {
var terminalPriority = -Number.MAX_VALUE,
preLinkFns = [],
postLinkFns = [],
newScopeDirective = null,
newIsolateScopeDirective = null,
templateDirective = null,
$compileNode = templateAttrs.$$element = jqLite(compileNode),
directive,
directiveName,
$template,
transcludeDirective,
childTranscludeFn = transcludeFn,
controllerDirectives,
linkFn,
directiveValue;
// executes all directives on the current element
for(var i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
$template = undefined;
if (terminalPriority > directive.priority) {
break; // prevent further processing of directives
}
if (directiveValue = directive.scope) {
assertNoDuplicate('isolated scope', newIsolateScopeDirective, directive, $compileNode);
if (isObject(directiveValue)) {
safeAddClass($compileNode, 'ng-isolate-scope');
newIsolateScopeDirective = directive;
}
safeAddClass($compileNode, 'ng-scope');
newScopeDirective = newScopeDirective || directive;
}
directiveName = directive.name;
if (directiveValue = directive.controller) {
controllerDirectives = controllerDirectives || {};
assertNoDuplicate("'" + directiveName + "' controller",
controllerDirectives[directiveName], directive, $compileNode);
controllerDirectives[directiveName] = directive;
}
if (directiveValue = directive.transclude) {
assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode);
transcludeDirective = directive;
terminalPriority = directive.priority;
if (directiveValue == 'element') {
$template = jqLite(compileNode);
$compileNode = templateAttrs.$$element =
jqLite(document.createComment(' ' + directiveName + ': ' + templateAttrs[directiveName] + ' '));
compileNode = $compileNode[0];
replaceWith(jqCollection, jqLite($template[0]), compileNode);
childTranscludeFn = compile($template, transcludeFn, terminalPriority);
} else {
$template = jqLite(JQLiteClone(compileNode)).contents();
$compileNode.html(''); // clear contents
childTranscludeFn = compile($template, transcludeFn);
}
}
if ((directiveValue = directive.template)) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
directiveValue = denormalizeTemplate(directiveValue);
if (directive.replace) {
$template = jqLite('<div>' +
trim(directiveValue) +
'</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + directiveValue);
}
replaceWith(jqCollection, $compileNode, compileNode);
var newTemplateAttrs = {$attr: {}};
// combine directives from the original node and from the template:
// - take the array of directives for this element
// - split it into two parts, those that were already applied and those that weren't
// - collect directives from the template, add them to the second group and sort them
// - append the second group with new directives to the first group
directives = directives.concat(
collectDirectives(
compileNode,
directives.splice(i + 1, directives.length - (i + 1)),
newTemplateAttrs
)
);
mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
ii = directives.length;
} else {
$compileNode.html(directiveValue);
}
}
if (directive.templateUrl) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i),
nodeLinkFn, $compileNode, templateAttrs, jqCollection, directive.replace,
childTranscludeFn);
ii = directives.length;
} else if (directive.compile) {
try {
linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
if (directive.terminal) {
nodeLinkFn.terminal = true;
terminalPriority = Math.max(terminalPriority, directive.priority);
}
}
nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope;
nodeLinkFn.transclude = transcludeDirective && childTranscludeFn;
// might be normal or delayed nodeLinkFn depending on if templateUrl is present
return nodeLinkFn;
////////////////////
function addLinkFns(pre, post) {
if (pre) {
pre.require = directive.require;
preLinkFns.push(pre);
}
if (post) {
post.require = directive.require;
postLinkFns.push(post);
}
}
function getControllers(require, $element) {
var value, retrievalMethod = 'data', optional = false;
if (isString(require)) {
while((value = require.charAt(0)) == '^' || value == '?') {
require = require.substr(1);
if (value == '^') {
retrievalMethod = 'inheritedData';
}
optional = optional || value == '?';
}
value = $element[retrievalMethod]('$' + require + 'Controller');
if (!value && !optional) {
throw Error("No controller: " + require);
}
return value;
} else if (isArray(require)) {
value = [];
forEach(require, function(require) {
value.push(getControllers(require, $element));
});
}
return value;
}
function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
var attrs, $element, i, ii, linkFn, controller;
if (compileNode === linkNode) {
attrs = templateAttrs;
} else {
attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
}
$element = attrs.$$element;
if (newIsolateScopeDirective) {
var LOCAL_REGEXP = /^\s*([@=&])\s*(\w*)\s*$/;
var parentScope = scope.$parent || scope;
forEach(newIsolateScopeDirective.scope, function(definiton, scopeName) {
var match = definiton.match(LOCAL_REGEXP) || [],
attrName = match[2]|| scopeName,
mode = match[1], // @, =, or &
lastValue,
parentGet, parentSet;
scope.$$isolateBindings[scopeName] = mode + attrName;
switch (mode) {
case '@': {
attrs.$observe(attrName, function(value) {
scope[scopeName] = value;
});
attrs.$$observers[attrName].$$scope = parentScope;
break;
}
case '=': {
parentGet = $parse(attrs[attrName]);
parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = scope[scopeName] = parentGet(parentScope);
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + attrs[attrName] +
' (directive: ' + newIsolateScopeDirective.name + ')');
};
lastValue = scope[scopeName] = parentGet(parentScope);
scope.$watch(function parentValueWatch() {
var parentValue = parentGet(parentScope);
if (parentValue !== scope[scopeName]) {
// we are out of sync and need to copy
if (parentValue !== lastValue) {
// parent changed and it has precedence
lastValue = scope[scopeName] = parentValue;
} else {
// if the parent can be assigned then do so
parentSet(parentScope, parentValue = lastValue = scope[scopeName]);
}
}
return parentValue;
});
break;
}
case '&': {
parentGet = $parse(attrs[attrName]);
scope[scopeName] = function(locals) {
return parentGet(parentScope, locals);
};
break;
}
default: {
throw Error('Invalid isolate scope definition for directive ' +
newIsolateScopeDirective.name + ': ' + definiton);
}
}
});
}
if (controllerDirectives) {
forEach(controllerDirectives, function(directive) {
var locals = {
$scope: scope,
$element: $element,
$attrs: attrs,
$transclude: boundTranscludeFn
};
controller = directive.controller;
if (controller == '@') {
controller = attrs[directive.name];
}
$element.data(
'$' + directive.name + 'Controller',
$controller(controller, locals));
});
}
// PRELINKING
for(i = 0, ii = preLinkFns.length; i < ii; i++) {
try {
linkFn = preLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
// RECURSION
childLinkFn && childLinkFn(scope, linkNode.childNodes, undefined, boundTranscludeFn);
// POSTLINKING
for(i = 0, ii = postLinkFns.length; i < ii; i++) {
try {
linkFn = postLinkFns[i];
linkFn(scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
}
}
/**
* looks up the directive and decorates it with exception handling and proper parameters. We
* call this the boundDirective.
*
* @param {string} name name of the directive to look up.
* @param {string} location The directive must be found in specific format.
* String containing any of theses characters:
*
* * `E`: element name
* * `A': attribute
* * `C`: class
* * `M`: comment
* @returns true if directive was added.
*/
function addDirective(tDirectives, name, location, maxPriority) {
var match = false;
if (hasDirectives.hasOwnProperty(name)) {
for(var directive, directives = $injector.get(name + Suffix),
i = 0, ii = directives.length; i<ii; i++) {
try {
directive = directives[i];
if ( (maxPriority === undefined || maxPriority > directive.priority) &&
directive.restrict.indexOf(location) != -1) {
tDirectives.push(directive);
match = true;
}
} catch(e) { $exceptionHandler(e); }
}
}
return match;
}
/**
* When the element is replaced with HTML template then the new attributes
* on the template need to be merged with the existing attributes in the DOM.
* The desired effect is to have both of the attributes present.
*
* @param {object} dst destination attributes (original DOM)
* @param {object} src source attributes (from the directive template)
*/
function mergeTemplateAttributes(dst, src) {
var srcAttr = src.$attr,
dstAttr = dst.$attr,
$element = dst.$$element;
// reapply the old attributes to the new element
forEach(dst, function(value, key) {
if (key.charAt(0) != '$') {
if (src[key]) {
value += (key === 'style' ? ';' : ' ') + src[key];
}
dst.$set(key, value, true, srcAttr[key]);
}
});
// copy the new attributes on the old attrs object
forEach(src, function(value, key) {
if (key == 'class') {
safeAddClass($element, value);
dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
} else if (key == 'style') {
$element.attr('style', $element.attr('style') + ';' + value);
} else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
dst[key] = value;
dstAttr[key] = srcAttr[key];
}
});
}
function compileTemplateUrl(directives, beforeTemplateNodeLinkFn, $compileNode, tAttrs,
$rootElement, replace, childTranscludeFn) {
var linkQueue = [],
afterTemplateNodeLinkFn,
afterTemplateChildLinkFn,
beforeTemplateCompileNode = $compileNode[0],
origAsyncDirective = directives.shift(),
// The fact that we have to copy and patch the directive seems wrong!
derivedSyncDirective = extend({}, origAsyncDirective, {
controller: null, templateUrl: null, transclude: null, scope: null
});
$compileNode.html('');
$http.get(origAsyncDirective.templateUrl, {cache: $templateCache}).
success(function(content) {
var compileNode, tempTemplateAttrs, $template;
content = denormalizeTemplate(content);
if (replace) {
$template = jqLite('<div>' + trim(content) + '</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw new Error(MULTI_ROOT_TEMPLATE_ERROR + content);
}
tempTemplateAttrs = {$attr: {}};
replaceWith($rootElement, $compileNode, compileNode);
collectDirectives(compileNode, directives, tempTemplateAttrs);
mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
} else {
compileNode = beforeTemplateCompileNode;
$compileNode.html(content);
}
directives.unshift(derivedSyncDirective);
afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs, childTranscludeFn);
afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
while(linkQueue.length) {
var controller = linkQueue.pop(),
linkRootElement = linkQueue.pop(),
beforeTemplateLinkNode = linkQueue.pop(),
scope = linkQueue.pop(),
linkNode = compileNode;
if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
// it was cloned therefore we have to clone as well.
linkNode = JQLiteClone(compileNode);
replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
}
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement, controller);
}, scope, linkNode, $rootElement, controller);
}
linkQueue = null;
}).
error(function(response, code, headers, config) {
throw Error('Failed to load template: ' + config.url);
});
return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) {
if (linkQueue) {
linkQueue.push(scope);
linkQueue.push(node);
linkQueue.push(rootElement);
linkQueue.push(controller);
} else {
afterTemplateNodeLinkFn(function() {
beforeTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller);
}, scope, node, rootElement, controller);
}
};
}
/**
* Sorting function for bound directives.
*/
function byPriority(a, b) {
return b.priority - a.priority;
}
function assertNoDuplicate(what, previousDirective, directive, element) {
if (previousDirective) {
throw Error('Multiple directives [' + previousDirective.name + ', ' +
directive.name + '] asking for ' + what + ' on: ' + startingTag(element));
}
}
function addTextInterpolateDirective(directives, text) {
var interpolateFn = $interpolate(text, true);
if (interpolateFn) {
directives.push({
priority: 0,
compile: valueFn(function textInterpolateLinkFn(scope, node) {
var parent = node.parent(),
bindings = parent.data('$binding') || [];
bindings.push(interpolateFn);
safeAddClass(parent.data('$binding', bindings), 'ng-binding');
scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
node[0].nodeValue = value;
});
})
});
}
}
function addAttrInterpolateDirective(node, directives, value, name) {
var interpolateFn = $interpolate(value, true);
// no interpolation found -> ignore
if (!interpolateFn) return;
directives.push({
priority: 100,
compile: valueFn(function attrInterpolateLinkFn(scope, element, attr) {
var $$observers = (attr.$$observers || (attr.$$observers = {}));
if (name === 'class') {
// we need to interpolate classes again, in the case the element was replaced
// and therefore the two class attrs got merged - we want to interpolate the result
interpolateFn = $interpolate(attr[name], true);
}
attr[name] = undefined;
($$observers[name] || ($$observers[name] = [])).$$inter = true;
(attr.$$observers && attr.$$observers[name].$$scope || scope).
$watch(interpolateFn, function interpolateFnWatchAction(value) {
attr.$set(name, value);
});
})
});
}
/**
* This is a special jqLite.replaceWith, which can replace items which
* have no parents, provided that the containing jqLite collection is provided.
*
* @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
* in the root of the tree.
* @param {JqLite} $element The jqLite element which we are going to replace. We keep the shell,
* but replace its DOM node reference.
* @param {Node} newNode The new DOM node.
*/
function replaceWith($rootElement, $element, newNode) {
var oldNode = $element[0],
parent = oldNode.parentNode,
i, ii;
if ($rootElement) {
for(i = 0, ii = $rootElement.length; i < ii; i++) {
if ($rootElement[i] == oldNode) {
$rootElement[i] = newNode;
break;
}
}
}
if (parent) {
parent.replaceChild(newNode, oldNode);
}
newNode[jqLite.expando] = oldNode[jqLite.expando];
$element[0] = newNode;
}
}];
}
var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
/**
* Converts all accepted directives format into proper directive name.
* All of these will become 'myDirective':
* my:DiRective
* my-directive
* x-my-directive
* data-my:directive
*
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return camelCase(name.replace(PREFIX_REGEXP, ''));
}
/**
* @ngdoc object
* @name ng.$compile.directive.Attributes
* @description
*
* A shared object between directive compile / linking functions which contains normalized DOM element
* attributes. The the values reflect current binding state `{{ }}`. The normalization is needed
* since all of these are treated as equivalent in Angular:
*
* <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
*/
/**
* @ngdoc property
* @name ng.$compile.directive.Attributes#$attr
* @propertyOf ng.$compile.directive.Attributes
* @returns {object} A map of DOM element attribute names to the normalized name. This is
* needed to do reverse lookup from normalized name back to actual name.
*/
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$set
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Set DOM element attribute value.
*
*
* @param {string} name Normalized element attribute name of the property to modify. The name is
* revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
* property to the original name.
* @param {string} value Value to set the attribute to.
*/
/**
* Closure compiler type information
*/
function nodesetLinkingFn(
/* angular.Scope */ scope,
/* NodeList */ nodeList,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
function directiveLinkingFn(
/* nodesetLinkingFn */ nodesetLinkingFn,
/* angular.Scope */ scope,
/* Node */ node,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
/**
* @ngdoc object
* @name ng.$controllerProvider
* @description
* The {@link ng.$controller $controller service} is used by Angular to create new
* controllers.
*
* This provider allows controller registration via the
* {@link ng.$controllerProvider#register register} method.
*/
function $ControllerProvider() {
var controllers = {};
/**
* @ngdoc function
* @name ng.$controllerProvider#register
* @methodOf ng.$controllerProvider
* @param {string} name Controller name
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
* annotations in the array notation).
*/
this.register = function(name, constructor) {
if (isObject(name)) {
extend(controllers, name)
} else {
controllers[name] = constructor;
}
};
this.$get = ['$injector', '$window', function($injector, $window) {
/**
* @ngdoc function
* @name ng.$controller
* @requires $injector
*
* @param {Function|string} constructor If called with a function then it's considered to be the
* controller constructor function. Otherwise it's considered to be a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$controllerProvider`
* * check if evaluating the string on the current scope returns a constructor
* * check `window[constructor]` on the global `window` object
*
* @param {Object} locals Injection locals for Controller.
* @return {Object} Instance of given controller.
*
* @description
* `$controller` service is responsible for instantiating controllers.
*
* It's just a simple call to {@link AUTO.$injector $injector}, but extracted into
* a service, so that one can override this service with {@link https://gist.github.com/1649788
* BC version}.
*/
return function(constructor, locals) {
if(isString(constructor)) {
var name = constructor;
constructor = controllers.hasOwnProperty(name)
? controllers[name]
: getter(locals.$scope, name, true) || getter($window, name, true);
assertArgFn(constructor, name, true);
}
return $injector.instantiate(constructor, locals);
};
}];
}
/**
* @ngdoc object
* @name ng.$document
* @requires $window
*
* @description
* A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
* element.
*/
function $DocumentProvider(){
this.$get = ['$window', function(window){
return jqLite(window.document);
}];
}
/**
* @ngdoc function
* @name ng.$exceptionHandler
* @requires $log
*
* @description
* Any uncaught exception in angular expressions is delegated to this service.
* The default implementation simply delegates to `$log.error` which logs it into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
* {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
*
* @param {Error} exception Exception associated with the error.
* @param {string=} cause optional information about the context in which
* the error was thrown.
*
*/
function $ExceptionHandlerProvider() {
this.$get = ['$log', function($log) {
return function(exception, cause) {
$log.error.apply($log, arguments);
};
}];
}
/**
* @ngdoc object
* @name ng.$interpolateProvider
* @function
*
* @description
*
* Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
*/
function $InterpolateProvider() {
var startSymbol = '{{';
var endSymbol = '}}';
/**
* @ngdoc method
* @name ng.$interpolateProvider#startSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
*
* @param {string=} value new value to set the starting symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.startSymbol = function(value){
if (value) {
startSymbol = value;
return this;
} else {
return startSymbol;
}
};
/**
* @ngdoc method
* @name ng.$interpolateProvider#endSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* @param {string=} value new value to set the ending symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.endSymbol = function(value){
if (value) {
endSymbol = value;
return this;
} else {
return endSymbol;
}
};
this.$get = ['$parse', function($parse) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length;
/**
* @ngdoc function
* @name ng.$interpolate
* @function
*
* @requires $parse
*
* @description
*
* Compiles a string with markup into an interpolation function. This service is used by the
* HTML {@link ng.$compile $compile} service for data binding. See
* {@link ng.$interpolateProvider $interpolateProvider} for configuring the
* interpolation markup.
*
*
<pre>
var $interpolate = ...; // injected
var exp = $interpolate('Hello {{name}}!');
expect(exp({name:'Angular'}).toEqual('Hello Angular!');
</pre>
*
*
* @param {string} text The text with markup to interpolate.
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
* embedded expression in order to return an interpolation function. Strings with no
* embedded expression will return null for the interpolation function.
* @returns {function(context)} an interpolation function which is used to compute the interpolated
* string. The function has these parameters:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against.
*
*/
function $interpolate(text, mustHaveExpression) {
var startIndex,
endIndex,
index = 0,
parts = [],
length = text.length,
hasInterpolation = false,
fn,
exp,
concat = [];
while(index < length) {
if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
(index != startIndex) && parts.push(text.substring(index, startIndex));
parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
fn.exp = exp;
index = endIndex + endSymbolLength;
hasInterpolation = true;
} else {
// we did not find anything, so we have to add the remainder to the parts array
(index != length) && parts.push(text.substring(index));
index = length;
}
}
if (!(length = parts.length)) {
// we added, nothing, must have been an empty string.
parts.push('');
length = 1;
}
if (!mustHaveExpression || hasInterpolation) {
concat.length = length;
fn = function(context) {
for(var i = 0, ii = length, part; i<ii; i++) {
if (typeof (part = parts[i]) == 'function') {
part = part(context);
if (part == null || part == undefined) {
part = '';
} else if (typeof part != 'string') {
part = toJson(part);
}
}
concat[i] = part;
}
return concat.join('');
};
fn.exp = text;
fn.parts = parts;
return fn;
}
}
/**
* @ngdoc method
* @name ng.$interpolate#startSymbol
* @methodOf ng.$interpolate
* @description
* Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
*
* Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
* the symbol.
*
* @returns {string} start symbol.
*/
$interpolate.startSymbol = function() {
return startSymbol;
}
/**
* @ngdoc method
* @name ng.$interpolate#endSymbol
* @methodOf ng.$interpolate
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change
* the symbol.
*
* @returns {string} start symbol.
*/
$interpolate.endSymbol = function() {
return endSymbol;
}
return $interpolate;
}];
}
var URL_MATCH = /^([^:]+):\/\/(\w+:{0,1}\w*@)?(\{?[\w\.-]*\}?)(:([0-9]+))?(\/[^\?#]*)?(\?([^#]*))?(#(.*))?$/,
PATH_MATCH = /^([^\?#]*)?(\?([^#]*))?(#(.*))?$/,
HASH_MATCH = PATH_MATCH,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
/**
* Encode path using encodeUriSegment, ignoring forward slashes
*
* @param {string} path Path to encode
* @returns {string}
*/
function encodePath(path) {
var segments = path.split('/'),
i = segments.length;
while (i--) {
segments[i] = encodeUriSegment(segments[i]);
}
return segments.join('/');
}
function stripHash(url) {
return url.split('#')[0];
}
function matchUrl(url, obj) {
var match = URL_MATCH.exec(url);
match = {
protocol: match[1],
host: match[3],
port: int(match[5]) || DEFAULT_PORTS[match[1]] || null,
path: match[6] || '/',
search: match[8],
hash: match[10]
};
if (obj) {
obj.$$protocol = match.protocol;
obj.$$host = match.host;
obj.$$port = match.port;
}
return match;
}
function composeProtocolHostPort(protocol, host, port) {
return protocol + '://' + host + (port == DEFAULT_PORTS[protocol] ? '' : ':' + port);
}
function pathPrefixFromBase(basePath) {
return basePath.substr(0, basePath.lastIndexOf('/'));
}
function convertToHtml5Url(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already html5 url
if (decodeURIComponent(match.path) != basePath || isUndefined(match.hash) ||
match.hash.indexOf(hashPrefix) !== 0) {
return url;
// convert hashbang url -> html5 url
} else {
return composeProtocolHostPort(match.protocol, match.host, match.port) +
pathPrefixFromBase(basePath) + match.hash.substr(hashPrefix.length);
}
}
function convertToHashbangUrl(url, basePath, hashPrefix) {
var match = matchUrl(url);
// already hashbang url
if (decodeURIComponent(match.path) == basePath && !isUndefined(match.hash) &&
match.hash.indexOf(hashPrefix) === 0) {
return url;
// convert html5 url -> hashbang url
} else {
var search = match.search && '?' + match.search || '',
hash = match.hash && '#' + match.hash || '',
pathPrefix = pathPrefixFromBase(basePath),
path = match.path.substr(pathPrefix.length);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing path prefix "' + pathPrefix + '" !');
}
return composeProtocolHostPort(match.protocol, match.host, match.port) + basePath +
'#' + hashPrefix + path + search + hash;
}
}
/**
* LocationUrl represents an url
* This object is exposed as $location service when HTML5 mode is enabled and supported
*
* @constructor
* @param {string} url HTML5 url
* @param {string} pathPrefix
*/
function LocationUrl(url, pathPrefix, appBaseUrl) {
pathPrefix = pathPrefix || '';
/**
* Parse given html5 (regular) url string into properties
* @param {string} newAbsoluteUrl HTML5 url
* @private
*/
this.$$parse = function(newAbsoluteUrl) {
var match = matchUrl(newAbsoluteUrl, this);
if (match.path.indexOf(pathPrefix) !== 0) {
throw Error('Invalid url "' + newAbsoluteUrl + '", missing path prefix "' + pathPrefix + '" !');
}
this.$$path = decodeURIComponent(match.path.substr(pathPrefix.length));
this.$$search = parseKeyValue(match.search);
this.$$hash = match.hash && decodeURIComponent(match.hash) || '';
this.$$compose();
};
/**
* Compose url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
pathPrefix + this.$$url;
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is disabled or not supported
*
* @constructor
* @param {string} url Legacy url
* @param {string} hashPrefix Prefix for hash part (containing path and search)
*/
function LocationHashbangUrl(url, hashPrefix, appBaseUrl) {
var basePath;
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse = function(url) {
var match = matchUrl(url, this);
if (match.hash && match.hash.indexOf(hashPrefix) !== 0) {
throw Error('Invalid url "' + url + '", missing hash prefix "' + hashPrefix + '" !');
}
basePath = match.path + (match.search ? '?' + match.search : '');
match = HASH_MATCH.exec((match.hash || '').substr(hashPrefix.length));
if (match[1]) {
this.$$path = (match[1].charAt(0) == '/' ? '' : '/') + decodeURIComponent(match[1]);
} else {
this.$$path = '';
}
this.$$search = parseKeyValue(match[3]);
this.$$hash = match[5] && decodeURIComponent(match[5]) || '';
this.$$compose();
};
/**
* Compose hashbang url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = composeProtocolHostPort(this.$$protocol, this.$$host, this.$$port) +
basePath + (this.$$url ? '#' + hashPrefix + this.$$url : '');
};
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if(absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return absoluteLinkUrl;
}
}
this.$$parse(url);
}
LocationUrl.prototype = {
/**
* Has any change been replacing ?
* @private
*/
$$replace: false,
/**
* @ngdoc method
* @name ng.$location#absUrl
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return full url representation with all segments encoded according to rules specified in
* {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
*
* @return {string} full url
*/
absUrl: locationGetter('$$absUrl'),
/**
* @ngdoc method
* @name ng.$location#url
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return url (e.g. `/path?a=b#hash`) when called without any parameter.
*
* Change path, search and hash, when called with parameter and return `$location`.
*
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
* @return {string} url
*/
url: function(url, replace) {
if (isUndefined(url))
return this.$$url;
var match = PATH_MATCH.exec(url);
if (match[1]) this.path(decodeURIComponent(match[1]));
if (match[2] || match[1]) this.search(match[3] || '');
this.hash(match[5] || '', replace);
return this;
},
/**
* @ngdoc method
* @name ng.$location#protocol
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return protocol of current url.
*
* @return {string} protocol of current url
*/
protocol: locationGetter('$$protocol'),
/**
* @ngdoc method
* @name ng.$location#host
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return host of current url.
*
* @return {string} host of current url.
*/
host: locationGetter('$$host'),
/**
* @ngdoc method
* @name ng.$location#port
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return port of current url.
*
* @return {Number} port
*/
port: locationGetter('$$port'),
/**
* @ngdoc method
* @name ng.$location#path
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return path of current url when called without any parameter.
*
* Change path when called with parameter and return `$location`.
*
* Note: Path should always begin with forward slash (/), this method will add the forward slash
* if it is missing.
*
* @param {string=} path New path
* @return {string} path
*/
path: locationGetterSetter('$$path', function(path) {
return path.charAt(0) == '/' ? path : '/' + path;
}),
/**
* @ngdoc method
* @name ng.$location#search
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return search part (as object) of current url when called without any parameter.
*
* Change search part when called with parameter and return `$location`.
*
* @param {string|object<string,string>=} search New search params - string or hash object
* @param {string=} paramValue If `search` is a string, then `paramValue` will override only a
* single search parameter. If the value is `null`, the parameter will be deleted.
*
* @return {string} search
*/
search: function(search, paramValue) {
if (isUndefined(search))
return this.$$search;
if (isDefined(paramValue)) {
if (paramValue === null) {
delete this.$$search[search];
} else {
this.$$search[search] = paramValue;
}
} else {
this.$$search = isString(search) ? parseKeyValue(search) : search;
}
this.$$compose();
return this;
},
/**
* @ngdoc method
* @name ng.$location#hash
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return hash fragment when called without any parameter.
*
* Change hash fragment when called with parameter and return `$location`.
*
* @param {string=} hash New hash fragment
* @return {string} hash
*/
hash: locationGetterSetter('$$hash', identity),
/**
* @ngdoc method
* @name ng.$location#replace
* @methodOf ng.$location
*
* @description
* If called, all changes to $location during current `$digest` will be replacing current history
* record, instead of adding new one.
*/
replace: function() {
this.$$replace = true;
return this;
}
};
LocationHashbangUrl.prototype = inherit(LocationUrl.prototype);
function LocationHashbangInHtml5Url(url, hashPrefix, appBaseUrl, baseExtra) {
LocationHashbangUrl.apply(this, arguments);
this.$$rewriteAppUrl = function(absoluteLinkUrl) {
if (absoluteLinkUrl.indexOf(appBaseUrl) == 0) {
return appBaseUrl + baseExtra + '#' + hashPrefix + absoluteLinkUrl.substr(appBaseUrl.length);
}
}
}
LocationHashbangInHtml5Url.prototype = inherit(LocationHashbangUrl.prototype);
function locationGetter(property) {
return function() {
return this[property];
};
}
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value))
return this[property];
this[property] = preprocess(value);
this.$$compose();
return this;
};
}
/**
* @ngdoc object
* @name ng.$location
*
* @requires $browser
* @requires $sniffer
* @requires $rootElement
*
* @description
* The $location service parses the URL in the browser address bar (based on the
* {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
* available to your application. Changes to the URL in the address bar are reflected into
* $location service and changes to $location are reflected into the browser address bar.
*
* **The $location service:**
*
* - Exposes the current URL in the browser address bar, so you can
* - Watch and observe the URL.
* - Change the URL.
* - Synchronizes the URL with the browser when the user
* - Changes the address bar.
* - Clicks the back or forward button (or clicks a History link).
* - Clicks on a link.
* - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
*
* For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
* Services: Using $location}
*/
/**
* @ngdoc object
* @name ng.$locationProvider
* @description
* Use the `$locationProvider` to configure how the application deep linking paths are stored.
*/
function $LocationProvider(){
var hashPrefix = '',
html5Mode = false;
/**
* @ngdoc property
* @name ng.$locationProvider#hashPrefix
* @methodOf ng.$locationProvider
* @description
* @param {string=} prefix Prefix for hash part (containing path and search)
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.hashPrefix = function(prefix) {
if (isDefined(prefix)) {
hashPrefix = prefix;
return this;
} else {
return hashPrefix;
}
};
/**
* @ngdoc property
* @name ng.$locationProvider#html5Mode
* @methodOf ng.$locationProvider
* @description
* @param {string=} mode Use HTML5 strategy if available.
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.html5Mode = function(mode) {
if (isDefined(mode)) {
html5Mode = mode;
return this;
} else {
return html5Mode;
}
};
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
function( $rootScope, $browser, $sniffer, $rootElement) {
var $location,
basePath,
pathPrefix,
initUrl = $browser.url(),
initUrlParts = matchUrl(initUrl),
appBaseUrl;
if (html5Mode) {
basePath = $browser.baseHref() || '/';
pathPrefix = pathPrefixFromBase(basePath);
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
pathPrefix + '/';
if ($sniffer.history) {
$location = new LocationUrl(
convertToHtml5Url(initUrl, basePath, hashPrefix),
pathPrefix, appBaseUrl);
} else {
$location = new LocationHashbangInHtml5Url(
convertToHashbangUrl(initUrl, basePath, hashPrefix),
hashPrefix, appBaseUrl, basePath.substr(pathPrefix.length + 1));
}
} else {
appBaseUrl =
composeProtocolHostPort(initUrlParts.protocol, initUrlParts.host, initUrlParts.port) +
(initUrlParts.path || '') +
(initUrlParts.search ? ('?' + initUrlParts.search) : '') +
'#' + hashPrefix + '/';
$location = new LocationHashbangUrl(initUrl, hashPrefix, appBaseUrl);
}
$rootElement.bind('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
// currently we open nice url link and redirect then
if (event.ctrlKey || event.metaKey || event.which == 2) return;
var elm = jqLite(event.target);
// traverse the DOM up to find first A tag
while (lowercase(elm[0].nodeName) !== 'a') {
// ignore rewriting if no A tag (reached root element, or no parent - removed from document)
if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
}
var absHref = elm.prop('href'),
rewrittenUrl = $location.$$rewriteAppUrl(absHref);
if (absHref && !elm.attr('target') && rewrittenUrl) {
// update location manually
$location.$$parse(rewrittenUrl);
$rootScope.$apply();
event.preventDefault();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
window.angular['ff-684208-preventDefault'] = true;
}
});
// rewrite hashbang url <> html5 url
if ($location.absUrl() != initUrl) {
$browser.url($location.absUrl(), true);
}
// update $location when $browser url changes
$browser.onUrlChange(function(newUrl) {
if ($location.absUrl() != newUrl) {
if ($rootScope.$broadcast('$locationChangeStart', newUrl, $location.absUrl()).defaultPrevented) {
$browser.url($location.absUrl());
return;
}
$rootScope.$evalAsync(function() {
var oldUrl = $location.absUrl();
$location.$$parse(newUrl);
afterLocationChange(oldUrl);
});
if (!$rootScope.$$phase) $rootScope.$digest();
}
});
// update browser
var changeCounter = 0;
$rootScope.$watch(function $locationWatch() {
var oldUrl = $browser.url();
var currentReplace = $location.$$replace;
if (!changeCounter || oldUrl != $location.absUrl()) {
changeCounter++;
$rootScope.$evalAsync(function() {
if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
defaultPrevented) {
$location.$$parse(oldUrl);
} else {
$browser.url($location.absUrl(), currentReplace);
afterLocationChange(oldUrl);
}
});
}
$location.$$replace = false;
return changeCounter;
});
return $location;
function afterLocationChange(oldUrl) {
$rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
}
}];
}
/**
* @ngdoc object
* @name ng.$log
* @requires $window
*
* @description
* Simple service for logging. Default implementation writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troubleshooting.
*
* @example
<example>
<file name="script.js">
function LogCtrl($scope, $log) {
$scope.$log = $log;
$scope.message = 'Hello World!';
}
</file>
<file name="index.html">
<div ng-controller="LogCtrl">
<p>Reload this page with open console, enter text and hit the log button...</p>
Message:
<input type="text" ng-model="message"/>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
<button ng-click="$log.info(message)">info</button>
<button ng-click="$log.error(message)">error</button>
</div>
</file>
</example>
*/
function $LogProvider(){
this.$get = ['$window', function($window){
return {
/**
* @ngdoc method
* @name ng.$log#log
* @methodOf ng.$log
*
* @description
* Write a log message
*/
log: consoleLog('log'),
/**
* @ngdoc method
* @name ng.$log#warn
* @methodOf ng.$log
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @ngdoc method
* @name ng.$log#info
* @methodOf ng.$log
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @ngdoc method
* @name ng.$log#error
* @methodOf ng.$log
*
* @description
* Write an error message
*/
error: consoleLog('error')
};
function formatError(arg) {
if (arg instanceof Error) {
if (arg.stack) {
arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
? 'Error: ' + arg.message + '\n' + arg.stack
: arg.stack;
} else if (arg.sourceURL) {
arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
}
}
return arg;
}
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop;
if (logFn.apply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args);
};
}
// we are IE which either doesn't have window.console => this is noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at least first 2 args
return function(arg1, arg2) {
logFn(arg1, arg2);
}
}
}];
}
var OPERATORS = {
'null':function(){return null;},
'true':function(){return true;},
'false':function(){return false;},
undefined:noop,
'+':function(self, locals, a,b){
a=a(self, locals); b=b(self, locals);
if (isDefined(a)) {
if (isDefined(b)) {
return a + b;
}
return a;
}
return isDefined(b)?b:undefined;},
'-':function(self, locals, a,b){a=a(self, locals); b=b(self, locals); return (isDefined(a)?a:0)-(isDefined(b)?b:0);},
'*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
'/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
'%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
'^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
'=':noop,
'==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
'!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
'<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
'>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
'<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
'>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
'&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
'||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
'&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
// '|':function(self, locals, a,b){return a|b;},
'|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
'!':function(self, locals, a){return !a(self, locals);}
};
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
function lex(text, csp){
var tokens = [],
token,
index = 0,
json = [],
ch,
lastCh = ':'; // can start regexp
while (index < text.length) {
ch = text.charAt(index);
if (is('"\'')) {
readString(ch);
} else if (isNumber(ch) || is('.') && isNumber(peek())) {
readNumber();
} else if (isIdent(ch)) {
readIdent();
// identifiers can only be if the preceding char was a { or ,
if (was('{,') && json[0]=='{' &&
(token=tokens[tokens.length-1])) {
token.json = token.text.indexOf('.') == -1;
}
} else if (is('(){}[].,;:')) {
tokens.push({
index:index,
text:ch,
json:(was(':[,') && is('{[')) || is('}]:,')
});
if (is('{[')) json.unshift(ch);
if (is('}]')) json.shift();
index++;
} else if (isWhitespace(ch)) {
index++;
continue;
} else {
var ch2 = ch + peek(),
fn = OPERATORS[ch],
fn2 = OPERATORS[ch2];
if (fn2) {
tokens.push({index:index, text:ch2, fn:fn2});
index += 2;
} else if (fn) {
tokens.push({index:index, text:ch, fn:fn, json: was('[,:') && is('+-')});
index += 1;
} else {
throwError("Unexpected next character ", index, index+1);
}
}
lastCh = ch;
}
return tokens;
function is(chars) {
return chars.indexOf(ch) != -1;
}
function was(chars) {
return chars.indexOf(lastCh) != -1;
}
function peek() {
return index + 1 < text.length ? text.charAt(index + 1) : false;
}
function isNumber(ch) {
return '0' <= ch && ch <= '9';
}
function isWhitespace(ch) {
return ch == ' ' || ch == '\r' || ch == '\t' ||
ch == '\n' || ch == '\v' || ch == '\u00A0'; // IE treats non-breaking space as \u00A0
}
function isIdent(ch) {
return 'a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' == ch || ch == '$';
}
function isExpOperator(ch) {
return ch == '-' || ch == '+' || isNumber(ch);
}
function throwError(error, start, end) {
end = end || index;
throw Error("Lexer Error: " + error + " at column" +
(isDefined(start)
? "s " + start + "-" + index + " [" + text.substring(start, end) + "]"
: " " + end) +
" in expression [" + text + "].");
}
function readNumber() {
var number = "";
var start = index;
while (index < text.length) {
var ch = lowercase(text.charAt(index));
if (ch == '.' || isNumber(ch)) {
number += ch;
} else {
var peekCh = peek();
if (ch == 'e' && isExpOperator(peekCh)) {
number += ch;
} else if (isExpOperator(ch) &&
peekCh && isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (isExpOperator(ch) &&
(!peekCh || !isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
throwError('Invalid exponent');
} else {
break;
}
}
index++;
}
number = 1 * number;
tokens.push({index:start, text:number, json:true,
fn:function() {return number;}});
}
function readIdent() {
var ident = "",
start = index,
lastDot, peekIndex, methodName, ch;
while (index < text.length) {
ch = text.charAt(index);
if (ch == '.' || isIdent(ch) || isNumber(ch)) {
if (ch == '.') lastDot = index;
ident += ch;
} else {
break;
}
index++;
}
//check if this is not a method invocation and if it is back out to last dot
if (lastDot) {
peekIndex = index;
while(peekIndex < text.length) {
ch = text.charAt(peekIndex);
if (ch == '(') {
methodName = ident.substr(lastDot - start + 1);
ident = ident.substr(0, lastDot - start);
index = peekIndex;
break;
}
if(isWhitespace(ch)) {
peekIndex++;
} else {
break;
}
}
}
var token = {
index:start,
text:ident
};
if (OPERATORS.hasOwnProperty(ident)) {
token.fn = token.json = OPERATORS[ident];
} else {
var getter = getterFn(ident, csp);
token.fn = extend(function(self, locals) {
return (getter(self, locals));
}, {
assign: function(self, value) {
return setter(self, ident, value);
}
});
}
tokens.push(token);
if (methodName) {
tokens.push({
index:lastDot,
text: '.',
json: false
});
tokens.push({
index: lastDot + 1,
text: methodName,
json: false
});
}
}
function readString(quote) {
var start = index;
index++;
var string = "";
var rawString = quote;
var escape = false;
while (index < text.length) {
var ch = text.charAt(index);
rawString += ch;
if (escape) {
if (ch == 'u') {
var hex = text.substring(index + 1, index + 5);
if (!hex.match(/[\da-f]{4}/i))
throwError( "Invalid unicode escape [\\u" + hex + "]");
index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
if (rep) {
string += rep;
} else {
string += ch;
}
}
escape = false;
} else if (ch == '\\') {
escape = true;
} else if (ch == quote) {
index++;
tokens.push({
index:start,
text:rawString,
string:string,
json:true,
fn:function() { return string; }
});
return;
} else {
string += ch;
}
index++;
}
throwError("Unterminated quote", start);
}
}
/////////////////////////////////////////
function parser(text, json, $filter, csp){
var ZERO = valueFn(0),
value,
tokens = lex(text, csp),
assignment = _assignment,
functionCall = _functionCall,
fieldAccess = _fieldAccess,
objectIndex = _objectIndex,
filterChain = _filterChain;
if(json){
// The extra level of aliasing is here, just in case the lexer misses something, so that
// we prevent any accidental execution in JSON.
assignment = logicalOR;
functionCall =
fieldAccess =
objectIndex =
filterChain =
function() { throwError("is not valid json", {text:text, index:0}); };
value = primary();
} else {
value = statements();
}
if (tokens.length !== 0) {
throwError("is an unexpected token", tokens[0]);
}
return value;
///////////////////////////////////
function throwError(msg, token) {
throw Error("Syntax Error: Token '" + token.text +
"' " + msg + " at column " +
(token.index + 1) + " of the expression [" +
text + "] starting at [" + text.substring(token.index) + "].");
}
function peekToken() {
if (tokens.length === 0)
throw Error("Unexpected end of expression: " + text);
return tokens[0];
}
function peek(e1, e2, e3, e4) {
if (tokens.length > 0) {
var token = tokens[0];
var t = token.text;
if (t==e1 || t==e2 || t==e3 || t==e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
}
function expect(e1, e2, e3, e4){
var token = peek(e1, e2, e3, e4);
if (token) {
if (json && !token.json) {
throwError("is not valid json", token);
}
tokens.shift();
return token;
}
return false;
}
function consume(e1){
if (!expect(e1)) {
throwError("is unexpected, expecting [" + e1 + "]", peek());
}
}
function unaryFn(fn, right) {
return function(self, locals) {
return fn(self, locals, right);
};
}
function binaryFn(left, fn, right) {
return function(self, locals) {
return fn(self, locals, left, right);
};
}
function statements() {
var statements = [];
while(true) {
if (tokens.length > 0 && !peek('}', ')', ';', ']'))
statements.push(filterChain());
if (!expect(';')) {
// optimize for the common case where there is only one statement.
// TODO(size): maybe we should not support multiple statements?
return statements.length == 1
? statements[0]
: function(self, locals){
var value;
for ( var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (statement)
value = statement(self, locals);
}
return value;
};
}
}
}
function _filterChain() {
var left = expression();
var token;
while(true) {
if ((token = expect('|'))) {
left = binaryFn(left, token.fn, filter());
} else {
return left;
}
}
}
function filter() {
var token = expect();
var fn = $filter(token.text);
var argsFn = [];
while(true) {
if ((token = expect(':'))) {
argsFn.push(expression());
} else {
var fnInvoke = function(self, locals, input){
var args = [input];
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
return fn.apply(self, args);
};
return function() {
return fnInvoke;
};
}
}
}
function expression() {
return assignment();
}
function _assignment() {
var left = logicalOR();
var right;
var token;
if ((token = expect('='))) {
if (!left.assign) {
throwError("implies assignment but [" +
text.substring(0, token.index) + "] can not be assigned to", token);
}
right = logicalOR();
return function(scope, locals){
return left.assign(scope, right(scope, locals), locals);
};
} else {
return left;
}
}
function logicalOR() {
var left = logicalAND();
var token;
while(true) {
if ((token = expect('||'))) {
left = binaryFn(left, token.fn, logicalAND());
} else {
return left;
}
}
}
function logicalAND() {
var left = equality();
var token;
if ((token = expect('&&'))) {
left = binaryFn(left, token.fn, logicalAND());
}
return left;
}
function equality() {
var left = relational();
var token;
if ((token = expect('==','!='))) {
left = binaryFn(left, token.fn, equality());
}
return left;
}
function relational() {
var left = additive();
var token;
if ((token = expect('<', '>', '<=', '>='))) {
left = binaryFn(left, token.fn, relational());
}
return left;
}
function additive() {
var left = multiplicative();
var token;
while ((token = expect('+','-'))) {
left = binaryFn(left, token.fn, multiplicative());
}
return left;
}
function multiplicative() {
var left = unary();
var token;
while ((token = expect('*','/','%'))) {
left = binaryFn(left, token.fn, unary());
}
return left;
}
function unary() {
var token;
if (expect('+')) {
return primary();
} else if ((token = expect('-'))) {
return binaryFn(ZERO, token.fn, unary());
} else if ((token = expect('!'))) {
return unaryFn(token.fn, unary());
} else {
return primary();
}
}
function primary() {
var primary;
if (expect('(')) {
primary = filterChain();
consume(')');
} else if (expect('[')) {
primary = arrayDeclaration();
} else if (expect('{')) {
primary = object();
} else {
var token = expect();
primary = token.fn;
if (!primary) {
throwError("not a primary expression", token);
}
}
var next, context;
while ((next = expect('(', '[', '.'))) {
if (next.text === '(') {
primary = functionCall(primary, context);
context = null;
} else if (next.text === '[') {
context = primary;
primary = objectIndex(primary);
} else if (next.text === '.') {
context = primary;
primary = fieldAccess(primary);
} else {
throwError("IMPOSSIBLE");
}
}
return primary;
}
function _fieldAccess(object) {
var field = expect().text;
var getter = getterFn(field, csp);
return extend(
function(scope, locals, self) {
return getter(self || object(scope, locals), locals);
},
{
assign:function(scope, value, locals) {
return setter(object(scope, locals), field, value);
}
}
);
}
function _objectIndex(obj) {
var indexFn = expression();
consume(']');
return extend(
function(self, locals){
var o = obj(self, locals),
i = indexFn(self, locals),
v, p;
if (!o) return undefined;
v = o[i];
if (v && v.then) {
p = v;
if (!('$$v' in v)) {
p.$$v = undefined;
p.then(function(val) { p.$$v = val; });
}
v = v.$$v;
}
return v;
}, {
assign:function(self, value, locals){
return obj(self, locals)[indexFn(self, locals)] = value;
}
});
}
function _functionCall(fn, contextGetter) {
var argsFn = [];
if (peekToken().text != ')') {
do {
argsFn.push(expression());
} while (expect(','));
}
consume(')');
return function(scope, locals){
var args = [],
context = contextGetter ? contextGetter(scope, locals) : scope;
for ( var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](scope, locals));
}
var fnPtr = fn(scope, locals, context) || noop;
// IE stupidity!
return fnPtr.apply
? fnPtr.apply(context, args)
: fnPtr(args[0], args[1], args[2], args[3], args[4]);
};
}
// This is used with json array declaration
function arrayDeclaration () {
var elementFns = [];
if (peekToken().text != ']') {
do {
elementFns.push(expression());
} while (expect(','));
}
consume(']');
return function(self, locals){
var array = [];
for ( var i = 0; i < elementFns.length; i++) {
array.push(elementFns[i](self, locals));
}
return array;
};
}
function object () {
var keyValues = [];
if (peekToken().text != '}') {
do {
var token = expect(),
key = token.string || token.text;
consume(":");
var value = expression();
keyValues.push({key:key, value:value});
} while (expect(','));
}
consume('}');
return function(self, locals){
var object = {};
for ( var i = 0; i < keyValues.length; i++) {
var keyValue = keyValues[i];
object[keyValue.key] = keyValue.value(self, locals);
}
return object;
};
}
}
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
function setter(obj, path, setValue) {
var element = path.split('.');
for (var i = 0; element.length > 1; i++) {
var key = element.shift();
var propertyObj = obj[key];
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = propertyObj;
}
obj[element.shift()] = setValue;
return setValue;
}
/**
* Return the value accesible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {string} path path to traverse
* @param {boolean=true} bindFnToScope
* @returns value as accesbile by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
var getterFnCache = {};
/**
* Implementation of the "Black Hole" variant from:
* - http://jsperf.com/angularjs-parse-getter/4
* - http://jsperf.com/path-evaluation-simplified/7
*/
function cspSafeGetterFn(key0, key1, key2, key3, key4) {
return function(scope, locals) {
var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
promise;
if (pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key0];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key1];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key2];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key3];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key4];
if (pathVal && pathVal.then) {
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
return pathVal;
};
}
function getterFn(path, csp) {
if (getterFnCache.hasOwnProperty(path)) {
return getterFnCache[path];
}
var pathKeys = path.split('.'),
pathKeysLength = pathKeys.length,
fn;
if (csp) {
fn = (pathKeysLength < 6)
? cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4])
: function(scope, locals) {
var i = 0, val;
do {
val = cspSafeGetterFn(
pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++]
)(scope, locals);
locals = undefined; // clear after first iteration
scope = val;
} while (i < pathKeysLength);
return val;
}
} else {
var code = 'var l, fn, p;\n';
forEach(pathKeys, function(key, index) {
code += 'if(s === null || s === undefined) return s;\n' +
'l=s;\n' +
's='+ (index
// we simply dereference 's' on any .dot notation
? 's'
// but if we are first then we check locals first, and if so read it first
: '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
'if (s && s.then) {\n' +
' if (!("$$v" in s)) {\n' +
' p=s;\n' +
' p.$$v = undefined;\n' +
' p.then(function(v) {p.$$v=v;});\n' +
'}\n' +
' s=s.$$v\n' +
'}\n';
});
code += 'return s;';
fn = Function('s', 'k', code); // s=scope, k=locals
fn.toString = function() { return code; };
}
return getterFnCache[path] = fn;
}
///////////////////////////////////
/**
* @ngdoc function
* @name ng.$parse
* @function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* <pre>
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* </pre>
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (tipically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*
* The return function also has an `assign` property, if the expression is assignable, which
* allows one to set values to expressions.
*
*/
function $ParseProvider() {
var cache = {};
this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
return function(exp) {
switch(typeof exp) {
case 'string':
return cache.hasOwnProperty(exp)
? cache[exp]
: cache[exp] = parser(exp, false, $filter, $sniffer.csp);
case 'function':
return exp;
default:
return noop;
}
};
}];
}
/**
* @ngdoc service
* @name ng.$q
* @requires $rootScope
*
* @description
* A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
*
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
* interface for interacting with an object that represents the result of an action that is
* performed asynchronously, and may or may not be finished at any given point in time.
*
* From the perspective of dealing with error handling, deferred and promise APIs are to
* asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
*
* <pre>
* // for the purpose of this example let's assume that variables `$q` and `scope` are
* // available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* var deferred = $q.defer();
*
* setTimeout(function() {
* // since this fn executes async in a future turn of the event loop, we need to wrap
* // our code into an $apply call so that the model changes are properly observed.
* scope.$apply(function() {
* if (okToGreet(name)) {
* deferred.resolve('Hello, ' + name + '!');
* } else {
* deferred.reject('Greeting ' + name + ' is not allowed.');
* }
* });
* }, 1000);
*
* return deferred.promise;
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* });
* </pre>
*
* At first it might not be obvious why this extra complexity is worth the trouble. The payoff
* comes in the way of
* [guarantees that promise and deferred APIs make](https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md).
*
* Additionally the promise api allows for composition that is very hard to do with the
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
* For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
* section on serial or parallel joining of promises.
*
*
* # The Deferred API
*
* A new instance of deferred is constructed by calling `$q.defer()`.
*
* The purpose of the deferred object is to expose the associated Promise instance as well as APIs
* that can be used for signaling the successful or unsuccessful completion of the task.
*
* **Methods**
*
* - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
* constructed via `$q.reject`, the promise will be rejected instead.
* - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
* resolving it with a rejection constructed via `$q.reject`.
*
* **Properties**
*
* - promise – `{Promise}` – promise object associated with this deferred.
*
*
* # The Promise API
*
* A new promise instance is created when a deferred instance is created and can be retrieved by
* calling `deferred.promise`.
*
* The purpose of the promise object is to allow for interested parties to get access to the result
* of the deferred task when it completes.
*
* **Methods**
*
* - `then(successCallback, errorCallback)` – regardless of when the promise was or will be resolved
* or rejected calls one of the success or error callbacks asynchronously as soon as the result
* is available. The callbacks are called with a single argument the result or rejection reason.
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
* `successCallback` or `errorCallback`.
*
*
* # Chaining promises
*
* Because calling `then` api of a promise returns a new derived promise, it is easily possible
* to create a chain of promises:
*
* <pre>
* promiseB = promiseA.then(function(result) {
* return result + 1;
* });
*
* // promiseB will be resolved immediately after promiseA is resolved and its value will be
* // the result of promiseA incremented by 1
* </pre>
*
* It is possible to create chains of any length and since a promise can be resolved with another
* promise (which will defer its resolution further), it is possible to pause/defer resolution of
* the promises at any point in the chain. This makes it possible to implement powerful apis like
* $http's response interceptors.
*
*
* # Differences between Kris Kowal's Q and $q
*
* There are three main differences:
*
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
* mechanism in angular, which means faster propagation of resolution or rejection into your
* models and avoiding unnecessary browser repaints, which would result in flickering UI.
* - $q promises are recognized by the templating engine in angular, which means that in templates
* you can treat promises attached to a scope as if they were the resulting values.
* - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
* all the important functionality needed for common async tasks.
*
* # Testing
*
* <pre>
* it('should simulate promise', inject(function($q, $rootScope) {
* var deferred = $q.defer();
* var promise = deferred.promise;
* var resolvedValue;
*
* promise.then(function(value) { resolvedValue = value; });
* expect(resolvedValue).toBeUndefined();
*
* // Simulate resolving of promise
* deferred.resolve(123);
* // Note that the 'then' function does not get called synchronously.
* // This is because we want the promise API to always be async, whether or not
* // it got called synchronously or asynchronously.
* expect(resolvedValue).toBeUndefined();
*
* // Propagate promise resolution to 'then' functions using $apply().
* $rootScope.$apply();
* expect(resolvedValue).toEqual(123);
* });
* </pre>
*/
function $QProvider() {
this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
return qFactory(function(callback) {
$rootScope.$evalAsync(callback);
}, $exceptionHandler);
}];
}
/**
* Constructs a promise manager.
*
* @param {function(function)} nextTick Function for executing functions in the next turn.
* @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
* debugging purposes.
* @returns {object} Promise manager.
*/
function qFactory(nextTick, exceptionHandler) {
/**
* @ngdoc
* @name ng.$q#defer
* @methodOf ng.$q
* @description
* Creates a `Deferred` object which represents a task which will finish in the future.
*
* @returns {Deferred} Returns a new instance of deferred.
*/
var defer = function() {
var pending = [],
value, deferred;
deferred = {
resolve: function(val) {
if (pending) {
var callbacks = pending;
pending = undefined;
value = ref(val);
if (callbacks.length) {
nextTick(function() {
var callback;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
callback = callbacks[i];
value.then(callback[0], callback[1]);
}
});
}
}
},
reject: function(reason) {
deferred.resolve(reject(reason));
},
promise: {
then: function(callback, errback) {
var result = defer();
var wrappedCallback = function(value) {
try {
result.resolve((callback || defaultCallback)(value));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
var wrappedErrback = function(reason) {
try {
result.resolve((errback || defaultErrback)(reason));
} catch(e) {
exceptionHandler(e);
result.reject(e);
}
};
if (pending) {
pending.push([wrappedCallback, wrappedErrback]);
} else {
value.then(wrappedCallback, wrappedErrback);
}
return result.promise;
}
}
};
return deferred;
};
var ref = function(value) {
if (value && value.then) return value;
return {
then: function(callback) {
var result = defer();
nextTick(function() {
result.resolve(callback(value));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#reject
* @methodOf ng.$q
* @description
* Creates a promise that is resolved as rejected with the specified `reason`. This api should be
* used to forward rejection in a chain of promises. If you are dealing with the last promise in
* a promise chain, you don't need to worry about it.
*
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
* `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
* a promise error callback and you want to forward the error to the promise derived from the
* current promise, you have to "rethrow" the error by returning a rejection constructed via
* `reject`.
*
* <pre>
* promiseB = promiseA.then(function(result) {
* // success: do something and resolve promiseB
* // with the old or a new result
* return result;
* }, function(reason) {
* // error: handle the error if possible and
* // resolve promiseB with newPromiseOrValue,
* // otherwise forward the rejection to promiseB
* if (canHandle(reason)) {
* // handle the error and recover
* return newPromiseOrValue;
* }
* return $q.reject(reason);
* });
* </pre>
*
* @param {*} reason Constant, message, exception or an object representing the rejection reason.
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
*/
var reject = function(reason) {
return {
then: function(callback, errback) {
var result = defer();
nextTick(function() {
result.resolve((errback || defaultErrback)(reason));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#when
* @methodOf ng.$q
* @description
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
* This is useful when you are dealing with an object that might or might not be a promise, or if
* the promise comes from a source that can't be trusted.
*
* @param {*} value Value or a promise
* @returns {Promise} Returns a promise of the passed value or promise
*/
var when = function(value, callback, errback) {
var result = defer(),
done;
var wrappedCallback = function(value) {
try {
return (callback || defaultCallback)(value);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
var wrappedErrback = function(reason) {
try {
return (errback || defaultErrback)(reason);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
nextTick(function() {
ref(value).then(function(value) {
if (done) return;
done = true;
result.resolve(ref(value).then(wrappedCallback, wrappedErrback));
}, function(reason) {
if (done) return;
done = true;
result.resolve(wrappedErrback(reason));
});
});
return result.promise;
};
function defaultCallback(value) {
return value;
}
function defaultErrback(reason) {
return reject(reason);
}
/**
* @ngdoc
* @name ng.$q#all
* @methodOf ng.$q
* @description
* Combines multiple promises into a single promise that is resolved when all of the input
* promises are resolved.
*
* @param {Array.<Promise>} promises An array of promises.
* @returns {Promise} Returns a single promise that will be resolved with an array of values,
* each value corresponding to the promise at the same index in the `promises` array. If any of
* the promises is resolved with a rejection, this resulting promise will be resolved with the
* same rejection.
*/
function all(promises) {
var deferred = defer(),
counter = promises.length,
results = [];
if (counter) {
forEach(promises, function(promise, index) {
ref(promise).then(function(value) {
if (index in results) return;
results[index] = value;
if (!(--counter)) deferred.resolve(results);
}, function(reason) {
if (index in results) return;
deferred.reject(reason);
});
});
} else {
deferred.resolve(results);
}
return deferred.promise;
}
return {
defer: defer,
reject: reject,
when: when,
all: all
};
}
/**
* @ngdoc object
* @name ng.$routeProvider
* @function
*
* @description
*
* Used for configuring routes. See {@link ng.$route $route} for an example.
*/
function $RouteProvider(){
var routes = {};
/**
* @ngdoc method
* @name ng.$routeProvider#when
* @methodOf ng.$routeProvider
*
* @param {string} path Route path (matched against `$location.path`). If `$location.path`
* contains redundant trailing slash or is missing one, the route will still match and the
* `$location.path` will be updated to add or drop the trailing slash to exactly match the
* route definition.
*
* `path` can contain named groups starting with a colon (`:name`). All characters up to the
* next slash are matched and stored in `$routeParams` under the given `name` when the route
* matches.
*
* @param {Object} route Mapping information to be assigned to `$route.current` on route
* match.
*
* Object properties:
*
* - `controller` – `{(string|function()=}` – Controller fn that should be associated with newly
* created scope or the name of a {@link angular.Module#controller registered controller}
* if passed as a string.
* - `template` – `{string=}` – html template as a string that should be used by
* {@link ng.directive:ngView ngView} or
* {@link ng.directive:ngInclude ngInclude} directives.
* this property takes precedence over `templateUrl`.
* - `templateUrl` – `{string=}` – path to an html template that should be used by
* {@link ng.directive:ngView ngView}.
* - `resolve` - `{Object.<string, function>=}` - An optional map of dependencies which should
* be injected into the controller. If any of these dependencies are promises, they will be
* resolved and converted to a value before the controller is instantiated and the
* `$routeChangeSuccess` event is fired. The map object is:
*
* - `key` – `{string}`: a name of a dependency to be injected into the controller.
* - `factory` - `{string|function}`: If `string` then it is an alias for a service.
* Otherwise if function, then it is {@link api/AUTO.$injector#invoke injected}
* and the return value is treated as the dependency. If the result is a promise, it is resolved
* before its value is injected into the controller.
*
* - `redirectTo` – {(string|function())=} – value to update
* {@link ng.$location $location} path with and trigger route redirection.
*
* If `redirectTo` is a function, it will be called with the following parameters:
*
* - `{Object.<string>}` - route parameters extracted from the current
* `$location.path()` by applying the current route templateUrl.
* - `{string}` - current `$location.path()`
* - `{Object}` - current `$location.search()`
*
* The custom `redirectTo` function is expected to return a string which will be used
* to update `$location.path()` and `$location.search()`.
*
* - `[reloadOnSearch=true]` - {boolean=} - reload route when only $location.search()
* changes.
*
* If the option is set to `false` and url in the browser changes, then
* `$routeUpdate` event is broadcasted on the root scope.
*
* @returns {Object} self
*
* @description
* Adds a new route definition to the `$route` service.
*/
this.when = function(path, route) {
routes[path] = extend({reloadOnSearch: true}, route);
// create redirection for trailing slashes
if (path) {
var redirectPath = (path[path.length-1] == '/')
? path.substr(0, path.length-1)
: path +'/';
routes[redirectPath] = {redirectTo: path};
}
return this;
};
/**
* @ngdoc method
* @name ng.$routeProvider#otherwise
* @methodOf ng.$routeProvider
*
* @description
* Sets route definition that will be used on route change when no other route definition
* is matched.
*
* @param {Object} params Mapping information to be assigned to `$route.current`.
* @returns {Object} self
*/
this.otherwise = function(params) {
this.when(null, params);
return this;
};
this.$get = ['$rootScope', '$location', '$routeParams', '$q', '$injector', '$http', '$templateCache',
function( $rootScope, $location, $routeParams, $q, $injector, $http, $templateCache) {
/**
* @ngdoc object
* @name ng.$route
* @requires $location
* @requires $routeParams
*
* @property {Object} current Reference to the current route definition.
* The route definition contains:
*
* - `controller`: The controller constructor as define in route definition.
* - `locals`: A map of locals which is used by {@link ng.$controller $controller} service for
* controller instantiation. The `locals` contain
* the resolved values of the `resolve` map. Additionally the `locals` also contain:
*
* - `$scope` - The current route scope.
* - `$template` - The current route template HTML.
*
* @property {Array.<Object>} routes Array of all configured routes.
*
* @description
* Is used for deep-linking URLs to controllers and views (HTML partials).
* It watches `$location.url()` and tries to map the path to an existing route definition.
*
* You can define routes through {@link ng.$routeProvider $routeProvider}'s API.
*
* The `$route` service is typically used in conjunction with {@link ng.directive:ngView ngView}
* directive and the {@link ng.$routeParams $routeParams} service.
*
* @example
This example shows how changing the URL hash causes the `$route` to match a route against the
URL, and the `ngView` pulls in the partial.
Note that this example is using {@link ng.directive:script inlined templates}
to get it working on jsfiddle as well.
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl,
resolve: {
// I will cause a 1 second delay
delay: function($q, $timeout) {
var delay = $q.defer();
$timeout(delay.resolve, 1000);
return delay.promise;
}
}
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
sleep(2); // promises are not part of scenario waiting
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeStart
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted before a route change. At this point the route services starts
* resolving all of the dependencies needed for the route change to occurs.
* Typically this involves fetching the view template as well as any dependencies
* defined in `resolve` route property. Once all of the dependencies are resolved
* `$routeChangeSuccess` is fired.
*
* @param {Route} next Future route information.
* @param {Route} current Current route information.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeSuccess
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted after a route dependencies are resolved.
* {@link ng.directive:ngView ngView} listens for the directive
* to instantiate the controller and render the view.
*
* @param {Object} angularEvent Synthetic event object.
* @param {Route} current Current route information.
* @param {Route|Undefined} previous Previous route information, or undefined if current is first route entered.
*/
/**
* @ngdoc event
* @name ng.$route#$routeChangeError
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
* Broadcasted if any of the resolve promises are rejected.
*
* @param {Route} current Current route information.
* @param {Route} previous Previous route information.
* @param {Route} rejection Rejection of the promise. Usually the error of the failed promise.
*/
/**
* @ngdoc event
* @name ng.$route#$routeUpdate
* @eventOf ng.$route
* @eventType broadcast on root scope
* @description
*
* The `reloadOnSearch` property has been set to false, and we are reusing the same
* instance of the Controller.
*/
var forceReload = false,
$route = {
routes: routes,
/**
* @ngdoc method
* @name ng.$route#reload
* @methodOf ng.$route
*
* @description
* Causes `$route` service to reload the current route even if
* {@link ng.$location $location} hasn't changed.
*
* As a result of that, {@link ng.directive:ngView ngView}
* creates new scope, reinstantiates the controller.
*/
reload: function() {
forceReload = true;
$rootScope.$evalAsync(updateRoute);
}
};
$rootScope.$on('$locationChangeSuccess', updateRoute);
return $route;
/////////////////////////////////////////////////////
/**
* @param on {string} current url
* @param when {string} route when template to match the url against
* @return {?Object}
*/
function switchRouteMatcher(on, when) {
// TODO(i): this code is convoluted and inefficient, we should construct the route matching
// regex only once and then reuse it
// Escape regexp special characters.
when = '^' + when.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&") + '$';
var regex = '',
params = [],
dst = {};
var re = /:(\w+)/g,
paramMatch,
lastMatchedIndex = 0;
while ((paramMatch = re.exec(when)) !== null) {
// Find each :param in `when` and replace it with a capturing group.
// Append all other sections of when unchanged.
regex += when.slice(lastMatchedIndex, paramMatch.index);
regex += '([^\\/]*)';
params.push(paramMatch[1]);
lastMatchedIndex = re.lastIndex;
}
// Append trailing path part.
regex += when.substr(lastMatchedIndex);
var match = on.match(new RegExp(regex));
if (match) {
forEach(params, function(name, index) {
dst[name] = match[index + 1];
});
}
return match ? dst : null;
}
function updateRoute() {
var next = parseRoute(),
last = $route.current;
if (next && last && next.$$route === last.$$route
&& equals(next.pathParams, last.pathParams) && !next.reloadOnSearch && !forceReload) {
last.params = next.params;
copy(last.params, $routeParams);
$rootScope.$broadcast('$routeUpdate', last);
} else if (next || last) {
forceReload = false;
$rootScope.$broadcast('$routeChangeStart', next, last);
$route.current = next;
if (next) {
if (next.redirectTo) {
if (isString(next.redirectTo)) {
$location.path(interpolate(next.redirectTo, next.params)).search(next.params)
.replace();
} else {
$location.url(next.redirectTo(next.pathParams, $location.path(), $location.search()))
.replace();
}
}
}
$q.when(next).
then(function() {
if (next) {
var keys = [],
values = [],
template;
forEach(next.resolve || {}, function(value, key) {
keys.push(key);
values.push(isString(value) ? $injector.get(value) : $injector.invoke(value));
});
if (isDefined(template = next.template)) {
} else if (isDefined(template = next.templateUrl)) {
template = $http.get(template, {cache: $templateCache}).
then(function(response) { return response.data; });
}
if (isDefined(template)) {
keys.push('$template');
values.push(template);
}
return $q.all(values).then(function(values) {
var locals = {};
forEach(values, function(value, index) {
locals[keys[index]] = value;
});
return locals;
});
}
}).
// after route change
then(function(locals) {
if (next == $route.current) {
if (next) {
next.locals = locals;
copy(next.params, $routeParams);
}
$rootScope.$broadcast('$routeChangeSuccess', next, last);
}
}, function(error) {
if (next == $route.current) {
$rootScope.$broadcast('$routeChangeError', next, last, error);
}
});
}
}
/**
* @returns the current active route, by matching it against the URL
*/
function parseRoute() {
// Match a route
var params, match;
forEach(routes, function(route, path) {
if (!match && (params = switchRouteMatcher($location.path(), path))) {
match = inherit(route, {
params: extend({}, $location.search(), params),
pathParams: params});
match.$$route = route;
}
});
// No route matched; fallback to "otherwise" route
return match || routes[null] && inherit(routes[null], {params: {}, pathParams:{}});
}
/**
* @returns interpolation of the redirect path with the parametrs
*/
function interpolate(string, params) {
var result = [];
forEach((string||'').split(':'), function(segment, i) {
if (i == 0) {
result.push(segment);
} else {
var segmentMatch = segment.match(/(\w+)(.*)/);
var key = segmentMatch[1];
result.push(params[key]);
result.push(segmentMatch[2] || '');
delete params[key];
}
});
return result.join('');
}
}];
}
/**
* @ngdoc object
* @name ng.$routeParams
* @requires $route
*
* @description
* Current set of route parameters. The route parameters are a combination of the
* {@link ng.$location $location} `search()`, and `path()`. The `path` parameters
* are extracted when the {@link ng.$route $route} path is matched.
*
* In case of parameter name collision, `path` params take precedence over `search` params.
*
* The service guarantees that the identity of the `$routeParams` object will remain unchanged
* (but its properties will likely change) even when a route change occurs.
*
* @example
* <pre>
* // Given:
* // URL: http://server.com/index.html#/Chapter/1/Section/2?search=moby
* // Route: /Chapter/:chapterId/Section/:sectionId
* //
* // Then
* $routeParams ==> {chapterId:1, sectionId:2, search:'moby'}
* </pre>
*/
function $RouteParamsProvider() {
this.$get = valueFn({});
}
/**
* DESIGN NOTES
*
* The design decisions behind the scope are heavily favored for speed and memory consumption.
*
* The typical use of scope is to watch the expressions, which most of the time return the same
* value as last time so we optimize the operation.
*
* Closures construction is expensive in terms of speed as well as memory:
* - No closures, instead use prototypical inheritance for API
* - Internal state needs to be stored on scope directly, which means that private state is
* exposed as $$____ properties
*
* Loop operations are optimized by using while(count--) { ... }
* - this means that in order to keep the same order of execution as addition we have to add
* items to the array at the beginning (shift) instead of at the end (push)
*
* Child scopes are created and removed often
* - Using an array would be slow since inserts in middle are expensive so we use linked list
*
* There are few watches then a lot of observers. This is why you don't want the observer to be
* implemented in the same way as watch. Watch requires return of initialization function which
* are expensive to construct.
*/
/**
* @ngdoc object
* @name ng.$rootScopeProvider
* @description
*
* Provider for the $rootScope service.
*/
/**
* @ngdoc function
* @name ng.$rootScopeProvider#digestTtl
* @methodOf ng.$rootScopeProvider
* @description
*
* Sets the number of digest iterations the scope should attempt to execute before giving up and
* assuming that the model is unstable.
*
* The current default is 10 iterations.
*
* @param {number} limit The number of digest iterations.
*/
/**
* @ngdoc object
* @name ng.$rootScope
* @description
*
* Every application has a single root {@link ng.$rootScope.Scope scope}.
* All other scopes are child scopes of the root scope. Scopes provide mechanism for watching the model and provide
* event processing life-cycle. See {@link guide/scope developer guide on scopes}.
*/
function $RootScopeProvider(){
var TTL = 10;
this.digestTtl = function(value) {
if (arguments.length) {
TTL = value;
}
return TTL;
};
this.$get = ['$injector', '$exceptionHandler', '$parse',
function( $injector, $exceptionHandler, $parse) {
/**
* @ngdoc function
* @name ng.$rootScope.Scope
*
* @description
* A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
* {@link AUTO.$injector $injector}. Child scopes are created using the
* {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
* compiled HTML template is executed.)
*
* Here is a simple scope snippet to show how you can interact with the scope.
* <pre>
angular.injector(['ng']).invoke(function($rootScope) {
var scope = $rootScope.$new();
scope.salutation = 'Hello';
scope.name = 'World';
expect(scope.greeting).toEqual(undefined);
scope.$watch('name', function() {
scope.greeting = scope.salutation + ' ' + scope.name + '!';
}); // initialize the watch
expect(scope.greeting).toEqual(undefined);
scope.name = 'Misko';
// still old value, since watches have not been called yet
expect(scope.greeting).toEqual(undefined);
scope.$digest(); // fire all the watches
expect(scope.greeting).toEqual('Hello Misko!');
});
* </pre>
*
* # Inheritance
* A scope can inherit from a parent scope, as in this example:
* <pre>
var parent = $rootScope;
var child = parent.$new();
parent.salutation = "Hello";
child.name = "World";
expect(child.salutation).toEqual('Hello');
child.salutation = "Welcome";
expect(child.salutation).toEqual('Welcome');
expect(parent.salutation).toEqual('Hello');
* </pre>
*
*
* @param {Object.<string, function()>=} providers Map of service factory which need to be provided
* for the current scope. Defaults to {@link ng}.
* @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
* append/override services provided by `providers`. This is handy when unit-testing and having
* the need to override a default service.
* @returns {Object} Newly created scope.
*
*/
function Scope() {
this.$id = nextUid();
this.$$phase = this.$parent = this.$$watchers =
this.$$nextSibling = this.$$prevSibling =
this.$$childHead = this.$$childTail = null;
this['this'] = this.$root = this;
this.$$destroyed = false;
this.$$asyncQueue = [];
this.$$listeners = {};
this.$$isolateBindings = {};
}
/**
* @ngdoc property
* @name ng.$rootScope.Scope#$id
* @propertyOf ng.$rootScope.Scope
* @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
* debugging.
*/
Scope.prototype = {
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$new
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Creates a new child {@link ng.$rootScope.Scope scope}.
*
* The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
* {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the scope
* hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
*
* {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is desired for
* the scope and its child scopes to be permanently detached from the parent and thus stop
* participating in model change detection and listener notification by invoking.
*
* @param {boolean} isolate if true then the scope does not prototypically inherit from the
* parent scope. The scope is isolated, as it can not see parent scope properties.
* When creating widgets it is useful for the widget to not accidentally read parent
* state.
*
* @returns {Object} The newly created child scope.
*
*/
$new: function(isolate) {
var Child,
child;
if (isFunction(isolate)) {
// TODO: remove at some point
throw Error('API-CHANGE: Use $controller to instantiate controllers.');
}
if (isolate) {
child = new Scope();
child.$root = this.$root;
} else {
Child = function() {}; // should be anonymous; This is so that when the minifier munges
// the name it does not become random set of chars. These will then show up as class
// name in the debugger.
Child.prototype = this;
child = new Child();
child.$id = nextUid();
}
child['this'] = child;
child.$$listeners = {};
child.$parent = this;
child.$$asyncQueue = [];
child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null;
child.$$prevSibling = this.$$childTail;
if (this.$$childHead) {
this.$$childTail.$$nextSibling = child;
this.$$childTail = child;
} else {
this.$$childHead = this.$$childTail = child;
}
return child;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$watch
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Registers a `listener` callback to be executed whenever the `watchExpression` changes.
*
* - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest $digest()} and
* should return the value which will be watched. (Since {@link ng.$rootScope.Scope#$digest $digest()}
* reruns when it detects changes the `watchExpression` can execute multiple times per
* {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
* - The `listener` is called only when the value from the current `watchExpression` and the
* previous call to `watchExpression` are not equal (with the exception of the initial run,
* see below). The inequality is determined according to
* {@link angular.equals} function. To save the value of the object for later comparison, the
* {@link angular.copy} function is used. It also means that watching complex options will
* have adverse memory and performance implications.
* - The watch `listener` may change the model, which may trigger other `listener`s to fire. This
* is achieved by rerunning the watchers until no changes are detected. The rerun iteration
* limit is 10 to prevent an infinite loop deadlock.
*
*
* If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
* you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
* can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a change is
* detected, be prepared for multiple calls to your listener.)
*
* After a watcher is registered with the scope, the `listener` fn is called asynchronously
* (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
* watcher. In rare cases, this is undesirable because the listener is called when the result
* of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
* can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
* listener was called due to initialization.
*
*
* # Example
* <pre>
// let's assume that scope was dependency injected as the $rootScope
var scope = $rootScope;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) { scope.counter = scope.counter + 1; });
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*
*
* @param {(function()|string)} watchExpression Expression that is evaluated on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers a
* call to the `listener`.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(scope)`: called with current `scope` as a parameter.
* @param {(function()|string)=} listener Callback called whenever the return value of
* the `watchExpression` changes.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(newValue, oldValue, scope)`: called with current and previous values as parameters.
*
* @param {boolean=} objectEquality Compare object for equality rather than for reference.
* @returns {function()} Returns a deregistration function for this listener.
*/
$watch: function(watchExp, listener, objectEquality) {
var scope = this,
get = compileToFn(watchExp, 'watch'),
array = scope.$$watchers,
watcher = {
fn: listener,
last: initWatchVal,
get: get,
exp: watchExp,
eq: !!objectEquality
};
// in the case user pass string, we need to compile it, do we really need this ?
if (!isFunction(listener)) {
var listenFn = compileToFn(listener || noop, 'listener');
watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
}
if (!array) {
array = scope.$$watchers = [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher);
return function() {
arrayRemove(array, watcher);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$digest
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and its children.
* Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change the model, the
* `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers} until no more listeners are
* firing. This means that it is possible to get into an infinite loop. This function will throw
* `'Maximum iteration limit exceeded.'` if the number of iterations exceeds 10.
*
* Usually you don't call `$digest()` directly in
* {@link ng.directive:ngController controllers} or in
* {@link ng.$compileProvider#directive directives}.
* Instead a call to {@link ng.$rootScope.Scope#$apply $apply()} (typically from within a
* {@link ng.$compileProvider#directive directives}) will force a `$digest()`.
*
* If you want to be notified whenever `$digest()` is called,
* you can register a `watchExpression` function with {@link ng.$rootScope.Scope#$watch $watch()}
* with no `listener`.
*
* You may have a need to call `$digest()` from within unit-tests, to simulate the scope
* life-cycle.
*
* # Example
* <pre>
var scope = ...;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*/
$digest: function() {
var watch, value, last,
watchers,
asyncQueue,
length,
dirty, ttl = TTL,
next, current, target = this,
watchLog = [],
logIdx, logMsg;
beginPhase('$digest');
do {
dirty = false;
current = target;
do {
asyncQueue = current.$$asyncQueue;
while(asyncQueue.length) {
try {
current.$eval(asyncQueue.shift());
} catch (e) {
$exceptionHandler(e);
}
}
if ((watchers = current.$$watchers)) {
// process our watches
length = watchers.length;
while (length--) {
try {
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if ((value = watch.get(current)) !== (last = watch.last) &&
!(watch.eq
? equals(value, last)
: (typeof value == 'number' && typeof last == 'number'
&& isNaN(value) && isNaN(last)))) {
dirty = true;
watch.last = watch.eq ? copy(value) : value;
watch.fn(value, ((last === initWatchVal) ? value : last), current);
if (ttl < 5) {
logIdx = 4 - ttl;
if (!watchLog[logIdx]) watchLog[logIdx] = [];
logMsg = (isFunction(watch.exp))
? 'fn: ' + (watch.exp.name || watch.exp.toString())
: watch.exp;
logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
watchLog[logIdx].push(logMsg);
}
}
} catch (e) {
$exceptionHandler(e);
}
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $broadcast
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
if(dirty && !(ttl--)) {
clearPhase();
throw Error(TTL + ' $digest() iterations reached. Aborting!\n' +
'Watchers fired in the last 5 iterations: ' + toJson(watchLog));
}
} while (dirty || asyncQueue.length);
clearPhase();
},
/**
* @ngdoc event
* @name ng.$rootScope.Scope#$destroy
* @eventOf ng.$rootScope.Scope
* @eventType broadcast on scope being destroyed
*
* @description
* Broadcasted when a scope and its children are being destroyed.
*/
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$destroy
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Removes the current scope (and all of its children) from the parent scope. Removal implies
* that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
* propagate to the current scope and its children. Removal also implies that the current
* scope is eligible for garbage collection.
*
* The `$destroy()` is usually used by directives such as
* {@link ng.directive:ngRepeat ngRepeat} for managing the
* unrolling of the loop.
*
* Just before a scope is destroyed a `$destroy` event is broadcasted on this scope.
* Application code can register a `$destroy` event handler that will give it chance to
* perform any necessary cleanup.
*/
$destroy: function() {
// we can't destroy the root scope or a scope that has been already destroyed
if ($rootScope == this || this.$$destroyed) return;
var parent = this.$parent;
this.$broadcast('$destroy');
this.$$destroyed = true;
if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
// This is bogus code that works around Chrome's GC leak
// see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
this.$$childTail = null;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$eval
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the `expression` on the current scope returning the result. Any exceptions in the
* expression are propagated (uncaught). This is useful when evaluating Angular expressions.
*
* # Example
* <pre>
var scope = ng.$rootScope.Scope();
scope.a = 1;
scope.b = 2;
expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
* </pre>
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$evalAsync
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the expression on the current scope at a later point in time.
*
* The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only that:
*
* - it will execute in the current script execution context (before any DOM rendering).
* - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
* `expression` execution.
*
* Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
*/
$evalAsync: function(expr) {
this.$$asyncQueue.push(expr);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$apply
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* `$apply()` is used to execute an expression in angular from outside of the angular framework.
* (For example from browser DOM events, setTimeout, XHR or third party libraries).
* Because we are calling into the angular framework we need to perform proper scope life-cycle
* of {@link ng.$exceptionHandler exception handling},
* {@link ng.$rootScope.Scope#$digest executing watches}.
*
* ## Life cycle
*
* # Pseudo-Code of `$apply()`
* <pre>
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
* </pre>
*
*
* Scope's `$apply()` method transitions through the following stages:
*
* 1. The {@link guide/expression expression} is executed using the
* {@link ng.$rootScope.Scope#$eval $eval()} method.
* 2. Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
* 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the expression
* was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
*
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$apply: function(expr) {
try {
beginPhase('$apply');
return this.$eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
clearPhase();
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$on
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for discussion of
* event life cycle.
*
* The event listener function format is: `function(event, args...)`. The `event` object
* passed into the listener has the following attributes:
*
* - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or `$broadcast`-ed.
* - `currentScope` - `{Scope}`: the current scope which is handling the event.
* - `name` - `{string}`: Name of the event.
* - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel further event
* propagation (available only for events that were `$emit`-ed).
* - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag to true.
* - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
*
* @param {string} name Event name to listen on.
* @param {function(event, args...)} listener Function to call when the event is emitted.
* @returns {function()} Returns a deregistration function for this listener.
*/
$on: function(name, listener) {
var namedListeners = this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] = namedListeners = [];
}
namedListeners.push(listener);
return function() {
namedListeners[indexOf(namedListeners, listener)] = null;
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$emit
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` upwards through the scope hierarchy notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$emit` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event traverses upwards toward the root scope and calls all registered
* listeners along the way. The event will stop propagating if one of the listeners cancels it.
*
* Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$emit: function(name, args) {
var empty = [],
namedListeners,
scope = this,
stopPropagation = false,
event = {
name: name,
targetScope: scope,
stopPropagation: function() {stopPropagation = true;},
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
i, length;
do {
namedListeners = scope.$$listeners[name] || empty;
event.currentScope = scope;
for (i=0, length=namedListeners.length; i<length; i++) {
// if listeners were deregistered, defragment the array
if (!namedListeners[i]) {
namedListeners.splice(i, 1);
i--;
length--;
continue;
}
try {
namedListeners[i].apply(null, listenerArgs);
if (stopPropagation) return event;
} catch (e) {
$exceptionHandler(e);
}
}
//traverse upwards
scope = scope.$parent;
} while (scope);
return event;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$broadcast
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` downwards to all child scopes (and their children) notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$broadcast` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get notified.
* Afterwards, the event propagates to all direct and indirect scopes of the current scope and
* calls all registered listeners along the way. The event cannot be canceled.
*
* Any exception emmited from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to broadcast.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$broadcast: function(name, args) {
var target = this,
current = target,
next = target,
event = {
name: name,
targetScope: target,
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
listeners, i, length;
//down while you can, then up and next sibling or up and next sibling until back at root
do {
current = next;
event.currentScope = current;
listeners = current.$$listeners[name] || [];
for (i=0, length = listeners.length; i<length; i++) {
// if listeners were deregistered, defragment the array
if (!listeners[i]) {
listeners.splice(i, 1);
i--;
length--;
continue;
}
try {
listeners[i].apply(null, listenerArgs);
} catch(e) {
$exceptionHandler(e);
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $digest
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
return event;
}
};
var $rootScope = new Scope();
return $rootScope;
function beginPhase(phase) {
if ($rootScope.$$phase) {
throw Error($rootScope.$$phase + ' already in progress');
}
$rootScope.$$phase = phase;
}
function clearPhase() {
$rootScope.$$phase = null;
}
function compileToFn(exp, name) {
var fn = $parse(exp);
assertArgFn(fn, name);
return fn;
}
/**
* function used as an initial value for watchers.
* because it's unique we can easily tell it apart from other values
*/
function initWatchVal() {}
}];
}
/**
* !!! This is an undocumented "private" service !!!
*
* @name ng.$sniffer
* @requires $window
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} hashchange Does the browser support hashchange event ?
*
* @description
* This is very simple implementation of testing browser's features.
*/
function $SnifferProvider() {
this.$get = ['$window', function($window) {
var eventSupport = {},
android = int((/android (\d+)/.exec(lowercase($window.navigator.userAgent)) || [])[1]);
return {
// Android has history.pushState, but it does not update location correctly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=17471
// https://github.com/angular/angular.js/issues/904
history: !!($window.history && $window.history.pushState && !(android < 4)),
hashchange: 'onhashchange' in $window &&
// IE8 compatible mode lies
(!$window.document.documentMode || $window.document.documentMode > 7),
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
// it. In particular the event is not fired when backspace or delete key are pressed or
// when cut operation is performed.
if (event == 'input' && msie == 9) return false;
if (isUndefined(eventSupport[event])) {
var divElm = $window.document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
// TODO(i): currently there is no way to feature detect CSP without triggering alerts
csp: false
};
}];
}
/**
* @ngdoc object
* @name ng.$window
*
* @description
* A reference to the browser's `window` object. While `window`
* is globally available in JavaScript, it causes testability problems, because
* it is a global variable. In angular we always refer to it through the
* `$window` service, so it may be overriden, removed or mocked for testing.
*
* All expressions are evaluated with respect to current scope so they don't
* suffer from window globality.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope, $window) {
$scope.$window = $window;
$scope.greeting = 'Hello, World!';
}
</script>
<div ng-controller="Ctrl">
<input type="text" ng-model="greeting" />
<button ng-click="$window.alert(greeting)">ALERT</button>
</div>
</doc:source>
<doc:scenario>
it('should display the greeting in the input box', function() {
input('greeting').enter('Hello, E2E Tests');
// If we click the button it will block the test runner
// element(':button').click();
});
</doc:scenario>
</doc:example>
*/
function $WindowProvider(){
this.$get = valueFn(window);
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed = {}, key, val, i;
if (!headers) return parsed;
forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
key = lowercase(trim(line.substr(0, i)));
val = trim(line.substr(i + 1));
if (key) {
if (parsed[key]) {
parsed[key] += ', ' + val;
} else {
parsed[key] = val;
}
}
});
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=)} Returns a getter function which if called with:
*
* - if called with single an argument returns a single header value or null
* - if called with no arguments returns an object containing all headers.
*/
function headersGetter(headers) {
var headersObj = isObject(headers) ? headers : undefined;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=)} headers Http headers getter fn.
* @param {(function|Array.<function>)} fns Function or an array of functions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, fns) {
if (isFunction(fns))
return fns(data, headers);
forEach(fns, function(fn) {
data = fn(data, headers);
});
return data;
}
function isSuccess(status) {
return 200 <= status && status < 300;
}
function $HttpProvider() {
var JSON_START = /^\s*(\[|\{[^\{])/,
JSON_END = /[\}\]]\s*$/,
PROTECTION_PREFIX = /^\)\]\}',?\n/;
var $config = this.defaults = {
// transform incoming response data
transformResponse: [function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
data = data.replace(PROTECTION_PREFIX, '');
if (JSON_START.test(data) && JSON_END.test(data))
data = fromJson(data, true);
}
return data;
}],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*',
'X-Requested-With': 'XMLHttpRequest'
},
post: {'Content-Type': 'application/json;charset=utf-8'},
put: {'Content-Type': 'application/json;charset=utf-8'}
}
};
var providerResponseInterceptors = this.responseInterceptors = [];
this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
var defaultCache = $cacheFactory('$http'),
responseInterceptors = [];
forEach(providerResponseInterceptors, function(interceptor) {
responseInterceptors.push(
isString(interceptor)
? $injector.get(interceptor)
: $injector.invoke(interceptor)
);
});
/**
* @ngdoc function
* @name ng.$http
* @requires $httpBackend
* @requires $browser
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates communication with the remote
* HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest
* XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}.
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngResource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
* the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
* it is important to familiarize yourself with these APIs and the guarantees they provide.
*
*
* # General usage
* The `$http` service is a function which takes a single argument — a configuration object —
* that is used to generate an HTTP request and returns a {@link ng.$q promise}
* with two $http specific methods: `success` and `error`.
*
* <pre>
* $http({method: 'GET', url: '/someUrl'}).
* success(function(data, status, headers, config) {
* // this callback will be called asynchronously
* // when the response is available
* }).
* error(function(data, status, headers, config) {
* // called asynchronously if an error occurs
* // or server returns response with an error status.
* });
* </pre>
*
* Since the returned value of calling the $http function is a `promise`, you can also use
* the `then` method to register callbacks, and these callbacks will receive a single argument –
* an object representing the response. See the API signature and type info below for more
* details.
*
* A response status code between 200 and 299 is considered a success status and
* will result in the success callback being called. Note that if the response is a redirect,
* XMLHttpRequest will transparently follow it, meaning that the error callback will not be
* called for such responses.
*
* # Shortcut methods
*
* Since all invocations of the $http service require passing in an HTTP method and URL, and
* POST/PUT requests require request data to be provided as well, shortcut methods
* were created:
*
* <pre>
* $http.get('/someUrl').success(successCallback);
* $http.post('/someUrl', data).success(successCallback);
* </pre>
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#get $http.get}
* - {@link ng.$http#head $http.head}
* - {@link ng.$http#post $http.post}
* - {@link ng.$http#put $http.put}
* - {@link ng.$http#delete $http.delete}
* - {@link ng.$http#jsonp $http.jsonp}
*
*
* # Setting HTTP Headers
*
* The $http service will automatically add certain HTTP headers to all requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, * / *`
* - `X-Requested-With: XMLHttpRequest`
* - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property from these configuration
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
* with the lowercased HTTP method name as the key, e.g.
* `$httpProvider.defaults.headers.get['My-Header']='value'`.
*
* Additionally, the defaults can be set at runtime via the `$http.defaults` object in the same
* fashion.
*
*
* # Transforming Requests and Responses
*
* Both requests and responses can be transformed using transform functions. By default, Angular
* applies these transformations:
*
* Request transformations:
*
* - If the `data` property of the request configuration object contains an object, serialize it into
* JSON format.
*
* Response transformations:
*
* - If XSRF prefix is detected, strip it (see Security Considerations section below).
* - If JSON response is detected, deserialize it using a JSON parser.
*
* To globally augment or override the default transforms, modify the `$httpProvider.defaults.transformRequest` and
* `$httpProvider.defaults.transformResponse` properties. These properties are by default an
* array of transform functions, which allows you to `push` or `unshift` a new transformation function into the
* transformation chain. You can also decide to completely override any default transformations by assigning your
* transformation functions to these properties directly without the array wrapper.
*
* Similarly, to locally override the request/response transforms, augment the `transformRequest` and/or
* `transformResponse` properties of the configuration object passed into `$http`.
*
*
* # Caching
*
* To enable caching, set the configuration property `cache` to `true`. When the cache is
* enabled, `$http` stores the response from the server in local cache. Next time the
* response is served from the cache without sending a request to the server.
*
* Note that even if the response is served from cache, delivery of the data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same URL that should be cached using the same
* cache, but the cache is not populated yet, only one request to the server will be made and
* the remaining requests will be fulfilled using the response from the first request.
*
*
* # Response interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication or any kind of synchronous or
* asynchronous preprocessing of received responses, it is desirable to be able to intercept
* responses for http requests before they are handed over to the application code that
* initiated these requests. The response interceptors leverage the {@link ng.$q
* promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
*
* The interceptors are service factories that are registered with the $httpProvider by
* adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor — a function that
* takes a {@link ng.$q promise} and returns the original or a new promise.
*
* <pre>
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return function(promise) {
* return promise.then(function(response) {
* // do something on success
* }, function(response) {
* // do something on error
* if (canRecover(response)) {
* return responseOrNewPromise
* }
* return $q.reject(response);
* });
* }
* });
*
* $httpProvider.responseInterceptors.push('myHttpInterceptor');
*
*
* // register the interceptor via an anonymous factory
* $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
* return function(promise) {
* // same as above
* }
* });
* </pre>
*
*
* # Security Considerations
*
* When designing web applications, consider security threats from:
*
* - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON vulnerability}
* - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}
*
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ## JSON Vulnerability Protection
*
* A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON vulnerability} allows third party website to turn your JSON resource URL into
* {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* <pre>
* ['one','two']
* </pre>
*
* which is vulnerable to attack, your server can return:
* <pre>
* )]}',
* ['one','two']
* </pre>
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ## Cross Site Request Forgery (XSRF) Protection
*
* {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which
* an unauthorized site can gain your user's private data. Angular provides a mechanism
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
* called `XSRF-TOKEN` and sets it as the HTTP header `X-XSRF-TOKEN`. Since only JavaScript that
* runs on your domain could read the cookie, your server can be assured that the XHR came from
* JavaScript running on your domain.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have sent the request. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript from making
* up its own tokens). We recommend that the token is a digest of your site's authentication
* cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt} for added security.
*
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
*
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned to
* `?key1=value1&key2=value2` after the url. If the value is not a string, it will be JSONified.
* - **data** – `{string|Object}` – Data to be sent as the request message data.
* - **headers** – `{Object}` – Map of strings representing HTTP headers to send to the server.
* - **transformRequest** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* - **transformResponse** – `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body and headers and returns its transformed (typically deserialized) version.
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **timeout** – `{number}` – timeout in milliseconds.
* - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
* XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
* requests with credentials} for more information.
*
* @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
* standard `then` method and two http specific methods: `success` and `error`. The `then`
* method takes two arguments a success and an error callback which will be called with a
* response object. The `success` and `error` methods take a single argument - a function that
* will be called when the request succeeds or fails respectively. The arguments passed into
* these functions are destructured representation of the response object passed into the
* `then` method. The response object has these properties:
*
* - **data** – `{string|Object}` – The response body transformed with the transform functions.
* - **status** – `{number}` – HTTP status code of the response.
* - **headers** – `{function([headerName])}` – Header getter function.
* - **config** – `{Object}` – The configuration object that was used to generate the request.
*
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
<example>
<file name="index.html">
<div ng-controller="FetchCtrl">
<select ng-model="method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80"/>
<button ng-click="fetch()">fetch</button><br>
<button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">Sample JSONP</button>
<button ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">Invalid JSONP</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
function FetchCtrl($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="scenario.js">
it('should make an xhr GET request', function() {
element(':button:contains("Sample GET")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Hello, \$http!/);
});
it('should make a JSONP request to angularjs.org', function() {
element(':button:contains("Sample JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Super Hero!/);
});
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
element(':button:contains("Invalid JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('0');
expect(binding('data')).toBe('Request failed');
});
</file>
</example>
*/
function $http(config) {
config.method = uppercase(config.method);
var reqTransformFn = config.transformRequest || $config.transformRequest,
respTransformFn = config.transformResponse || $config.transformResponse,
defHeaders = $config.headers,
reqHeaders = extend({'X-XSRF-TOKEN': $browser.cookies()['XSRF-TOKEN']},
defHeaders.common, defHeaders[lowercase(config.method)], config.headers),
reqData = transformData(config.data, headersGetter(reqHeaders), reqTransformFn),
promise;
// strip content-type if data is undefined
if (isUndefined(config.data)) {
delete reqHeaders['Content-Type'];
}
// send request
promise = sendReq(config, reqData, reqHeaders);
// transform future response
promise = promise.then(transformResponse, transformResponse);
// apply interceptors
forEach(responseInterceptors, function(interceptor) {
promise = interceptor(promise);
});
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response, {
data: transformData(response.data, response.headers, respTransformFn)
});
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
}
$http.pendingRequests = [];
/**
* @ngdoc method
* @name ng.$http#get
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `GET` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#delete
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `DELETE` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#head
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `HEAD` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#jsonp
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `JSONP` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
* Should contain `JSON_CALLBACK` string.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name ng.$http#post
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `POST` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#put
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `PUT` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put');
/**
* @ngdoc property
* @name ng.$http#defaults
* @propertyOf ng.$http
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
* default headers as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = $config;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(extend(config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(extend(config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request.
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, $config, $log, $rootScope, defaultCache, $http.pendingRequests
*/
function sendReq(config, reqData, reqHeaders) {
var deferred = $q.defer(),
promise = deferred.promise,
cache,
cachedResp,
url = buildUrl(config.url, config.params);
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if (config.cache && config.method == 'GET') {
cache = isObject(config.cache) ? config.cache : defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (cachedResp) {
if (cachedResp.then) {
// cached request has already been sent, but there is no response yet
cachedResp.then(removePendingReq, removePendingReq);
return cachedResp;
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]));
} else {
resolvePromise(cachedResp, 200, {});
}
}
} else {
// put the promise for the non-transformed response into cache as a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, send the request to the backend
if (!cachedResp) {
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
config.withCredentials);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString)]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
resolvePromise(response, status, headersString);
$rootScope.$apply();
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers) {
// normalize internal statuses to 0
status = Math.max(status, 0);
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config
});
}
function removePendingReq() {
var idx = indexOf($http.pendingRequests, config);
if (idx !== -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, params) {
if (!params) return url;
var parts = [];
forEachSorted(params, function(value, key) {
if (value == null || value == undefined) return;
if (isObject(value)) {
value = toJson(value);
}
parts.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
});
return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
}
}];
}
var XHR = window.XMLHttpRequest || function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
throw new Error("This browser does not support XMLHttpRequest.");
};
/**
* @ngdoc object
* @name ng.$httpBackend
* @requires $browser
* @requires $window
* @requires $document
*
* @description
* HTTP backend used by the {@link ng.$http service} that delegates to
* XMLHttpRequest object or JSONP and deals with browser incompatibilities.
*
* You should never need to use this service directly, instead use the higher-level abstractions:
* {@link ng.$http $http} or {@link ngResource.$resource $resource}.
*
* During testing this implementation is swapped with {@link ngMock.$httpBackend mock
* $httpBackend} which can be trained with responses.
*/
function $HttpBackendProvider() {
this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks,
$document[0], $window.location.protocol.replace(':', ''));
}];
}
function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) {
// TODO(vojta): fix the signature
return function(method, url, post, callback, headers, timeout, withCredentials) {
$browser.$$incOutstandingRequestCount();
url = url || $browser.url();
if (lowercase(method) == 'jsonp') {
var callbackId = '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] = function(data) {
callbacks[callbackId].data = data;
};
jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
function() {
if (callbacks[callbackId].data) {
completeRequest(callback, 200, callbacks[callbackId].data);
} else {
completeRequest(callback, -2);
}
delete callbacks[callbackId];
});
} else {
var xhr = new XHR();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (value) xhr.setRequestHeader(key, value);
});
var status;
// In IE6 and 7, this might be called synchronously when xhr.send below is called and the
// response is in the cache. the promise api will ensure that to the app code the api is
// always async
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var responseHeaders = xhr.getAllResponseHeaders();
// TODO(vojta): remove once Firefox 21 gets released.
// begin: workaround to overcome Firefox CORS http response headers bug
// https://bugzilla.mozilla.org/show_bug.cgi?id=608735
// Firefox already patched in nightly. Should land in Firefox 21.
// CORS "simple response headers" http://www.w3.org/TR/cors/
var value,
simpleHeaders = ["Cache-Control", "Content-Language", "Content-Type",
"Expires", "Last-Modified", "Pragma"];
if (!responseHeaders) {
responseHeaders = "";
forEach(simpleHeaders, function (header) {
var value = xhr.getResponseHeader(header);
if (value) {
responseHeaders += header + ": " + value + "\n";
}
});
}
// end of the workaround.
completeRequest(callback, status || xhr.status, xhr.responseText,
responseHeaders);
}
};
if (withCredentials) {
xhr.withCredentials = true;
}
xhr.send(post || '');
if (timeout > 0) {
$browserDefer(function() {
status = -1;
xhr.abort();
}, timeout);
}
}
function completeRequest(callback, status, response, headersString) {
// URL_MATCH is defined in src/service/location.js
var protocol = (url.match(URL_MATCH) || ['', locationProtocol])[1];
// fix status code for file protocol (it's always 0)
status = (protocol == 'file') ? (response ? 200 : 404) : status;
// normalize IE bug (http://bugs.jquery.com/ticket/1450)
status = status == 1223 ? 204 : status;
callback(status, response, headersString);
$browser.$$completeOutstandingRequest(noop);
}
};
function jsonpReq(url, done) {
// we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
var script = rawDocument.createElement('script'),
doneWrapper = function() {
rawDocument.body.removeChild(script);
if (done) done();
};
script.type = 'text/javascript';
script.src = url;
if (msie) {
script.onreadystatechange = function() {
if (/loaded|complete/.test(script.readyState)) doneWrapper();
};
} else {
script.onload = script.onerror = doneWrapper;
}
rawDocument.body.appendChild(script);
}
}
/**
* @ngdoc object
* @name ng.$locale
*
* @description
* $locale service provides localization rules for various Angular components. As of right now the
* only public api is:
*
* * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
*/
function $LocaleProvider(){
this.$get = function() {
return {
id: 'en-us',
NUMBER_FORMATS: {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [
{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
},{ //Currency Pattern
minInt: 1,
minFrac: 2,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}
],
CURRENCY_SYM: '$'
},
DATETIME_FORMATS: {
MONTH: 'January,February,March,April,May,June,July,August,September,October,November,December'
.split(','),
SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
AMPMS: ['AM','PM'],
medium: 'MMM d, y h:mm:ss a',
short: 'M/d/yy h:mm a',
fullDate: 'EEEE, MMMM d, y',
longDate: 'MMMM d, y',
mediumDate: 'MMM d, y',
shortDate: 'M/d/yy',
mediumTime: 'h:mm:ss a',
shortTime: 'h:mm a'
},
pluralCat: function(num) {
if (num === 1) {
return 'one';
}
return 'other';
}
};
};
}
function $TimeoutProvider() {
this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
function($rootScope, $browser, $q, $exceptionHandler) {
var deferreds = {};
/**
* @ngdoc function
* @name ng.$timeout
* @requires $browser
*
* @description
* Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
* block and delegates any exceptions to
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* The return value of registering a timeout function is a promise, which will be resolved when
* the timeout is reached and the timeout function is executed.
*
* To cancel a timeout request, call `$timeout.cancel(promise)`.
*
* In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
* synchronously flush the queue of deferred functions.
*
* @param {function()} fn A function, whose execution should be delayed.
* @param {number=} [delay=0] Delay in milliseconds.
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
* @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
* promise will be resolved with is the return value of the `fn` function.
*/
function timeout(fn, delay, invokeApply) {
var deferred = $q.defer(),
promise = deferred.promise,
skipApply = (isDefined(invokeApply) && !invokeApply),
timeoutId, cleanup;
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn());
} catch(e) {
deferred.reject(e);
$exceptionHandler(e);
}
if (!skipApply) $rootScope.$apply();
}, delay);
cleanup = function() {
delete deferreds[promise.$$timeoutId];
};
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = deferred;
promise.then(cleanup, cleanup);
return promise;
}
/**
* @ngdoc function
* @name ng.$timeout#cancel
* @methodOf ng.$timeout
*
* @description
* Cancels a task associated with the `promise`. As a result of this, the promise will be
* resolved with a rejection.
*
* @param {Promise=} promise Promise returned by the `$timeout` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
timeout.cancel = function(promise) {
if (promise && promise.$$timeoutId in deferreds) {
deferreds[promise.$$timeoutId].reject('canceled');
return $browser.defer.cancel(promise.$$timeoutId);
}
return false;
};
return timeout;
}];
}
/**
* @ngdoc object
* @name ng.$filterProvider
* @description
*
* Filters are just functions which transform input to an output. However filters need to be Dependency Injected. To
* achieve this a filter definition consists of a factory function which is annotated with dependencies and is
* responsible for creating a filter function.
*
* <pre>
* // Filter registration
* function MyModule($provide, $filterProvider) {
* // create a service to demonstrate injection (not always needed)
* $provide.value('greet', function(name){
* return 'Hello ' + name + '!';
* });
*
* // register a filter factory which uses the
* // greet service to demonstrate DI.
* $filterProvider.register('greet', function(greet){
* // return the filter function which uses the greet service
* // to generate salutation
* return function(text) {
* // filters need to be forgiving so check input validity
* return text && greet(text) || text;
* };
* });
* }
* </pre>
*
* The filter function is registered with the `$injector` under the filter name suffixe with `Filter`.
* <pre>
* it('should be the same instance', inject(
* function($filterProvider) {
* $filterProvider.register('reverse', function(){
* return ...;
* });
* },
* function($filter, reverseFilter) {
* expect($filter('reverse')).toBe(reverseFilter);
* });
* </pre>
*
*
* For more information about how angular filters work, and how to create your own filters, see
* {@link guide/dev_guide.templates.filters Understanding Angular Filters} in the angular Developer
* Guide.
*/
/**
* @ngdoc method
* @name ng.$filterProvider#register
* @methodOf ng.$filterProvider
* @description
* Register filter factory function.
*
* @param {String} name Name of the filter.
* @param {function} fn The filter factory function which is injectable.
*/
/**
* @ngdoc function
* @name ng.$filter
* @function
* @description
* Filters are used for formatting data displayed to the user.
*
* The general syntax in templates is as follows:
*
* {{ expression [| filter_name[:parameter_value] ... ] }}
*
* @param {String} name Name of the filter function to retrieve
* @return {Function} the filter function
*/
$FilterProvider.$inject = ['$provide'];
function $FilterProvider($provide) {
var suffix = 'Filter';
function register(name, factory) {
return $provide.factory(name + suffix, factory);
}
this.register = register;
this.$get = ['$injector', function($injector) {
return function(name) {
return $injector.get(name + suffix);
}
}];
////////////////////////////////////////
register('currency', currencyFilter);
register('date', dateFilter);
register('filter', filterFilter);
register('json', jsonFilter);
register('limitTo', limitToFilter);
register('lowercase', lowercaseFilter);
register('number', numberFilter);
register('orderBy', orderByFilter);
register('uppercase', uppercaseFilter);
}
/**
* @ngdoc filter
* @name ng.filter:filter
* @function
*
* @description
* Selects a subset of items from `array` and returns it as a new array.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array The source array.
* @param {string|Object|function()} expression The predicate to be used for selecting items from
* `array`.
*
* Can be one of:
*
* - `string`: Predicate that results in a substring match using the value of `expression`
* string. All strings or objects with string properties in `array` that contain this string
* will be returned. The predicate can be negated by prefixing the string with `!`.
*
* - `Object`: A pattern object can be used to filter specific properties on objects contained
* by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
* which have property `name` containing "M" and property `phone` containing "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any
* property of the object. That's equivalent to the simple substring match with a `string`
* as described above.
*
* - `function`: A predicate function can be used to write arbitrary filters. The function is
* called for each element of `array`. The final result is an array of those elements that
* the predicate returned true for.
*
* @example
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'}]"></div>
Search: <input ng-model="searchText">
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
<hr>
Any: <input ng-model="search.$"> <br>
Name only <input ng-model="search.name"><br>
Phone only <input ng-model="search.phone"><br>
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:search">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
</doc:source>
<doc:scenario>
it('should search across all fields when filtering with a string', function() {
input('searchText').enter('m');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Adam']);
input('searchText').enter('76');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['John', 'Julie']);
});
it('should search in specific fields when filtering with a predicate object', function() {
input('search.$').enter('i');
expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Julie']);
});
</doc:scenario>
</doc:example>
*/
function filterFilter() {
return function(array, expression) {
if (!isArray(array)) return array;
var predicates = [];
predicates.check = function(value) {
for (var j = 0; j < predicates.length; j++) {
if(!predicates[j](value)) {
return false;
}
}
return true;
};
var search = function(obj, text){
if (text.charAt(0) === '!') {
return !search(obj, text.substr(1));
}
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return ('' + obj).toLowerCase().indexOf(text) > -1;
case "object":
for ( var objKey in obj) {
if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
return true;
}
}
return false;
case "array":
for ( var i = 0; i < obj.length; i++) {
if (search(obj[i], text)) {
return true;
}
}
return false;
default:
return false;
}
};
switch (typeof expression) {
case "boolean":
case "number":
case "string":
expression = {$:expression};
case "object":
for (var key in expression) {
if (key == '$') {
(function() {
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(value, text);
});
})();
} else {
(function() {
var path = key;
var text = (''+expression[key]).toLowerCase();
if (!text) return;
predicates.push(function(value) {
return search(getter(value, path), text);
});
})();
}
}
break;
case 'function':
predicates.push(expression);
break;
default:
return array;
}
var filtered = [];
for ( var j = 0; j < array.length; j++) {
var value = array[j];
if (predicates.check(value)) {
filtered.push(value);
}
}
return filtered;
}
}
/**
* @ngdoc filter
* @name ng.filter:currency
* @function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @returns {string} Formatted number.
*
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.amount = 1234.56;
}
</script>
<div ng-controller="Ctrl">
<input type="number" ng-model="amount"> <br>
default currency symbol ($): {{amount | currency}}<br>
custom currency identifier (USD$): {{amount | currency:"USD$"}}
</div>
</doc:source>
<doc:scenario>
it('should init with 1234.56', function() {
expect(binding('amount | currency')).toBe('$1,234.56');
expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
});
it('should update', function() {
input('amount').enter('-1234');
expect(binding('amount | currency')).toBe('($1,234.00)');
expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
});
</doc:scenario>
</doc:example>
*/
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(amount, currencySymbol){
if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
replace(/\u00A4/g, currencySymbol);
};
}
/**
* @ngdoc filter
* @name ng.filter:number
* @function
*
* @description
* Formats a number as text.
*
* If the input is not a number an empty string is returned.
*
* @param {number|string} number Number to format.
* @param {(number|string)=} [fractionSize=2] Number of decimal places to round the number to.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.val = 1234.56789;
}
</script>
<div ng-controller="Ctrl">
Enter number: <input ng-model='val'><br>
Default formatting: {{val | number}}<br>
No fractions: {{val | number:0}}<br>
Negative number: {{-val | number:4}}
</div>
</doc:source>
<doc:scenario>
it('should format numbers', function() {
expect(binding('val | number')).toBe('1,234.568');
expect(binding('val | number:0')).toBe('1,235');
expect(binding('-val | number:4')).toBe('-1,234.5679');
});
it('should update', function() {
input('val').enter('3374.333');
expect(binding('val | number')).toBe('3,374.333');
expect(binding('val | number:0')).toBe('3,374');
expect(binding('-val | number:4')).toBe('-3,374.3330');
});
</doc:scenario>
</doc:example>
*/
numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
fractionSize);
};
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (isNaN(number) || !isFinite(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var numStr = number + '',
formatedText = '',
parts = [];
var hasExponent = false;
if (numStr.indexOf('e') !== -1) {
var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
if (match && match[2] == '-' && match[3] > fractionSize + 1) {
numStr = '0';
} else {
formatedText = numStr;
hasExponent = true;
}
}
if (!hasExponent) {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}
var pow = Math.pow(10, fractionSize);
number = Math.round(number * pow) / pow;
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (var i = 0; i < pos; i++) {
if ((pos - i)%group === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
}
for (i = pos; i < whole.length; i++) {
if ((whole.length - i)%lgroup === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
// format fraction part.
while(fraction.length < fractionSize) {
fraction += '0';
}
if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
}
parts.push(isNegative ? pattern.negPre : pattern.posPre);
parts.push(formatedText);
parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while(num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
function dateGetter(name, size, offset, trim) {
offset = offset || 0;
return function(date) {
var value = date['get' + name]();
if (offset > 0 || value > -offset)
value += offset;
if (value === 0 && offset == -12 ) value = 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date['get' + name]();
var get = uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date) {
var zone = -1 * date.getTimezoneOffset();
var paddedZone = (zone >= 0) ? "+" : "";
paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
padNumber(Math.abs(zone % 60), 2);
return paddedZone;
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
var DATE_FORMATS = {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter
};
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
NUMBER_STRING = /^\d+$/;
/**
* @ngdoc filter
* @name ng.filter:date
* @function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in am/pm, padded (01-12)
* * `'h'`: Hour in am/pm, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'a'`: am/pm marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
*
* `format` string can also be one of the following predefined
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 pm)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
*
* `format` string can contain literal values. These need to be quoted with single quotes (e.g.
* `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
* (e.g. `"h o''clock"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
* specified in the string input, the time is considered to be in the local timezone.
* @param {string=} format Formatting rules (see Description). If not specified,
* `mediumDate` is used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
<doc:example>
<doc:source>
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
{{1288323623006 | date:'medium'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
</doc:source>
<doc:scenario>
it('should format date', function() {
expect(binding("1288323623006 | date:'medium'")).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
});
</doc:scenario>
</doc:example>
*/
dateFilter.$inject = ['$locale'];
function dateFilter($locale) {
var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
function jsonStringToDate(string){
var match;
if (match = string.match(R_ISO8601_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
date.setUTCFullYear(int(match[1]), int(match[2]) - 1, int(match[3]));
date.setUTCHours(int(match[4]||0) - tzHour, int(match[5]||0) - tzMin, int(match[6]||0), int(match[7]||0));
return date;
}
return string;
}
return function(date, format) {
var text = '',
parts = [],
fn, match;
format = format || 'mediumDate';
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
if (NUMBER_STRING.test(date)) {
date = int(date);
} else {
date = jsonStringToDate(date);
}
}
if (isNumber(date)) {
date = new Date(date);
}
if (!isDate(date)) {
return date;
}
while(format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
forEach(parts, function(value){
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS)
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
});
return text;
};
}
/**
* @ngdoc filter
* @name ng.filter:json
* @function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curly {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
* @returns {string} JSON string.
*
*
* @example:
<doc:example>
<doc:source>
<pre>{{ {'name':'value'} | json }}</pre>
</doc:source>
<doc:scenario>
it('should jsonify filtered objects', function() {
expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
});
</doc:scenario>
</doc:example>
*
*/
function jsonFilter() {
return function(object) {
return toJson(object, true);
};
}
/**
* @ngdoc filter
* @name ng.filter:lowercase
* @function
* @description
* Converts string to lowercase.
* @see angular.lowercase
*/
var lowercaseFilter = valueFn(lowercase);
/**
* @ngdoc filter
* @name ng.filter:uppercase
* @function
* @description
* Converts string to uppercase.
* @see angular.uppercase
*/
var uppercaseFilter = valueFn(uppercase);
/**
* @ngdoc function
* @name ng.filter:limitTo
* @function
*
* @description
* Creates a new array containing only a specified number of elements in an array. The elements
* are taken from either the beginning or the end of the source array, as specified by the
* value and sign (positive or negative) of `limit`.
*
* Note: This function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more information about Angular arrays.
*
* @param {Array} array Source array to be limited.
* @param {string|Number} limit The length of the returned array. If the `limit` number is
* positive, `limit` number of items from the beginning of the source array are copied.
* If the number is negative, `limit` number of items from the end of the source array are
* copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array} A new sub-array of length `limit` or less if input array had less than `limit`
* elements.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.limit = 3;
}
</script>
<div ng-controller="Ctrl">
Limit {{numbers}} to: <input type="integer" ng-model="limit">
<p>Output: {{ numbers | limitTo:limit }}</p>
</div>
</doc:source>
<doc:scenario>
it('should limit the numer array to first three items', function() {
expect(element('.doc-example-live input[ng-model=limit]').val()).toBe('3');
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3]');
});
it('should update the output when -3 is entered', function() {
input('limit').enter(-3);
expect(binding('numbers | limitTo:limit')).toEqual('[7,8,9]');
});
it('should not exceed the maximum size of input array', function() {
input('limit').enter(100);
expect(binding('numbers | limitTo:limit')).toEqual('[1,2,3,4,5,6,7,8,9]');
});
</doc:scenario>
</doc:example>
*/
function limitToFilter(){
return function(array, limit) {
if (!(array instanceof Array)) return array;
limit = int(limit);
var out = [],
i, n;
// check that array is iterable
if (!array || !(array instanceof Array))
return out;
// if abs(limit) exceeds maximum length, trim it
if (limit > array.length)
limit = array.length;
else if (limit < -array.length)
limit = -array.length;
if (limit > 0) {
i = 0;
n = limit;
} else {
i = array.length + limit;
n = array.length;
}
for (; i<n; i++) {
out.push(array[i]);
}
return out;
}
}
/**
* @ngdoc function
* @name ng.filter:orderBy
* @function
*
* @description
* Orders a specified `array` by the `expression` predicate.
*
* Note: this function is used to augment the `Array` type in Angular expressions. See
* {@link ng.$filter} for more informaton about Angular arrays.
*
* @param {Array} array The array to sort.
* @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
* used by the comparator to determine the order of elements.
*
* Can be one of:
*
* - `function`: Getter function. The result of this function will be sorted using the
* `<`, `=`, `>` operator.
* - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
* to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
* ascending or descending sort order (for example, +name or -name).
* - `Array`: An array of function or string predicates. The first predicate in the array
* is used for sorting, but when two items are equivalent, the next predicate is used.
*
* @param {boolean=} reverse Reverse the order the array.
* @returns {Array} Sorted copy of the source array.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}]
$scope.predicate = '-age';
}
</script>
<div ng-controller="Ctrl">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
(<a href ng-click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
</tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</doc:source>
<doc:scenario>
it('should be reverse ordered by aged', function() {
expect(binding('predicate')).toBe('-age');
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '29', '21', '19', '10']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
});
it('should reorder the table when user selects different predicate', function() {
element('.doc-example-live a:contains("Name")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '10', '29', '19', '21']);
element('.doc-example-live a:contains("Phone")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
});
</doc:scenario>
</doc:example>
*/
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse){
return function(array, sortPredicate, reverseOrder) {
if (!isArray(array)) return array;
if (!sortPredicate) return array;
sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
sortPredicate = map(sortPredicate, function(predicate){
var descending = false, get = predicate || identity;
if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
descending = predicate.charAt(0) == '-';
predicate = predicate.substring(1);
}
get = $parse(predicate);
}
return reverseComparator(function(a,b){
return compare(get(a),get(b));
}, descending);
});
var arrayCopy = [];
for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
function comparator(o1, o2){
for ( var i = 0; i < sortPredicate.length; i++) {
var comp = sortPredicate[i](o1, o2);
if (comp !== 0) return comp;
}
return 0;
}
function reverseComparator(comp, descending) {
return toBoolean(descending)
? function(a,b){return comp(b,a);}
: comp;
}
function compare(v1, v2){
var t1 = typeof v1;
var t2 = typeof v2;
if (t1 == t2) {
if (t1 == "string") v1 = v1.toLowerCase();
if (t1 == "string") v2 = v2.toLowerCase();
if (v1 === v2) return 0;
return v1 < v2 ? -1 : 1;
} else {
return t1 < t2 ? -1 : 1;
}
}
}
}
function ngDirective(directive) {
if (isFunction(directive)) {
directive = {
link: directive
}
}
directive.restrict = directive.restrict || 'AC';
return valueFn(directive);
}
/**
* @ngdoc directive
* @name ng.directive:a
* @restrict E
*
* @description
* Modifies the default behavior of html A tag, so that the default action is prevented when href
* attribute is empty.
*
* The reasoning for this change is to allow easy creation of action links with `ngClick` directive
* without changing the location or causing page reloads, e.g.:
* `<a href="" ng-click="model.$save()">Save</a>`
*/
var htmlAnchorDirective = valueFn({
restrict: 'E',
compile: function(element, attr) {
if (msie <= 8) {
// turn <a href ng-click="..">link</a> into a stylable link in IE
// but only if it doesn't have name attribute, in which case it's an anchor
if (!attr.href && !attr.name) {
attr.$set('href', '');
}
// add a comment node to anchors to workaround IE bug that causes element content to be reset
// to new attribute content if attribute is updated with value containing @ and element also
// contains value with @
// see issue #1949
element.append(document.createComment('IE fix'));
}
return function(scope, element) {
element.bind('click', function(event){
// if we have no href url, then don't navigate anywhere.
if (!element.attr('href')) {
event.preventDefault();
}
});
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngHref
* @restrict A
*
* @description
* Using Angular markup like {{hash}} in an href attribute makes
* the page open to a wrong URL, if the user clicks that link before
* angular has a chance to replace the {{hash}} with actual URL, the
* link will be broken and will most likely return a 404 error.
* The `ngHref` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <a href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element A
* @param {template} ngHref any string which can contain `{{}}` markup.
*
* @example
* This example uses `link` variable inside `href` attribute:
<doc:example>
<doc:source>
<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
<a id="link-6" ng-href="{{value}}">link</a> (link, change location)
</doc:source>
<doc:scenario>
it('should execute ng-click but not reload when href without value', function() {
element('#link-1').click();
expect(input('value').val()).toEqual('1');
expect(element('#link-1').attr('href')).toBe("");
});
it('should execute ng-click but not reload when href empty string', function() {
element('#link-2').click();
expect(input('value').val()).toEqual('2');
expect(element('#link-2').attr('href')).toBe("");
});
it('should execute ng-click and change url when ng-href specified', function() {
expect(element('#link-3').attr('href')).toBe("/123");
element('#link-3').click();
expect(browser().window().path()).toEqual('/123');
});
it('should execute ng-click but not reload when href empty string and name specified', function() {
element('#link-4').click();
expect(input('value').val()).toEqual('4');
expect(element('#link-4').attr('href')).toBe('');
});
it('should execute ng-click but not reload when no href but name specified', function() {
element('#link-5').click();
expect(input('value').val()).toEqual('5');
expect(element('#link-5').attr('href')).toBe(undefined);
});
it('should only change url when only ng-href', function() {
input('value').enter('6');
expect(element('#link-6').attr('href')).toBe('6');
element('#link-6').click();
expect(browser().location().url()).toEqual('/6');
});
</doc:scenario>
</doc:example>
*/
/**
* @ngdoc directive
* @name ng.directive:ngSrc
* @restrict A
*
* @description
* Using Angular markup like `{{hash}}` in a `src` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrc` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <img src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element IMG
* @param {template} ngSrc any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ng.directive:ngDisabled
* @restrict A
*
* @description
*
* The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
* <pre>
* <div ng-init="scope = { isDisabled: false }">
* <button disabled="{{scope.isDisabled}}">Disabled</button>
* </div>
* </pre>
*
* The HTML specs do not require browsers to preserve the special attributes such as disabled.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngDisabled` directive.
*
* @example
<doc:example>
<doc:source>
Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
<button ng-model="button" ng-disabled="checked">Button</button>
</doc:source>
<doc:scenario>
it('should toggle button', function() {
expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngDisabled Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngChecked
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as checked.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngChecked` directive.
* @example
<doc:example>
<doc:source>
Check me to check both: <input type="checkbox" ng-model="master"><br/>
<input id="checkSlave" type="checkbox" ng-checked="master">
</doc:source>
<doc:scenario>
it('should check both checkBoxes', function() {
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
input('master').check();
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngChecked Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngMultiple
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as multiple.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngMultiple` directive.
*
* @example
<doc:example>
<doc:source>
Check me check multiple: <input type="checkbox" ng-model="checked"><br/>
<select id="select" ng-multiple="checked">
<option>Misko</option>
<option>Igor</option>
<option>Vojta</option>
<option>Di</option>
</select>
</doc:source>
<doc:scenario>
it('should toggle multiple', function() {
expect(element('.doc-example-live #select').prop('multiple')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live #select').prop('multiple')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element SELECT
* @param {expression} ngMultiple Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngReadonly
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as readonly.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduce the `ngReadonly` directive.
* @example
<doc:example>
<doc:source>
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
<input type="text" ng-readonly="checked" value="I'm Angular"/>
</doc:source>
<doc:scenario>
it('should toggle readonly attr', function() {
expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {string} expression Angular expression that will be evaluated.
*/
/**
* @ngdoc directive
* @name ng.directive:ngSelected
* @restrict A
*
* @description
* The HTML specs do not require browsers to preserve the special attributes such as selected.
* (The presence of them means true and absence means false)
* This prevents the angular compiler from correctly retrieving the binding expression.
* To solve this problem, we introduced the `ngSelected` directive.
* @example
<doc:example>
<doc:source>
Check me to select: <input type="checkbox" ng-model="selected"><br/>
<select>
<option>Hello!</option>
<option id="greet" ng-selected="selected">Greetings!</option>
</select>
</doc:source>
<doc:scenario>
it('should select Greetings!', function() {
expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
input('selected').check();
expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element OPTION
* @param {string} expression Angular expression that will be evaluated.
*/
var ngAttributeAliasDirectives = {};
// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 100,
compile: function() {
return function(scope, element, attr) {
scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
attr.$set(attrName, !!value);
});
};
}
};
};
});
// ng-src, ng-href are interpolated
forEach(['src', 'href'], function(attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 99, // it needs to run after the attributes are interpolated
link: function(scope, element, attr) {
attr.$observe(normalized, function(value) {
if (!value)
return;
attr.$set(attrName, value);
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
// to set the property as well to achieve the desired effect.
// we use attr[attrName] value since $set can sanitize the url.
if (msie) element.prop(attrName, attr[attrName]);
});
}
};
};
});
var nullFormCtrl = {
$addControl: noop,
$removeControl: noop,
$setValidity: noop,
$setDirty: noop
};
/**
* @ngdoc object
* @name ng.directive:form.FormController
*
* @property {boolean} $pristine True if user has not interacted with the form yet.
* @property {boolean} $dirty True if user has already interacted with the form.
* @property {boolean} $valid True if all of the containing forms and controls are valid.
* @property {boolean} $invalid True if at least one containing control or form is invalid.
*
* @property {Object} $error Is an object hash, containing references to all invalid controls or
* forms, where:
*
* - keys are validation tokens (error names) — such as `required`, `url` or `email`),
* - values are arrays of controls or forms that are invalid with given error.
*
* @description
* `FormController` keeps track of all its controls and nested forms as well as state of them,
* such as being valid/invalid or dirty/pristine.
*
* Each {@link ng.directive:form form} directive creates an instance
* of `FormController`.
*
*/
//asks for $scope to fool the BC controller module
FormController.$inject = ['$element', '$attrs', '$scope'];
function FormController(element, attrs) {
var form = this,
parentForm = element.parent().controller('form') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
errors = form.$error = {};
// init state
form.$name = attrs.name;
form.$dirty = false;
form.$pristine = true;
form.$valid = true;
form.$invalid = false;
parentForm.$addControl(form);
// Setup initial state of the control
element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
form.$addControl = function(control) {
if (control.$name && !form.hasOwnProperty(control.$name)) {
form[control.$name] = control;
}
};
form.$removeControl = function(control) {
if (control.$name && form[control.$name] === control) {
delete form[control.$name];
}
forEach(errors, function(queue, validationToken) {
form.$setValidity(validationToken, true, control);
});
};
form.$setValidity = function(validationToken, isValid, control) {
var queue = errors[validationToken];
if (isValid) {
if (queue) {
arrayRemove(queue, control);
if (!queue.length) {
invalidCount--;
if (!invalidCount) {
toggleValidCss(isValid);
form.$valid = true;
form.$invalid = false;
}
errors[validationToken] = false;
toggleValidCss(true, validationToken);
parentForm.$setValidity(validationToken, true, form);
}
}
} else {
if (!invalidCount) {
toggleValidCss(isValid);
}
if (queue) {
if (includes(queue, control)) return;
} else {
errors[validationToken] = queue = [];
invalidCount++;
toggleValidCss(false, validationToken);
parentForm.$setValidity(validationToken, false, form);
}
queue.push(control);
form.$valid = false;
form.$invalid = true;
}
};
form.$setDirty = function() {
element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
form.$dirty = true;
form.$pristine = false;
parentForm.$setDirty();
};
}
/**
* @ngdoc directive
* @name ng.directive:ngForm
* @restrict EAC
*
* @description
* Nestable alias of {@link ng.directive:form `form`} directive. HTML
* does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
* sub-group of controls needs to be determined.
*
* @param {string=} name|ngForm Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
*/
/**
* @ngdoc directive
* @name ng.directive:form
* @restrict E
*
* @description
* Directive that instantiates
* {@link ng.directive:form.FormController FormController}.
*
* If `name` attribute is specified, the form controller is published onto the current scope under
* this name.
*
* # Alias: {@link ng.directive:ngForm `ngForm`}
*
* In angular forms can be nested. This means that the outer form is valid when all of the child
* forms are valid as well. However browsers do not allow nesting of `<form>` elements, for this
* reason angular provides {@link ng.directive:ngForm `ngForm`} alias
* which behaves identical to `<form>` but allows form nesting.
*
*
* # CSS classes
* - `ng-valid` Is set if the form is valid.
* - `ng-invalid` Is set if the form is invalid.
* - `ng-pristine` Is set if the form is pristine.
* - `ng-dirty` Is set if the form is dirty.
*
*
* # Submitting a form and preventing default action
*
* Since the role of forms in client-side Angular applications is different than in classical
* roundtrip apps, it is desirable for the browser not to translate the form submission into a full
* page reload that sends the data to the server. Instead some javascript logic should be triggered
* to handle the form submission in application specific way.
*
* For this reason, Angular prevents the default action (form submission to the server) unless the
* `<form>` element has an `action` attribute specified.
*
* You can use one of the following two ways to specify what javascript method should be called when
* a form is submitted:
*
* - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
* - {@link ng.directive:ngClick ngClick} directive on the first
* button or input field of type submit (input[type=submit])
*
* To prevent double execution of the handler, use only one of ngSubmit or ngClick directives. This
* is because of the following form submission rules coming from the html spec:
*
* - If a form has only one input field then hitting enter in this field triggers form submit
* (`ngSubmit`)
* - if a form has has 2+ input fields and no buttons or input[type=submit] then hitting enter
* doesn't trigger submit
* - if a form has one or more input fields and one or more buttons or input[type=submit] then
* hitting enter in any of the input fields will trigger the click handler on the *first* button or
* input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
*
* @param {string=} name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.userType = 'guest';
}
</script>
<form name="myForm" ng-controller="Ctrl">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
<tt>userType = {{userType}}</tt><br>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('userType')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('userType').enter('');
expect(binding('userType')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var formDirectiveFactory = function(isNgForm) {
return ['$timeout', function($timeout) {
var formDirective = {
name: 'form',
restrict: 'E',
controller: FormController,
compile: function() {
return {
pre: function(scope, formElement, attr, controller) {
if (!attr.action) {
// we can't use jq events because if a form is destroyed during submission the default
// action is not prevented. see #1238
//
// IE 9 is not affected because it doesn't fire a submit event and try to do a full
// page reload if the form was destroyed by submission of the form via a click handler
// on a button in the form. Looks like an IE9 specific bug.
var preventDefaultListener = function(event) {
event.preventDefault
? event.preventDefault()
: event.returnValue = false; // IE
};
addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
// unregister the preventDefault listener so that we don't not leak memory but in a
// way that will achieve the prevention of the default action.
formElement.bind('$destroy', function() {
$timeout(function() {
removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
}, 0, false);
});
}
var parentFormCtrl = formElement.parent().controller('form'),
alias = attr.name || attr.ngForm;
if (alias) {
scope[alias] = controller;
}
if (parentFormCtrl) {
formElement.bind('$destroy', function() {
parentFormCtrl.$removeControl(controller);
if (alias) {
scope[alias] = undefined;
}
extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
});
}
}
};
}
};
return isNgForm ? extend(copy(formDirective), {restrict: 'EAC'}) : formDirective;
}];
};
var formDirective = formDirectiveFactory();
var ngFormDirective = formDirectiveFactory(true);
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
var inputType = {
/**
* @ngdoc inputType
* @name ng.directive:input.text
*
* @description
* Standard HTML text input with angular data binding.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Adds `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'guest';
$scope.word = /^\w*$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Single word: <input type="text" name="input" ng-model="text"
ng-pattern="word" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if multi word', function() {
input('text').enter('hello world');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'text': textInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.number
*
* @description
* Text input with number validation and transformation. Sets the `number` validation
* error if not a valid number.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value = 12;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Number: <input type="number" name="input" ng-model="value"
min="0" max="99" required>
<span class="error" ng-show="myForm.list.$error.required">
Required!</span>
<span class="error" ng-show="myForm.list.$error.number">
Not valid number!</span>
<tt>value = {{value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('value')).toEqual('12');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('value').enter('');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if over max', function() {
input('value').enter('123');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'number': numberInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.url
*
* @description
* Text input with URL validation. Sets the `url` validation error key if the content is not a
* valid URL.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'http://google.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
URL: <input type="url" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('http://google.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not url', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'url': urlInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.email
*
* @description
* Text input with email validation. Sets the `email` validation error key if not a valid email
* address.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'me@example.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('me@example.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not email', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'email': emailInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.radio
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the expression should be set when selected.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.color = 'blue';
}
</script>
<form name="myForm" ng-controller="Ctrl">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" value="green"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('color')).toEqual('blue');
input('color').select('red');
expect(binding('color')).toEqual('red');
});
</doc:scenario>
</doc:example>
*/
'radio': radioInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.checkbox
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngTrueValue The value to which the expression should be set when selected.
* @param {string=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value1 = true;
$scope.value2 = 'YES'
}
</script>
<form name="myForm" ng-controller="Ctrl">
Value1: <input type="checkbox" ng-model="value1"> <br/>
Value2: <input type="checkbox" ng-model="value2"
ng-true-value="YES" ng-false-value="NO"> <br/>
<tt>value1 = {{value1}}</tt><br/>
<tt>value2 = {{value2}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('value1')).toEqual('true');
expect(binding('value2')).toEqual('YES');
input('value1').check();
input('value2').check();
expect(binding('value1')).toEqual('false');
expect(binding('value2')).toEqual('NO');
});
</doc:scenario>
</doc:example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop
};
function isEmpty(value) {
return isUndefined(value) || value === '' || value === null || value !== value;
}
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var listener = function() {
var value = trim(element.val());
if (ctrl.$viewValue !== value) {
scope.$apply(function() {
ctrl.$setViewValue(value);
});
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.bind('input', listener);
} else {
var timeout;
var deferListener = function() {
if (!timeout) {
timeout = $browser.defer(function() {
listener();
timeout = null;
});
}
};
element.bind('keydown', function(event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
deferListener();
});
// if user paste into input using mouse, we need "change" event to catch it
element.bind('change', listener);
// if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
if ($sniffer.hasEvent('paste')) {
element.bind('paste cut', deferListener);
}
}
ctrl.$render = function() {
element.val(isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
};
// pattern validator
var pattern = attr.ngPattern,
patternValidator;
var validate = function(regexp, value) {
if (isEmpty(value) || regexp.test(value)) {
ctrl.$setValidity('pattern', true);
return value;
} else {
ctrl.$setValidity('pattern', false);
return undefined;
}
};
if (pattern) {
if (pattern.match(/^\/(.*)\/$/)) {
pattern = new RegExp(pattern.substr(1, pattern.length - 2));
patternValidator = function(value) {
return validate(pattern, value)
};
} else {
patternValidator = function(value) {
var patternObj = scope.$eval(pattern);
if (!patternObj || !patternObj.test) {
throw new Error('Expected ' + pattern + ' to be a RegExp but was ' + patternObj);
}
return validate(patternObj, value);
};
}
ctrl.$formatters.push(patternValidator);
ctrl.$parsers.push(patternValidator);
}
// min length validator
if (attr.ngMinlength) {
var minlength = int(attr.ngMinlength);
var minLengthValidator = function(value) {
if (!isEmpty(value) && value.length < minlength) {
ctrl.$setValidity('minlength', false);
return undefined;
} else {
ctrl.$setValidity('minlength', true);
return value;
}
};
ctrl.$parsers.push(minLengthValidator);
ctrl.$formatters.push(minLengthValidator);
}
// max length validator
if (attr.ngMaxlength) {
var maxlength = int(attr.ngMaxlength);
var maxLengthValidator = function(value) {
if (!isEmpty(value) && value.length > maxlength) {
ctrl.$setValidity('maxlength', false);
return undefined;
} else {
ctrl.$setValidity('maxlength', true);
return value;
}
};
ctrl.$parsers.push(maxLengthValidator);
ctrl.$formatters.push(maxLengthValidator);
}
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$parsers.push(function(value) {
var empty = isEmpty(value);
if (empty || NUMBER_REGEXP.test(value)) {
ctrl.$setValidity('number', true);
return value === '' ? null : (empty ? value : parseFloat(value));
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
ctrl.$formatters.push(function(value) {
return isEmpty(value) ? '' : '' + value;
});
if (attr.min) {
var min = parseFloat(attr.min);
var minValidator = function(value) {
if (!isEmpty(value) && value < min) {
ctrl.$setValidity('min', false);
return undefined;
} else {
ctrl.$setValidity('min', true);
return value;
}
};
ctrl.$parsers.push(minValidator);
ctrl.$formatters.push(minValidator);
}
if (attr.max) {
var max = parseFloat(attr.max);
var maxValidator = function(value) {
if (!isEmpty(value) && value > max) {
ctrl.$setValidity('max', false);
return undefined;
} else {
ctrl.$setValidity('max', true);
return value;
}
};
ctrl.$parsers.push(maxValidator);
ctrl.$formatters.push(maxValidator);
}
ctrl.$formatters.push(function(value) {
if (isEmpty(value) || isNumber(value)) {
ctrl.$setValidity('number', true);
return value;
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var urlValidator = function(value) {
if (isEmpty(value) || URL_REGEXP.test(value)) {
ctrl.$setValidity('url', true);
return value;
} else {
ctrl.$setValidity('url', false);
return undefined;
}
};
ctrl.$formatters.push(urlValidator);
ctrl.$parsers.push(urlValidator);
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var emailValidator = function(value) {
if (isEmpty(value) || EMAIL_REGEXP.test(value)) {
ctrl.$setValidity('email', true);
return value;
} else {
ctrl.$setValidity('email', false);
return undefined;
}
};
ctrl.$formatters.push(emailValidator);
ctrl.$parsers.push(emailValidator);
}
function radioInputType(scope, element, attr, ctrl) {
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
element.bind('click', function() {
if (element[0].checked) {
scope.$apply(function() {
ctrl.$setViewValue(attr.value);
});
}
});
ctrl.$render = function() {
var value = attr.value;
element[0].checked = (value == ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function checkboxInputType(scope, element, attr, ctrl) {
var trueValue = attr.ngTrueValue,
falseValue = attr.ngFalseValue;
if (!isString(trueValue)) trueValue = true;
if (!isString(falseValue)) falseValue = false;
element.bind('click', function() {
scope.$apply(function() {
ctrl.$setViewValue(element[0].checked);
});
});
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
ctrl.$formatters.push(function(value) {
return value === trueValue;
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name ng.directive:textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-binding and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*/
/**
* @ngdoc directive
* @name ng.directive:input
* @restrict E
*
* @description
* HTML input element control with angular data-binding. Input control follows HTML5 input types
* and polyfills the HTML5 validation behavior for older browsers.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {boolean=} ngRequired Sets `required` attribute if set to true
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}
</script>
<div ng-controller="Ctrl">
<form name="myForm">
User name: <input type="text" name="userName" ng-model="user.name" required>
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span><br>
Last name: <input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span><br>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
<tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
</div>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if empty when required', function() {
input('user.name').enter('');
expect(binding('user')).toEqual('{"last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('false');
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be valid if empty when min length is set', function() {
input('user.last').enter('');
expect(binding('user')).toEqual('{"name":"guest","last":""}');
expect(binding('myForm.lastName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if less than required min length', function() {
input('user.last').enter('xx');
expect(binding('user')).toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be invalid if longer than max length', function() {
input('user.last').enter('some ridiculously long name');
expect(binding('user'))
.toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attr, ctrl) {
if (ctrl) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
$browser);
}
}
};
}];
var VALID_CLASS = 'ng-valid',
INVALID_CLASS = 'ng-invalid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty';
/**
* @ngdoc object
* @name ng.directive:ngModel.NgModelController
*
* @property {string} $viewValue Actual string value in the view.
* @property {*} $modelValue The value in the model, that the control is bound to.
* @property {Array.<Function>} $parsers Whenever the control reads value from the DOM, it executes
* all of these functions to sanitize / convert the value as well as validate.
*
* @property {Array.<Function>} $formatters Whenever the model value changes, it executes all of
* these functions to convert the value as well as validate.
*
* @property {Object} $error An bject hash with all errors as keys.
*
* @property {boolean} $pristine True if user has not interacted with the control yet.
* @property {boolean} $dirty True if user has already interacted with the control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
*
* @description
*
* `NgModelController` provides API for the `ng-model` directive. The controller contains
* services for data-binding, validation, CSS update, value formatting and parsing. It
* specifically does not contain any logic which deals with DOM rendering or listening to
* DOM events. The `NgModelController` is meant to be extended by other directives where, the
* directive provides DOM manipulation and the `NgModelController` provides the data-binding.
*
* This example shows how to use `NgModelController` with a custom control to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
* collaborate together to achieve the desired result.
*
* <example module="customControl">
<file name="style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name="script.js">
angular.module('customControl', []).
directive('contenteditable', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.bind('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
ngModel.$setViewValue(element.html());
}
}
};
});
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent"></textarea>
</form>
</file>
<file name="scenario.js">
it('should data-bind and become invalid', function() {
var contentEditable = element('[contenteditable]');
expect(contentEditable.text()).toEqual('Change me!');
input('userContent').enter('');
expect(contentEditable.text()).toEqual('');
expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/);
});
</file>
* </example>
*
*/
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse',
function($scope, $exceptionHandler, $attr, $element, $parse) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$pristine = true;
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
this.$name = $attr.name;
var ngModelGet = $parse($attr.ngModel),
ngModelSet = ngModelGet.assign;
if (!ngModelSet) {
throw Error(NON_ASSIGNABLE_MODEL_EXPRESSION + $attr.ngModel +
' (' + startingTag($element) + ')');
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$render
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Called when the view needs to be updated. It is expected that the user of the ng-model
* directive will implement this method.
*/
this.$render = noop;
var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
$error = this.$error = {}; // keep invalid keys here
// Setup initial state of the control
$element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
$element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setValidity
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Change the validity state, and notifies the form when the control changes validity. (i.e. it
* does not notify form if given validator is already marked as invalid).
*
* This method should be called by validators - i.e. the parser or formatter functions.
*
* @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
* to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
*/
this.$setValidity = function(validationErrorKey, isValid) {
if ($error[validationErrorKey] === !isValid) return;
if (isValid) {
if ($error[validationErrorKey]) invalidCount--;
if (!invalidCount) {
toggleValidCss(true);
this.$valid = true;
this.$invalid = false;
}
} else {
toggleValidCss(false);
this.$invalid = true;
this.$valid = false;
invalidCount++;
}
$error[validationErrorKey] = !isValid;
toggleValidCss(isValid, validationErrorKey);
parentForm.$setValidity(validationErrorKey, isValid, this);
};
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setViewValue
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Read a value from view.
*
* This method should be called from within a DOM event handler.
* For example {@link ng.directive:input input} or
* {@link ng.directive:select select} directives call it.
*
* It internally calls all `parsers` and if resulted value is valid, updates the model and
* calls all registered change listeners.
*
* @param {string} value Value from the view.
*/
this.$setViewValue = function(value) {
this.$viewValue = value;
// change to dirty
if (this.$pristine) {
this.$dirty = true;
this.$pristine = false;
$element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
parentForm.$setDirty();
}
forEach(this.$parsers, function(fn) {
value = fn(value);
});
if (this.$modelValue !== value) {
this.$modelValue = value;
ngModelSet($scope, value);
forEach(this.$viewChangeListeners, function(listener) {
try {
listener();
} catch(e) {
$exceptionHandler(e);
}
})
}
};
// model -> value
var ctrl = this;
$scope.$watch(function ngModelWatch() {
var value = ngModelGet($scope);
// if scope model value and ngModel value are out of sync
if (ctrl.$modelValue !== value) {
var formatters = ctrl.$formatters,
idx = formatters.length;
ctrl.$modelValue = value;
while(idx--) {
value = formatters[idx](value);
}
if (ctrl.$viewValue !== value) {
ctrl.$viewValue = value;
ctrl.$render();
}
}
});
}];
/**
* @ngdoc directive
* @name ng.directive:ngModel
*
* @element input
*
* @description
* Is directive that tells Angular to do two-way data binding. It works together with `input`,
* `select`, `textarea`. You can easily write your own directives to use `ngModel` as well.
*
* `ngModel` is responsible for:
*
* - binding the view into the model, which other directives such as `input`, `textarea` or `select`
* require,
* - providing validation behavior (i.e. required, number, email, url),
* - keeping state of the control (valid/invalid, dirty/pristine, validation errors),
* - setting related css class onto the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`),
* - register the control with parent {@link ng.directive:form form}.
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link ng.directive:input.text text}
* - {@link ng.directive:input.checkbox checkbox}
* - {@link ng.directive:input.radio radio}
* - {@link ng.directive:input.number number}
* - {@link ng.directive:input.email email}
* - {@link ng.directive:input.url url}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
*/
var ngModelDirective = function() {
return {
require: ['ngModel', '^?form'],
controller: NgModelController,
link: function(scope, element, attr, ctrls) {
// notify others, especially parent forms
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || nullFormCtrl;
formCtrl.$addControl(modelCtrl);
element.bind('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngChange
* @restrict E
*
* @description
* Evaluate given expression when user changes the input.
* The expression is not evaluated when the value change is coming from the model.
*
* Note, this directive requires `ngModel` to be present.
*
* @element input
*
* @example
* <doc:example>
* <doc:source>
* <script>
* function Controller($scope) {
* $scope.counter = 0;
* $scope.change = function() {
* $scope.counter++;
* };
* }
* </script>
* <div ng-controller="Controller">
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
* <label for="ng-change-example2">Confirmed</label><br />
* debug = {{confirmed}}<br />
* counter = {{counter}}
* </div>
* </doc:source>
* <doc:scenario>
* it('should evaluate the expression if changing from view', function() {
* expect(binding('counter')).toEqual('0');
* element('#ng-change-example1').click();
* expect(binding('counter')).toEqual('1');
* expect(binding('confirmed')).toEqual('true');
* });
*
* it('should not evaluate the expression if changing from model', function() {
* element('#ng-change-example2').click();
* expect(binding('counter')).toEqual('0');
* expect(binding('confirmed')).toEqual('true');
* });
* </doc:scenario>
* </doc:example>
*/
var ngChangeDirective = valueFn({
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$viewChangeListeners.push(function() {
scope.$eval(attr.ngChange);
});
}
});
var requiredDirective = function() {
return {
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
var validator = function(value) {
if (attr.required && (isEmpty(value) || value === false)) {
ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
attr.$observe('required', function() {
validator(ctrl.$viewValue);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngList
*
* @description
* Text input that converts between comma-separated string into an array of strings.
*
* @element input
* @param {string=} ngList optional delimiter that should be used to split the value. If
* specified in form `/something/` then the value will be converted into a regular expression.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.names = ['igor', 'misko', 'vojta'];
}
</script>
<form name="myForm" ng-controller="Ctrl">
List: <input name="namesInput" ng-model="names" ng-list required>
<span class="error" ng-show="myForm.list.$error.required">
Required!</span>
<tt>names = {{names}}</tt><br/>
<tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
<tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('names')).toEqual('["igor","misko","vojta"]');
expect(binding('myForm.namesInput.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('names').enter('');
expect(binding('names')).toEqual('[]');
expect(binding('myForm.namesInput.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var ngListDirective = function() {
return {
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
var match = /\/(.*)\//.exec(attr.ngList),
separator = match && new RegExp(match[1]) || attr.ngList || ',';
var parse = function(viewValue) {
var list = [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trim(value));
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value)) {
return value.join(', ');
}
return undefined;
});
}
};
};
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
var ngValueDirective = function() {
return {
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function(scope, elm, attr) {
scope.$watch(attr.ngValue, function valueWatchAction(value) {
attr.$set('value', value, false);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngBind
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* One scenario in which the use of `ngBind` is preferred over `{{ expression }}` binding is when
* it's desirable to put bindings into template that is momentarily displayed by the browser in its
* raw state before Angular compiles it. Since `ngBind` is an element attribute, it makes the
* bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.name = 'Whirled';
}
</script>
<div ng-controller="Ctrl">
Enter name: <input type="text" ng-model="name"><br>
Hello <span ng-bind="name"></span>!
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('name')).toBe('Whirled');
using('.doc-example-live').input('name').enter('world');
expect(using('.doc-example-live').binding('name')).toBe('world');
});
</doc:scenario>
</doc:example>
*/
var ngBindDirective = ngDirective(function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBind);
scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
element.text(value == undefined ? '' : value);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text should be replaced with the template in ngBindTemplate.
* Unlike ngBind the ngBindTemplate can contain multiple `{{` `}}`
* expressions. (This is required since some HTML elements
* can not have SPAN elements such as TITLE, or OPTION to name a few.)
*
* @element ANY
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.salutation = 'Hello';
$scope.name = 'World';
}
</script>
<div ng-controller="Ctrl">
Salutation: <input type="text" ng-model="salutation"><br>
Name: <input type="text" ng-model="name"><br>
<pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('salutation')).
toBe('Hello');
expect(using('.doc-example-live').binding('name')).
toBe('World');
using('.doc-example-live').input('salutation').enter('Greetings');
using('.doc-example-live').input('name').enter('user');
expect(using('.doc-example-live').binding('salutation')).
toBe('Greetings');
expect(using('.doc-example-live').binding('name')).
toBe('user');
});
</doc:scenario>
</doc:example>
*/
var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
return function(scope, element, attr) {
// TODO: move this to scenario runner
var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
element.addClass('ng-binding').data('$binding', interpolateFn);
attr.$observe('ngBindTemplate', function(value) {
element.text(value);
});
}
}];
/**
* @ngdoc directive
* @name ng.directive:ngBindHtmlUnsafe
*
* @description
* Creates a binding that will innerHTML the result of evaluating the `expression` into the current
* element. *The innerHTML-ed content will not be sanitized!* You should use this directive only if
* {@link ngSanitize.directive:ngBindHtml ngBindHtml} directive is too
* restrictive and when you absolutely trust the source of the content you are binding to.
*
* See {@link ngSanitize.$sanitize $sanitize} docs for examples.
*
* @element ANY
* @param {expression} ngBindHtmlUnsafe {@link guide/expression Expression} to evaluate.
*/
var ngBindHtmlUnsafeDirective = [function() {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
scope.$watch(attr.ngBindHtmlUnsafe, function ngBindHtmlUnsafeWatchAction(value) {
element.html(value || '');
});
};
}];
function classDirective(name, selector) {
name = 'ngClass' + name;
return ngDirective(function(scope, element, attr) {
var oldVal = undefined;
scope.$watch(attr[name], ngClassWatchAction, true);
attr.$observe('class', function(value) {
var ngClass = scope.$eval(attr[name]);
ngClassWatchAction(ngClass, ngClass);
});
if (name !== 'ngClass') {
scope.$watch('$index', function($index, old$index) {
var mod = $index & 1;
if (mod !== old$index & 1) {
if (mod === selector) {
addClass(scope.$eval(attr[name]));
} else {
removeClass(scope.$eval(attr[name]));
}
}
});
}
function ngClassWatchAction(newVal) {
if (selector === true || scope.$index % 2 === selector) {
if (oldVal && !equals(newVal,oldVal)) {
removeClass(oldVal);
}
addClass(newVal);
}
oldVal = copy(newVal);
}
function removeClass(classVal) {
if (isObject(classVal) && !isArray(classVal)) {
classVal = map(classVal, function(v, k) { if (v) return k });
}
element.removeClass(isArray(classVal) ? classVal.join(' ') : classVal);
}
function addClass(classVal) {
if (isObject(classVal) && !isArray(classVal)) {
classVal = map(classVal, function(v, k) { if (v) return k });
}
if (classVal) {
element.addClass(isArray(classVal) ? classVal.join(' ') : classVal);
}
}
});
}
/**
* @ngdoc directive
* @name ng.directive:ngClass
*
* @description
* The `ngClass` allows you to set CSS class on HTML element dynamically by databinding an
* expression that represents all classes to be added.
*
* The directive won't add duplicate classes if a particular class was already set.
*
* When the expression changes, the previously added classes are removed and only then the
* new classes are added.
*
* @element ANY
* @param {expression} ngClass {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class
* names, an array, or a map of class names to boolean values.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myVar='my-class'">
<input type="button" value="clear" ng-click="myVar=''">
<br>
<span ng-class="myVar">Sample Text</span>
</file>
<file name="style.css">
.my-class {
color: red;
}
</file>
<file name="scenario.js">
it('should check ng-class', function() {
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
using('.doc-example-live').element(':button:first').click();
expect(element('.doc-example-live span').prop('className')).
toMatch(/my-class/);
using('.doc-example-live').element(':button:last').click();
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
});
</file>
</example>
*/
var ngClassDirective = classDirective('', true);
/**
* @ngdoc directive
* @name ng.directive:ngClassOdd
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassOddDirective = classDirective('Odd', 0);
/**
* @ngdoc directive
* @name ng.directive:ngClassEven
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except it works in
* conjunction with `ngRepeat` and takes affect only on odd (even) rows.
*
* This directive can be applied only within a scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
* result of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassEvenDirective = classDirective('Even', 1);
/**
* @ngdoc directive
* @name ng.directive:ngCloak
*
* @description
* The `ngCloak` directive is used to prevent the Angular html template from being briefly
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html template display.
*
* The directive can be applied to the `<body>` element, but typically a fine-grained application is
* prefered in order to benefit from progressive rendering of the browser view.
*
* `ngCloak` works in cooperation with a css rule that is embedded within `angular.js` and
* `angular.min.js` files. Following is the css rule:
*
* <pre>
* [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
* display: none;
* }
* </pre>
*
* When this css rule is loaded by the browser, all html elements (including their children) that
* are tagged with the `ng-cloak` directive are hidden. When Angular comes across this directive
* during the compilation of the template it deletes the `ngCloak` element attribute, which
* makes the compiled element visible.
*
* For the best result, `angular.js` script must be loaded in the head section of the html file;
* alternatively, the css rule (above) must be included in the external stylesheet of the
* application.
*
* Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
* cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
* class `ngCloak` in addition to `ngCloak` directive as shown in the example below.
*
* @element ANY
*
* @example
<doc:example>
<doc:source>
<div id="template1" ng-cloak>{{ 'hello' }}</div>
<div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
</doc:source>
<doc:scenario>
it('should remove the template directive and css class', function() {
expect(element('.doc-example-live #template1').attr('ng-cloak')).
not().toBeDefined();
expect(element('.doc-example-live #template2').attr('ng-cloak')).
not().toBeDefined();
});
</doc:scenario>
</doc:example>
*
*/
var ngCloakDirective = ngDirective({
compile: function(element, attr) {
attr.$set('ngCloak', undefined);
element.removeClass('ng-cloak');
}
});
/**
* @ngdoc directive
* @name ng.directive:ngController
*
* @description
* The `ngController` directive assigns behavior to a scope. This is a key aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
* * Model — The Model is data in scope properties; scopes are attached to the DOM.
* * View — The template (HTML with data bindings) is rendered into the View.
* * Controller — The `ngController` directive specifies a Controller class; the class has
* methods that typically express the business logic behind the application.
*
* Note that an alternative way to define controllers is via the {@link ng.$route $route} service.
*
* @element ANY
* @scope
* @param {expression} ngController Name of a globally accessible constructor function or an
* {@link guide/expression expression} that on the current scope evaluates to a
* constructor function.
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
* greeting are methods declared on the controller (see source tab). These methods can
* easily be called from the angular markup. Notice that the scope becomes the `this` for the
* controller's instance. This allows for easy access to the view data from the controller. Also
* notice that any changes to the data are automatically reflected in the View without the need
* for a manual update.
<doc:example>
<doc:source>
<script>
function SettingsController($scope) {
$scope.name = "John Smith";
$scope.contacts = [
{type:'phone', value:'408 555 1212'},
{type:'email', value:'john.smith@example.org'} ];
$scope.greet = function() {
alert(this.name);
};
$scope.addContact = function() {
this.contacts.push({type:'email', value:'yourname@example.org'});
};
$scope.removeContact = function(contactToRemove) {
var index = this.contacts.indexOf(contactToRemove);
this.contacts.splice(index, 1);
};
$scope.clearContact = function(contact) {
contact.type = 'phone';
contact.value = '';
};
}
</script>
<div ng-controller="SettingsController">
Name: <input type="text" ng-model="name"/>
[ <a href="" ng-click="greet()">greet</a> ]<br/>
Contact:
<ul>
<li ng-repeat="contact in contacts">
<select ng-model="contact.type">
<option>phone</option>
<option>email</option>
</select>
<input type="text" ng-model="contact.value"/>
[ <a href="" ng-click="clearContact(contact)">clear</a>
| <a href="" ng-click="removeContact(contact)">X</a> ]
</li>
<li>[ <a href="" ng-click="addContact()">add</a> ]</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check controller', function() {
expect(element('.doc-example-live div>:input').val()).toBe('John Smith');
expect(element('.doc-example-live li:nth-child(1) input').val())
.toBe('408 555 1212');
expect(element('.doc-example-live li:nth-child(2) input').val())
.toBe('john.smith@example.org');
element('.doc-example-live li:first a:contains("clear")').click();
expect(element('.doc-example-live li:first input').val()).toBe('');
element('.doc-example-live li:last a:contains("add")').click();
expect(element('.doc-example-live li:nth-child(3) input').val())
.toBe('yourname@example.org');
});
</doc:scenario>
</doc:example>
*/
var ngControllerDirective = [function() {
return {
scope: true,
controller: '@'
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngCsp
* @priority 1000
*
* @element html
* @description
* Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
*
* This is necessary when developing things like Google Chrome Extensions.
*
* CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
* For us to be compatible, we just need to implement the "getterFn" in $parse without violating
* any of these restrictions.
*
* AngularJS uses `Function(string)` generated functions as a speed optimization. By applying `ngCsp`
* it is be possible to opt into the CSP compatible mode. When this mode is on AngularJS will
* evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
* be raised.
*
* In order to use this feature put `ngCsp` directive on the root element of the application.
*
* @example
* This example shows how to apply the `ngCsp` directive to the `html` tag.
<pre>
<!doctype html>
<html ng-app ng-csp>
...
...
</html>
</pre>
*/
var ngCspDirective = ['$sniffer', function($sniffer) {
return {
priority: 1000,
compile: function() {
$sniffer.csp = true;
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngClick
*
* @description
* The ngClick allows you to specify custom behavior when
* element is clicked.
*
* @element ANY
* @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
* click. (Event object is available as `$event`)
*
* @example
<doc:example>
<doc:source>
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
count: {{count}}
</doc:source>
<doc:scenario>
it('should check ng-click', function() {
expect(binding('count')).toBe('0');
element('.doc-example-live :button').click();
expect(binding('count')).toBe('1');
});
</doc:scenario>
</doc:example>
*/
/*
* A directive that allows creation of custom onclick handlers that are defined as angular
* expressions and are compiled and executed within the current scope.
*
* Events that are handled via these handler are always configured not to propagate further.
*/
var ngEventDirectives = {};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave'.split(' '),
function(name) {
var directiveName = directiveNormalize('ng-' + name);
ngEventDirectives[directiveName] = ['$parse', function($parse) {
return function(scope, element, attr) {
var fn = $parse(attr[directiveName]);
element.bind(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}];
}
);
/**
* @ngdoc directive
* @name ng.directive:ngDblclick
*
* @description
* The `ngDblclick` directive allows you to specify custom behavior on dblclick event.
*
* @element ANY
* @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
* dblclick. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousedown
*
* @description
* The ngMousedown directive allows you to specify custom behavior on mousedown event.
*
* @element ANY
* @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
* mousedown. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseup
*
* @description
* Specify custom behavior on mouseup event.
*
* @element ANY
* @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
* mouseup. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseover
*
* @description
* Specify custom behavior on mouseover event.
*
* @element ANY
* @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
* mouseover. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseenter
*
* @description
* Specify custom behavior on mouseenter event.
*
* @element ANY
* @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
* mouseenter. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseleave
*
* @description
* Specify custom behavior on mouseleave event.
*
* @element ANY
* @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
* mouseleave. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousemove
*
* @description
* Specify custom behavior on mousemove event.
*
* @element ANY
* @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
* mousemove. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngSubmit
*
* @description
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sending the request to the
* server and reloading the current page).
*
* @element form
* @param {expression} ngSubmit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if (this.text) {
this.list.push(this.text);
this.text = '';
}
};
}
</script>
<form ng-submit="submit()" ng-controller="Ctrl">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>
</doc:source>
<doc:scenario>
it('should check ng-submit', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
expect(input('text').val()).toBe('');
});
it('should ignore empty strings', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
});
</doc:scenario>
</doc:example>
*/
var ngSubmitDirective = ngDirective(function(scope, element, attrs) {
element.bind('submit', function() {
scope.$apply(attrs.ngSubmit);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngInclude
* @restrict ECA
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* Keep in mind that Same Origin Policy applies to included resources
* (e.g. ngInclude won't work for cross-domain requests on all browsers and for
* file:// access on some browsers).
*
* @scope
*
* @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
* @param {string=} onload Expression to evaluate when a new partial is loaded.
*
* @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the content is loaded.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the expression evaluates to truthy value.
*
* @example
<example>
<file name="index.html">
<div ng-controller="Ctrl">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
<div ng-include src="template.url"></div>
</div>
</file>
<file name="script.js">
function Ctrl($scope) {
$scope.templates =
[ { name: 'template1.html', url: 'template1.html'}
, { name: 'template2.html', url: 'template2.html'} ];
$scope.template = $scope.templates[0];
}
</file>
<file name="template1.html">
Content of template1.html
</file>
<file name="template2.html">
Content of template2.html
</file>
<file name="scenario.js">
it('should load template1.html', function() {
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template1.html/);
});
it('should load template2.html', function() {
select('template').option('1');
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template2.html/);
});
it('should change to blank', function() {
select('template').option('');
expect(element('.doc-example-live [ng-include]').text()).toEqual('');
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngInclude#$includeContentLoaded
* @eventOf ng.directive:ngInclude
* @eventType emit on the current ngInclude scope
* @description
* Emitted every time the ngInclude content is reloaded.
*/
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile',
function($http, $templateCache, $anchorScroll, $compile) {
return {
restrict: 'ECA',
terminal: true,
compile: function(element, attr) {
var srcExp = attr.ngInclude || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
return function(scope, element) {
var changeCounter = 0,
childScope;
var clearContent = function() {
if (childScope) {
childScope.$destroy();
childScope = null;
}
element.html('');
};
scope.$watch(srcExp, function ngIncludeWatchAction(src) {
var thisChangeId = ++changeCounter;
if (src) {
$http.get(src, {cache: $templateCache}).success(function(response) {
if (thisChangeId !== changeCounter) return;
if (childScope) childScope.$destroy();
childScope = scope.$new();
element.html(response);
$compile(element.contents())(childScope);
if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
childScope.$emit('$includeContentLoaded');
scope.$eval(onloadExp);
}).error(function() {
if (thisChangeId === changeCounter) clearContent();
});
} else clearContent();
});
};
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngInit
*
* @description
* The `ngInit` directive specifies initialization tasks to be executed
* before the template enters execution mode during bootstrap.
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<div ng-init="greeting='Hello'; person='World'">
{{greeting}} {{person}}!
</div>
</doc:source>
<doc:scenario>
it('should check greeting', function() {
expect(binding('greeting')).toBe('Hello');
expect(binding('person')).toBe('World');
});
</doc:scenario>
</doc:example>
*/
var ngInitDirective = ngDirective({
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
}
}
});
/**
* @ngdoc directive
* @name ng.directive:ngNonBindable
* @priority 1000
*
* @description
* Sometimes it is necessary to write code which looks like bindings but which should be left alone
* by angular. Use `ngNonBindable` to make angular ignore a chunk of HTML.
*
* @element ANY
*
* @example
* In this example there are two location where a simple binding (`{{}}`) is present, but the one
* wrapped in `ngNonBindable` is left alone.
*
* @example
<doc:example>
<doc:source>
<div>Normal: {{1 + 2}}</div>
<div ng-non-bindable>Ignored: {{1 + 2}}</div>
</doc:source>
<doc:scenario>
it('should check ng-non-bindable', function() {
expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
expect(using('.doc-example-live').element('div:last').text()).
toMatch(/1 \+ 2/);
});
</doc:scenario>
</doc:example>
*/
var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
/**
* @ngdoc directive
* @name ng.directive:ngPluralize
* @restrict EA
*
* @description
* # Overview
* `ngPluralize` is a directive that displays messages according to en-US localization rules.
* These rules are bundled with angular.js and the rules can be overridden
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
* by specifying the mappings between
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} in Angular's default en-US locale: "one" and "other".
*
* While a pural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
* explicit number rule for "3" matches the number 3. You will see the use of plural categories
* and explicit number rules throughout later parts of this documentation.
*
* # Configuring ngPluralize
* You configure ngPluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link guide/expression
* Angular expression}; these are evaluated on the current scope for its bound value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
* string to be displayed. The value of the attribute should be a JSON object so that Angular
* can interpret it correctly.
*
* The following example shows how to configure ngPluralize:
*
* <pre>
* <ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng-pluralize>
*</pre>
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
* for <span ng-non-bindable>{{numberExpression}}</span>.
*
* # Configuring ngPluralize with offset
* The `offset` attribute allows further customization of pluralized text, which can result in
* a better user experience. For example, instead of the message "4 people are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* <pre>
* <ng-pluralize count="personCount" offset=2
* when="{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other person are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
* </ng-pluralize>
* </pre>
*
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
* In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bounded to.
* @param {string} when The mapping between plural category to its correspoding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.person1 = 'Igor';
$scope.person2 = 'Misko';
$scope.personCount = 1;
}
</script>
<div ng-controller="Ctrl">
Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
<!--- Example with simple pluralization rules for en locale --->
Without Offset:
<ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng-pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng-pluralize count="personCount" offset=2
when="{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewing.',
'one': '{{person1}}, {{person2}} and one other person are viewing.',
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng-pluralize>
</div>
</doc:source>
<doc:scenario>
it('should show correct pluralized string', function() {
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('1 person is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor is viewing.');
using('.doc-example-live').input('personCount').enter('0');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('Nobody is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Nobody is viewing.');
using('.doc-example-live').input('personCount').enter('2');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('2 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor and Misko are viewing.');
using('.doc-example-live').input('personCount').enter('3');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('3 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and one other person are viewing.');
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('4 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
});
it('should show data-binded names', function() {
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
using('.doc-example-live').input('person1').enter('Di');
using('.doc-example-live').input('person2').enter('Vojta');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Di, Vojta and 2 other people are viewing.');
});
</doc:scenario>
</doc:example>
*/
var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
var BRACE = /{}/g;
return {
restrict: 'EA',
link: function(scope, element, attr) {
var numberExp = attr.count,
whenExp = element.attr(attr.$attr.when), // this is because we have {{}} in attrs
offset = attr.offset || 0,
whens = scope.$eval(whenExp),
whensExpFns = {},
startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol();
forEach(whens, function(expression, key) {
whensExpFns[key] =
$interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
offset + endSymbol));
});
scope.$watch(function ngPluralizeWatch() {
var value = parseFloat(scope.$eval(numberExp));
if (!isNaN(value)) {
//if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
//check it against pluralization rules in $locale service
if (!(value in whens)) value = $locale.pluralCat(value - offset);
return whensExpFns[value](scope, element, true);
} else {
return '';
}
}, function ngPluralizeWatchAction(newVal) {
element.text(newVal);
});
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngRepeat
*
* @description
* The `ngRepeat` directive instantiates a template once per item from a collection. Each template
* instance gets its own scope, where the given loop variable is set to the current collection item,
* and `$index` is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* * `$index` – `{number}` – iterator offset of the repeated element (0..length-1)
* * `$first` – `{boolean}` – true if the repeated element is first in the iterator.
* * `$middle` – `{boolean}` – true if the repeated element is between the first and last in the iterator.
* * `$last` – `{boolean}` – true if the repeated element is last in the iterator.
*
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. Two
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `track in cd.tracks`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', age:25}, {name:'Mary', age:28}]">
I have {{friends.length}} friends. They are:
<ul>
<li ng-repeat="friend in friends">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check ng-repeat', function() {
var r = using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(2);
expect(r.row(0)).toEqual(["1","John","25"]);
expect(r.row(1)).toEqual(["2","Mary","28"]);
});
</doc:scenario>
</doc:example>
*/
var ngRepeatDirective = ngDirective({
transclude: 'element',
priority: 1000,
terminal: true,
compile: function(element, attr, linker) {
return function(scope, iterStartElement, attr){
var expression = attr.ngRepeat;
var match = expression.match(/^\s*(.+)\s+in\s+(.*)\s*$/),
lhs, rhs, valueIdent, keyIdent;
if (! match) {
throw Error("Expected ngRepeat in form of '_item_ in _collection_' but got '" +
expression + "'.");
}
lhs = match[1];
rhs = match[2];
match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!match) {
throw Error("'item' in 'item in collection' should be identifier or (key, value) but got '" +
lhs + "'.");
}
valueIdent = match[3] || match[1];
keyIdent = match[2];
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is an array of objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
// We need an array of these objects since the same object can be returned from the iterator.
// We expect this to be a rare case.
var lastOrder = new HashQueueMap();
scope.$watch(function ngRepeatWatch(scope){
var index, length,
collection = scope.$eval(rhs),
cursor = iterStartElement, // current position of the node
// Same as lastOrder but it has the current state. It will become the
// lastOrder on the next iteration.
nextOrder = new HashQueueMap(),
arrayBound,
childScope,
key, value, // key/value of iteration
array,
last; // last object information {scope, element, index}
if (!isArray(collection)) {
// if object, extract keys, sort them and use to determine order of iteration over obj props
array = [];
for(key in collection) {
if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
array.push(key);
}
}
array.sort();
} else {
array = collection || [];
}
arrayBound = array.length-1;
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = 0, length = array.length; index < length; index++) {
key = (collection === array) ? index : array[index];
value = collection[key];
last = lastOrder.shift(value);
if (last) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
childScope = last.scope;
nextOrder.push(value, last);
if (index === last.index) {
// do nothing
cursor = last.element;
} else {
// existing item which got moved
last.index = index;
// This may be a noop, if the element is next, but I don't know of a good way to
// figure this out, since it would require extra DOM access, so let's just hope that
// the browsers realizes that it is noop, and treats it as such.
cursor.after(last.element);
cursor = last.element;
}
} else {
// new item which we don't know about
childScope = scope.$new();
}
childScope[valueIdent] = value;
if (keyIdent) childScope[keyIdent] = key;
childScope.$index = index;
childScope.$first = (index === 0);
childScope.$last = (index === arrayBound);
childScope.$middle = !(childScope.$first || childScope.$last);
if (!last) {
linker(childScope, function(clone){
cursor.after(clone);
last = {
scope: childScope,
element: (cursor = clone),
index: index
};
nextOrder.push(value, last);
});
}
}
//shrink children
for (key in lastOrder) {
if (lastOrder.hasOwnProperty(key)) {
array = lastOrder[key];
while(array.length) {
value = array.pop();
value.element.remove();
value.scope.$destroy();
}
}
}
lastOrder = nextOrder;
});
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngShow
*
* @description
* The `ngShow` and `ngHide` directives show or hide a portion of the DOM tree (HTML)
* conditionally.
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when your checkbox is checked.</span> <br/>
Hide: <span ng-hide="checked">I hide when your checkbox is checked.</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngShowDirective = ngDirective(function(scope, element, attr){
scope.$watch(attr.ngShow, function ngShowWatchAction(value){
element.css('display', toBoolean(value) ? '' : 'none');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngHide
*
* @description
* The `ngHide` and `ngShow` directives hide or show a portion of the DOM tree (HTML)
* conditionally.
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} is truthy then
* the element is shown or hidden respectively.
*
* @example
<doc:example>
<doc:source>
Click me: <input type="checkbox" ng-model="checked"><br/>
Show: <span ng-show="checked">I show up when you checkbox is checked?</span> <br/>
Hide: <span ng-hide="checked">I hide when you checkbox is checked?</span>
</doc:source>
<doc:scenario>
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</doc:scenario>
</doc:example>
*/
//TODO(misko): refactor to remove element from the DOM
var ngHideDirective = ngDirective(function(scope, element, attr){
scope.$watch(attr.ngHide, function ngHideWatchAction(value){
element.css('display', toBoolean(value) ? 'none' : '');
});
});
/**
* @ngdoc directive
* @name ng.directive:ngStyle
*
* @description
* The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
*
* @element ANY
* @param {expression} ngStyle {@link guide/expression Expression} which evals to an
* object whose keys are CSS style names and values are corresponding values for those CSS
* keys.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myStyle={color:'red'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</file>
<file name="style.css">
span {
color: black;
}
</file>
<file name="scenario.js">
it('should check ng-style', function() {
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
element('.doc-example-live :button[value=set]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
element('.doc-example-live :button[value=clear]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
});
</file>
</example>
*/
var ngStyleDirective = ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) { element.css(style, '');});
}
if (newStyles) element.css(newStyles);
}, true);
});
/**
* @ngdoc directive
* @name ng.directive:ngSwitch
* @restrict EA
*
* @description
* Conditionally change the DOM structure.
*
* @usage
* <ANY ng-switch="expression">
* <ANY ng-switch-when="matchValue1">...</ANY>
* <ANY ng-switch-when="matchValue2">...</ANY>
* ...
* <ANY ng-switch-default>...</ANY>
* </ANY>
*
* @scope
* @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
* @paramDescription
* On child elments add:
*
* * `ngSwitchWhen`: the case statement to match against. If match then this
* case will be displayed.
* * `ngSwitchDefault`: the default case when no other casses match.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.items = ['settings', 'home', 'other'];
$scope.selection = $scope.items[0];
}
</script>
<div ng-controller="Ctrl">
<select ng-model="selection" ng-options="item for item in items">
</select>
<tt>selection={{selection}}</tt>
<hr/>
<div ng-switch on="selection" >
<div ng-switch-when="settings">Settings Div</div>
<span ng-switch-when="home">Home Span</span>
<span ng-switch-default>default</span>
</div>
</div>
</doc:source>
<doc:scenario>
it('should start in settings', function() {
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
});
it('should change to home', function() {
select('selection').option('home');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
});
it('should select deafault', function() {
select('selection').option('other');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
});
</doc:scenario>
</doc:example>
*/
var NG_SWITCH = 'ng-switch';
var ngSwitchDirective = valueFn({
restrict: 'EA',
require: 'ngSwitch',
// asks for $scope to fool the BC controller module
controller: ['$scope', function ngSwitchController() {
this.cases = {};
}],
link: function(scope, element, attr, ctrl) {
var watchExpr = attr.ngSwitch || attr.on,
selectedTransclude,
selectedElement,
selectedScope;
scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
if (selectedElement) {
selectedScope.$destroy();
selectedElement.remove();
selectedElement = selectedScope = null;
}
if ((selectedTransclude = ctrl.cases['!' + value] || ctrl.cases['?'])) {
scope.$eval(attr.change);
selectedScope = scope.$new();
selectedTransclude(selectedScope, function(caseElement) {
selectedElement = caseElement;
element.append(caseElement);
});
}
});
}
});
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 500,
require: '^ngSwitch',
compile: function(element, attrs, transclude) {
return function(scope, element, attr, ctrl) {
ctrl.cases['!' + attrs.ngSwitchWhen] = transclude;
};
}
});
var ngSwitchDefaultDirective = ngDirective({
transclude: 'element',
priority: 500,
require: '^ngSwitch',
compile: function(element, attrs, transclude) {
return function(scope, element, attr, ctrl) {
ctrl.cases['?'] = transclude;
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngTransclude
*
* @description
* Insert the transcluded DOM here.
*
* @element ANY
*
* @example
<doc:example module="transclude">
<doc:source>
<script>
function Ctrl($scope) {
$scope.title = 'Lorem Ipsum';
$scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
}
angular.module('transclude', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: 'isolate',
locals: { title:'bind' },
template: '<div style="border: 1px solid black;">' +
'<div style="background-color: gray">{{title}}</div>' +
'<div ng-transclude></div>' +
'</div>'
};
});
</script>
<div ng-controller="Ctrl">
<input ng-model="title"><br>
<textarea ng-model="text"></textarea> <br/>
<pane title="{{title}}">{{text}}</pane>
</div>
</doc:source>
<doc:scenario>
it('should have transcluded', function() {
input('title').enter('TITLE');
input('text').enter('TEXT');
expect(binding('title')).toEqual('TITLE');
expect(binding('text')).toEqual('TEXT');
});
</doc:scenario>
</doc:example>
*
*/
var ngTranscludeDirective = ngDirective({
controller: ['$transclude', '$element', function($transclude, $element) {
$transclude(function(clone) {
$element.append(clone);
});
}]
});
/**
* @ngdoc directive
* @name ng.directive:ngView
* @restrict ECA
*
* @description
* # Overview
* `ngView` is a directive that complements the {@link ng.$route $route} service by
* including the rendered template of the current route into the main layout (`index.html`) file.
* Every time the current route changes, the included view changes with it according to the
* configuration of the `$route` service.
*
* @scope
* @example
<example module="ngView">
<file name="index.html">
<div ng-controller="MainCntl">
Choose:
<a href="Book/Moby">Moby</a> |
<a href="Book/Moby/ch/1">Moby: Ch1</a> |
<a href="Book/Gatsby">Gatsby</a> |
<a href="Book/Gatsby/ch/4?key=value">Gatsby: Ch4</a> |
<a href="Book/Scarlet">Scarlet Letter</a><br/>
<div ng-view></div>
<hr />
<pre>$location.path() = {{$location.path()}}</pre>
<pre>$route.current.templateUrl = {{$route.current.templateUrl}}</pre>
<pre>$route.current.params = {{$route.current.params}}</pre>
<pre>$route.current.scope.name = {{$route.current.scope.name}}</pre>
<pre>$routeParams = {{$routeParams}}</pre>
</div>
</file>
<file name="book.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
</file>
<file name="chapter.html">
controller: {{name}}<br />
Book Id: {{params.bookId}}<br />
Chapter Id: {{params.chapterId}}
</file>
<file name="script.js">
angular.module('ngView', [], function($routeProvider, $locationProvider) {
$routeProvider.when('/Book/:bookId', {
templateUrl: 'book.html',
controller: BookCntl
});
$routeProvider.when('/Book/:bookId/ch/:chapterId', {
templateUrl: 'chapter.html',
controller: ChapterCntl
});
// configure html5 to get links working on jsfiddle
$locationProvider.html5Mode(true);
});
function MainCntl($scope, $route, $routeParams, $location) {
$scope.$route = $route;
$scope.$location = $location;
$scope.$routeParams = $routeParams;
}
function BookCntl($scope, $routeParams) {
$scope.name = "BookCntl";
$scope.params = $routeParams;
}
function ChapterCntl($scope, $routeParams) {
$scope.name = "ChapterCntl";
$scope.params = $routeParams;
}
</file>
<file name="scenario.js">
it('should load and compile correct template', function() {
element('a:contains("Moby: Ch1")').click();
var content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: ChapterCntl/);
expect(content).toMatch(/Book Id\: Moby/);
expect(content).toMatch(/Chapter Id\: 1/);
element('a:contains("Scarlet")').click();
content = element('.doc-example-live [ng-view]').text();
expect(content).toMatch(/controller\: BookCntl/);
expect(content).toMatch(/Book Id\: Scarlet/);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngView#$viewContentLoaded
* @eventOf ng.directive:ngView
* @eventType emit on the current ngView scope
* @description
* Emitted every time the ngView content is reloaded.
*/
var ngViewDirective = ['$http', '$templateCache', '$route', '$anchorScroll', '$compile',
'$controller',
function($http, $templateCache, $route, $anchorScroll, $compile,
$controller) {
return {
restrict: 'ECA',
terminal: true,
link: function(scope, element, attr) {
var lastScope,
onloadExp = attr.onload || '';
scope.$on('$routeChangeSuccess', update);
update();
function destroyLastScope() {
if (lastScope) {
lastScope.$destroy();
lastScope = null;
}
}
function clearContent() {
element.html('');
destroyLastScope();
}
function update() {
var locals = $route.current && $route.current.locals,
template = locals && locals.$template;
if (template) {
element.html(template);
destroyLastScope();
var link = $compile(element.contents()),
current = $route.current,
controller;
lastScope = current.scope = scope.$new();
if (current.controller) {
locals.$scope = lastScope;
controller = $controller(current.controller, locals);
element.children().data('$ngControllerController', controller);
}
link(lastScope);
lastScope.$emit('$viewContentLoaded');
lastScope.$eval(onloadExp);
// $anchorScroll might listen on event...
$anchorScroll();
} else {
clearContent();
}
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:script
*
* @description
* Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the
* template can be used by `ngInclude`, `ngView` or directive templates.
*
* @restrict E
* @param {'text/ng-template'} type must be set to `'text/ng-template'`
*
* @example
<doc:example>
<doc:source>
<script type="text/ng-template" id="/tpl.html">
Content of the template.
</script>
<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
<div id="tpl-content" ng-include src="currentTpl"></div>
</doc:source>
<doc:scenario>
it('should load template defined inside script tag', function() {
element('#tpl-link').click();
expect(element('#tpl-content').text()).toMatch(/Content of the template/);
});
</doc:scenario>
</doc:example>
*/
var scriptDirective = ['$templateCache', function($templateCache) {
return {
restrict: 'E',
terminal: true,
compile: function(element, attr) {
if (attr.type == 'text/ng-template') {
var templateUrl = attr.id,
// IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
text = element[0].text;
$templateCache.put(templateUrl, text);
}
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:select
* @restrict E
*
* @description
* HTML `SELECT` element with angular data-binding.
*
* # `ngOptions`
*
* Optionally `ngOptions` attribute can be used to dynamically generate a list of `<option>`
* elements for a `<select>` element using an array or an object obtained by evaluating the
* `ngOptions` expression.
*˝˝
* When an item in the select menu is select, the value of array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive of the parent select element.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent `null` or "not selected"
* option. See example below for demonstration.
*
* Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead
* of {@link ng.directive:ngRepeat ngRepeat} when you want the
* `select` model to be bound to a non-string value. This is because an option element can currently
* be bound to string values only.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required The control is considered valid only if value is entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {comprehension_expression=} ngOptions in one of the following forms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / object to iterate over.
* * `value`: local variable which will refer to each item in the `array` or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object` during iteration.
* * `label`: The result of this expression will be the label for `<option>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
* * `select`: The result of this expression will be bound to the model of the parent `<select>`
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
*
* @example
<doc:example>
<doc:source>
<script>
function MyCntrl($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.color = $scope.colors[2]; // red
}
</script>
<div ng-controller="MyCntrl">
<ul>
<li ng-repeat="color in colors">
Name: <input ng-model="color.name">
[<a href ng-click="colors.splice($index, 1)">X</a>]
</li>
<li>
[<a href ng-click="colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select ng-model="color" ng-options="c.name for c in colors"></select><br>
Color (null allowed):
<span class="nullable">
<select ng-model="color" ng-options="c.name for c in colors">
<option value="">-- chose color --</option>
</select>
</span><br/>
Color grouped by shade:
<select ng-model="color" ng-options="c.name group by c.shade for c in colors">
</select><br/>
Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:color} }}
<div style="border:solid 1px black; height:20px"
ng-style="{'background-color':color.name}">
</div>
</div>
</doc:source>
<doc:scenario>
it('should check ng-options', function() {
expect(binding('{selected_color:color}')).toMatch('red');
select('color').option('0');
expect(binding('{selected_color:color}')).toMatch('black');
using('.nullable').select('color').option('');
expect(binding('{selected_color:color}')).toMatch('null');
});
</doc:scenario>
</doc:example>
*/
var ngOptionsDirective = valueFn({ terminal: true });
var selectDirective = ['$compile', '$parse', function($compile, $parse) {
//0000111110000000000022220000000000000000000000333300000000000000444444444444444440000000005555555555555555500000006666666666666666600000000000000077770
var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w\d]*)|(?:\(\s*([\$\w][\$\w\d]*)\s*,\s*([\$\w][\$\w\d]*)\s*\)))\s+in\s+(.*)$/,
nullModelCtrl = {$setViewValue: noop};
return {
restrict: 'E',
require: ['select', '?ngModel'],
controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
var self = this,
optionsMap = {},
ngModelCtrl = nullModelCtrl,
nullOption,
unknownOption;
self.databound = $attrs.ngModel;
self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
ngModelCtrl = ngModelCtrl_;
nullOption = nullOption_;
unknownOption = unknownOption_;
}
self.addOption = function(value) {
optionsMap[value] = true;
if (ngModelCtrl.$viewValue == value) {
$element.val(value);
if (unknownOption.parent()) unknownOption.remove();
}
};
self.removeOption = function(value) {
if (this.hasOption(value)) {
delete optionsMap[value];
if (ngModelCtrl.$viewValue == value) {
this.renderUnknownOption(value);
}
}
};
self.renderUnknownOption = function(val) {
var unknownVal = '? ' + hashKey(val) + ' ?';
unknownOption.val(unknownVal);
$element.prepend(unknownOption);
$element.val(unknownVal);
unknownOption.prop('selected', true); // needed for IE
}
self.hasOption = function(value) {
return optionsMap.hasOwnProperty(value);
}
$scope.$on('$destroy', function() {
// disable unknown option so that we don't do work when the whole select is being destroyed
self.renderUnknownOption = noop;
});
}],
link: function(scope, element, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
if (!ctrls[1]) return;
var selectCtrl = ctrls[0],
ngModelCtrl = ctrls[1],
multiple = attr.multiple,
optionsExp = attr.ngOptions,
nullOption = false, // if false, user will not be able to select it (used by ngOptions)
emptyOption,
// we can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
optionTemplate = jqLite(document.createElement('option')),
optGroupTemplate =jqLite(document.createElement('optgroup')),
unknownOption = optionTemplate.clone();
// find "null" option
for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
if (children[i].value == '') {
emptyOption = nullOption = children.eq(i);
break;
}
}
selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
// required validator
if (multiple && (attr.required || attr.ngRequired)) {
var requiredValidator = function(value) {
ngModelCtrl.$setValidity('required', !attr.required || (value && value.length));
return value;
};
ngModelCtrl.$parsers.push(requiredValidator);
ngModelCtrl.$formatters.unshift(requiredValidator);
attr.$observe('required', function() {
requiredValidator(ngModelCtrl.$viewValue);
});
}
if (optionsExp) Options(scope, element, ngModelCtrl);
else if (multiple) Multiple(scope, element, ngModelCtrl);
else Single(scope, element, ngModelCtrl, selectCtrl);
////////////////////////////
function Single(scope, selectElement, ngModelCtrl, selectCtrl) {
ngModelCtrl.$render = function() {
var viewValue = ngModelCtrl.$viewValue;
if (selectCtrl.hasOption(viewValue)) {
if (unknownOption.parent()) unknownOption.remove();
selectElement.val(viewValue);
if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
} else {
if (isUndefined(viewValue) && emptyOption) {
selectElement.val('');
} else {
selectCtrl.renderUnknownOption(viewValue);
}
}
};
selectElement.bind('change', function() {
scope.$apply(function() {
if (unknownOption.parent()) unknownOption.remove();
ngModelCtrl.$setViewValue(selectElement.val());
});
});
}
function Multiple(scope, selectElement, ctrl) {
var lastView;
ctrl.$render = function() {
var items = new HashMap(ctrl.$viewValue);
forEach(selectElement.find('option'), function(option) {
option.selected = isDefined(items.get(option.value));
});
};
// we have to do it on each watch since ngModel watches reference, but
// we need to work of an array, so we need to see if anything was inserted/removed
scope.$watch(function selectMultipleWatch() {
if (!equals(lastView, ctrl.$viewValue)) {
lastView = copy(ctrl.$viewValue);
ctrl.$render();
}
});
selectElement.bind('change', function() {
scope.$apply(function() {
var array = [];
forEach(selectElement.find('option'), function(option) {
if (option.selected) {
array.push(option.value);
}
});
ctrl.$setViewValue(array);
});
});
}
function Options(scope, selectElement, ctrl) {
var match;
if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
throw Error(
"Expected ngOptions in form of '_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
" but got '" + optionsExp + "'.");
}
var displayFn = $parse(match[2] || match[1]),
valueName = match[4] || match[6],
keyName = match[5],
groupByFn = $parse(match[3] || ''),
valueFn = $parse(match[2] ? match[1] : valueName),
valuesFn = $parse(match[7]),
// This is an array of array of existing option groups in DOM. We try to reuse these if possible
// optionGroupsCache[0] is the options with no option group
// optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
optionGroupsCache = [[{element: selectElement, label:''}]];
if (nullOption) {
// compile the element since there might be bindings in it
$compile(nullOption)(scope);
// remove the class, which is added automatically because we recompile the element and it
// becomes the compilation root
nullOption.removeClass('ng-scope');
// we need to remove it before calling selectElement.html('') because otherwise IE will
// remove the label from the element. wtf?
nullOption.remove();
}
// clear contents, we'll add what's needed based on the model
selectElement.html('');
selectElement.bind('change', function() {
scope.$apply(function() {
var optionGroup,
collection = valuesFn(scope) || [],
locals = {},
key, value, optionElement, index, groupIndex, length, groupLength;
if (multiple) {
value = [];
for (groupIndex = 0, groupLength = optionGroupsCache.length;
groupIndex < groupLength;
groupIndex++) {
// list of options for that group. (first item has the parent)
optionGroup = optionGroupsCache[groupIndex];
for(index = 1, length = optionGroup.length; index < length; index++) {
if ((optionElement = optionGroup[index].element)[0].selected) {
key = optionElement.val();
if (keyName) locals[keyName] = key;
locals[valueName] = collection[key];
value.push(valueFn(scope, locals));
}
}
}
} else {
key = selectElement.val();
if (key == '?') {
value = undefined;
} else if (key == ''){
value = null;
} else {
locals[valueName] = collection[key];
if (keyName) locals[keyName] = key;
value = valueFn(scope, locals);
}
}
ctrl.$setViewValue(value);
});
});
ctrl.$render = render;
// TODO(vojta): can't we optimize this ?
scope.$watch(render);
function render() {
var optionGroups = {'':[]}, // Temporary location for the option groups before we render them
optionGroupNames = [''],
optionGroupName,
optionGroup,
option,
existingParent, existingOptions, existingOption,
modelValue = ctrl.$modelValue,
values = valuesFn(scope) || [],
keys = keyName ? sortedKeys(values) : values,
groupLength, length,
groupIndex, index,
locals = {},
selected,
selectedSet = false, // nothing is selected yet
lastElement,
element,
label;
if (multiple) {
selectedSet = new HashMap(modelValue);
}
// We now build up the list of options we need (we merge later)
for (index = 0; length = keys.length, index < length; index++) {
locals[valueName] = values[keyName ? locals[keyName]=keys[index]:index];
optionGroupName = groupByFn(scope, locals) || '';
if (!(optionGroup = optionGroups[optionGroupName])) {
optionGroup = optionGroups[optionGroupName] = [];
optionGroupNames.push(optionGroupName);
}
if (multiple) {
selected = selectedSet.remove(valueFn(scope, locals)) != undefined;
} else {
selected = modelValue === valueFn(scope, locals);
selectedSet = selectedSet || selected; // see if at least one item is selected
}
label = displayFn(scope, locals); // what will be seen by the user
label = label === undefined ? '' : label; // doing displayFn(scope, locals) || '' overwrites zero values
optionGroup.push({
id: keyName ? keys[index] : index, // either the index into array or key from object
label: label,
selected: selected // determine if we should be selected
});
}
if (!multiple) {
if (nullOption || modelValue === null) {
// insert null option if we have a placeholder, or the model is null
optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});
} else if (!selectedSet) {
// option could not be found, we have to insert the undefined item
optionGroups[''].unshift({id:'?', label:'', selected:true});
}
}
// Now we need to update the list of DOM nodes to match the optionGroups we computed above
for (groupIndex = 0, groupLength = optionGroupNames.length;
groupIndex < groupLength;
groupIndex++) {
// current option group name or '' if no group
optionGroupName = optionGroupNames[groupIndex];
// list of options for that group. (first item has the parent)
optionGroup = optionGroups[optionGroupName];
if (optionGroupsCache.length <= groupIndex) {
// we need to grow the optionGroups
existingParent = {
element: optGroupTemplate.clone().attr('label', optionGroupName),
label: optionGroup.label
};
existingOptions = [existingParent];
optionGroupsCache.push(existingOptions);
selectElement.append(existingParent.element);
} else {
existingOptions = optionGroupsCache[groupIndex];
existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
// update the OPTGROUP label if not the same.
if (existingParent.label != optionGroupName) {
existingParent.element.attr('label', existingParent.label = optionGroupName);
}
}
lastElement = null; // start at the beginning
for(index = 0, length = optionGroup.length; index < length; index++) {
option = optionGroup[index];
if ((existingOption = existingOptions[index+1])) {
// reuse elements
lastElement = existingOption.element;
if (existingOption.label !== option.label) {
lastElement.text(existingOption.label = option.label);
}
if (existingOption.id !== option.id) {
lastElement.val(existingOption.id = option.id);
}
// lastElement.prop('selected') provided by jQuery has side-effects
if (lastElement[0].selected !== option.selected) {
lastElement.prop('selected', (existingOption.selected = option.selected));
}
} else {
// grow elements
// if it's a null option
if (option.id === '' && nullOption) {
// put back the pre-compiled element
element = nullOption;
} else {
// jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
// in this version of jQuery on some browser the .text() returns a string
// rather then the element.
(element = optionTemplate.clone())
.val(option.id)
.attr('selected', option.selected)
.text(option.label);
}
existingOptions.push(existingOption = {
element: element,
label: option.label,
id: option.id,
selected: option.selected
});
if (lastElement) {
lastElement.after(element);
} else {
existingParent.element.append(element);
}
lastElement = element;
}
}
// remove any excessive OPTIONs in a group
index++; // increment since the existingOptions[0] is parent element not OPTION
while(existingOptions.length > index) {
existingOptions.pop().element.remove();
}
}
// remove any excessive OPTGROUPs from select
while(optionGroupsCache.length > groupIndex) {
optionGroupsCache.pop()[0].element.remove();
}
}
}
}
}
}];
var optionDirective = ['$interpolate', function($interpolate) {
var nullSelectCtrl = {
addOption: noop,
removeOption: noop
};
return {
restrict: 'E',
priority: 100,
compile: function(element, attr) {
if (isUndefined(attr.value)) {
var interpolateFn = $interpolate(element.text(), true);
if (!interpolateFn) {
attr.$set('value', element.text());
}
}
return function (scope, element, attr) {
var selectCtrlName = '$selectController',
parent = element.parent(),
selectCtrl = parent.data(selectCtrlName) ||
parent.parent().data(selectCtrlName); // in case we are in optgroup
if (selectCtrl && selectCtrl.databound) {
// For some reason Opera defaults to true and if not overridden this messes up the repeater.
// We don't want the view to drive the initialization of the model anyway.
element.prop('selected', false);
} else {
selectCtrl = nullSelectCtrl;
}
if (interpolateFn) {
scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
attr.$set('value', newVal);
if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
selectCtrl.addOption(newVal);
});
} else {
selectCtrl.addOption(attr.value);
}
element.bind('$destroy', function() {
selectCtrl.removeOption(attr.value);
});
};
}
}
}];
var styleDirective = valueFn({
restrict: 'E',
terminal: true
});
/**
* Setup file for the Scenario.
* Must be first in the compilation/bootstrap list.
*/
// Public namespace
angular.scenario = angular.scenario || {};
/**
* Defines a new output format.
*
* @param {string} name the name of the new output format
* @param {function()} fn function(context, runner) that generates the output
*/
angular.scenario.output = angular.scenario.output || function(name, fn) {
angular.scenario.output[name] = fn;
};
/**
* Defines a new DSL statement. If your factory function returns a Future
* it's returned, otherwise the result is assumed to be a map of functions
* for chaining. Chained functions are subject to the same rules.
*
* Note: All functions on the chain are bound to the chain scope so values
* set on "this" in your statement function are available in the chained
* functions.
*
* @param {string} name The name of the statement
* @param {function()} fn Factory function(), return a function for
* the statement.
*/
angular.scenario.dsl = angular.scenario.dsl || function(name, fn) {
angular.scenario.dsl[name] = function() {
function executeStatement(statement, args) {
var result = statement.apply(this, args);
if (angular.isFunction(result) || result instanceof angular.scenario.Future)
return result;
var self = this;
var chain = angular.extend({}, result);
angular.forEach(chain, function(value, name) {
if (angular.isFunction(value)) {
chain[name] = function() {
return executeStatement.call(self, value, arguments);
};
} else {
chain[name] = value;
}
});
return chain;
}
var statement = fn.apply(this, arguments);
return function() {
return executeStatement.call(this, statement, arguments);
};
};
};
/**
* Defines a new matcher for use with the expects() statement. The value
* this.actual (like in Jasmine) is available in your matcher to compare
* against. Your function should return a boolean. The future is automatically
* created for you.
*
* @param {string} name The name of the matcher
* @param {function()} fn The matching function(expected).
*/
angular.scenario.matcher = angular.scenario.matcher || function(name, fn) {
angular.scenario.matcher[name] = function(expected) {
var prefix = 'expect ' + this.future.name + ' ';
if (this.inverse) {
prefix += 'not ';
}
var self = this;
this.addFuture(prefix + name + ' ' + angular.toJson(expected),
function(done) {
var error;
self.actual = self.future.value;
if ((self.inverse && fn.call(self, expected)) ||
(!self.inverse && !fn.call(self, expected))) {
error = 'expected ' + angular.toJson(expected) +
' but was ' + angular.toJson(self.actual);
}
done(error);
});
};
};
/**
* Initialize the scenario runner and run !
*
* Access global window and document object
* Access $runner through closure
*
* @param {Object=} config Config options
*/
angular.scenario.setUpAndRun = function(config) {
var href = window.location.href;
var body = _jQuery(document.body);
var output = [];
var objModel = new angular.scenario.ObjectModel($runner);
if (config && config.scenario_output) {
output = config.scenario_output.split(',');
}
angular.forEach(angular.scenario.output, function(fn, name) {
if (!output.length || indexOf(output,name) != -1) {
var context = body.append('<div></div>').find('div:last');
context.attr('id', name);
fn.call({}, context, $runner, objModel);
}
});
if (!/^http/.test(href) && !/^https/.test(href)) {
body.append('<p id="system-error"></p>');
body.find('#system-error').text(
'Scenario runner must be run using http or https. The protocol ' +
href.split(':')[0] + ':// is not supported.'
);
return;
}
var appFrame = body.append('<div id="application"></div>').find('#application');
var application = new angular.scenario.Application(appFrame);
$runner.on('RunnerEnd', function() {
appFrame.css('display', 'none');
appFrame.find('iframe').attr('src', 'about:blank');
});
$runner.on('RunnerError', function(error) {
if (window.console) {
console.log(formatException(error));
} else {
// Do something for IE
alert(error);
}
});
$runner.run(application);
};
/**
* Iterates through list with iterator function that must call the
* continueFunction to continute iterating.
*
* @param {Array} list list to iterate over
* @param {function()} iterator Callback function(value, continueFunction)
* @param {function()} done Callback function(error, result) called when
* iteration finishes or an error occurs.
*/
function asyncForEach(list, iterator, done) {
var i = 0;
function loop(error, index) {
if (index && index > i) {
i = index;
}
if (error || i >= list.length) {
done(error);
} else {
try {
iterator(list[i++], loop);
} catch (e) {
done(e);
}
}
}
loop();
}
/**
* Formats an exception into a string with the stack trace, but limits
* to a specific line length.
*
* @param {Object} error The exception to format, can be anything throwable
* @param {Number=} [maxStackLines=5] max lines of the stack trace to include
* default is 5.
*/
function formatException(error, maxStackLines) {
maxStackLines = maxStackLines || 5;
var message = error.toString();
if (error.stack) {
var stack = error.stack.split('\n');
if (stack[0].indexOf(message) === -1) {
maxStackLines++;
stack.unshift(error.message);
}
message = stack.slice(0, maxStackLines).join('\n');
}
return message;
}
/**
* Returns a function that gets the file name and line number from a
* location in the stack if available based on the call site.
*
* Note: this returns another function because accessing .stack is very
* expensive in Chrome.
*
* @param {Number} offset Number of stack lines to skip
*/
function callerFile(offset) {
var error = new Error();
return function() {
var line = (error.stack || '').split('\n')[offset];
// Clean up the stack trace line
if (line) {
if (line.indexOf('@') !== -1) {
// Firefox
line = line.substring(line.indexOf('@')+1);
} else {
// Chrome
line = line.substring(line.indexOf('(')+1).replace(')', '');
}
}
return line || '';
};
}
/**
* Triggers a browser event. Attempts to choose the right event if one is
* not specified.
*
* @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement
* @param {string} type Optional event type.
* @param {Array.<string>=} keys Optional list of pressed keys
* (valid values: 'alt', 'meta', 'shift', 'ctrl')
*/
function browserTrigger(element, type, keys) {
if (element && !element.nodeName) element = element[0];
if (!element) return;
if (!type) {
type = {
'text': 'change',
'textarea': 'change',
'hidden': 'change',
'password': 'change',
'button': 'click',
'submit': 'click',
'reset': 'click',
'image': 'click',
'checkbox': 'click',
'radio': 'click',
'select-one': 'change',
'select-multiple': 'change'
}[lowercase(element.type)] || 'click';
}
if (lowercase(nodeName_(element)) == 'option') {
element.parentNode.value = element.value;
element = element.parentNode;
type = 'change';
}
keys = keys || [];
function pressed(key) {
return indexOf(keys, key) !== -1;
}
if (msie < 9) {
switch(element.type) {
case 'radio':
case 'checkbox':
element.checked = !element.checked;
break;
}
// WTF!!! Error: Unspecified error.
// Don't know why, but some elements when detached seem to be in inconsistent state and
// calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error)
// forcing the browser to compute the element position (by reading its CSS)
// puts the element in consistent state.
element.style.posLeft;
// TODO(vojta): create event objects with pressed keys to get it working on IE<9
var ret = element.fireEvent('on' + type);
if (lowercase(element.type) == 'submit') {
while(element) {
if (lowercase(element.nodeName) == 'form') {
element.fireEvent('onsubmit');
break;
}
element = element.parentNode;
}
}
return ret;
} else {
var evnt = document.createEvent('MouseEvents'),
originalPreventDefault = evnt.preventDefault,
iframe = _jQuery('#application iframe')[0],
appWindow = iframe ? iframe.contentWindow : window,
fakeProcessDefault = true,
finalProcessDefault,
angular = appWindow.angular || {};
// igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208
angular['ff-684208-preventDefault'] = false;
evnt.preventDefault = function() {
fakeProcessDefault = false;
return originalPreventDefault.apply(evnt, arguments);
};
evnt.initMouseEvent(type, true, true, window, 0, 0, 0, 0, 0, pressed('ctrl'), pressed('alt'),
pressed('shift'), pressed('meta'), 0, element);
element.dispatchEvent(evnt);
finalProcessDefault = !(angular['ff-684208-preventDefault'] || !fakeProcessDefault);
delete angular['ff-684208-preventDefault'];
return finalProcessDefault;
}
}
/**
* Don't use the jQuery trigger method since it works incorrectly.
*
* jQuery notifies listeners and then changes the state of a checkbox and
* does not create a real browser event. A real click changes the state of
* the checkbox and then notifies listeners.
*
* To work around this we instead use our own handler that fires a real event.
*/
(function(fn){
var parentTrigger = fn.trigger;
fn.trigger = function(type) {
if (/(click|change|keydown|blur|input)/.test(type)) {
var processDefaults = [];
this.each(function(index, node) {
processDefaults.push(browserTrigger(node, type));
});
// this is not compatible with jQuery - we return an array of returned values,
// so that scenario runner know whether JS code has preventDefault() of the event or not...
return processDefaults;
}
return parentTrigger.apply(this, arguments);
};
})(_jQuery.fn);
/**
* Finds all bindings with the substring match of name and returns an
* array of their values.
*
* @param {string} bindExp The name to match
* @return {Array.<string>} String of binding values
*/
_jQuery.fn.bindings = function(windowJquery, bindExp) {
var result = [], match,
bindSelector = '.ng-binding:visible';
if (angular.isString(bindExp)) {
bindExp = bindExp.replace(/\s/g, '');
match = function (actualExp) {
if (actualExp) {
actualExp = actualExp.replace(/\s/g, '');
if (actualExp == bindExp) return true;
if (actualExp.indexOf(bindExp) == 0) {
return actualExp.charAt(bindExp.length) == '|';
}
}
}
} else if (bindExp) {
match = function(actualExp) {
return actualExp && bindExp.exec(actualExp);
}
} else {
match = function(actualExp) {
return !!actualExp;
};
}
var selection = this.find(bindSelector);
if (this.is(bindSelector)) {
selection = selection.add(this);
}
function push(value) {
if (value == undefined) {
value = '';
} else if (typeof value != 'string') {
value = angular.toJson(value);
}
result.push('' + value);
}
selection.each(function() {
var element = windowJquery(this),
binding;
if (binding = element.data('$binding')) {
if (typeof binding == 'string') {
if (match(binding)) {
push(element.scope().$eval(binding));
}
} else {
if (!angular.isArray(binding)) {
binding = [binding];
}
for(var fns, j=0, jj=binding.length; j<jj; j++) {
fns = binding[j];
if (fns.parts) {
fns = fns.parts;
} else {
fns = [fns];
}
for (var scope, fn, i = 0, ii = fns.length; i < ii; i++) {
if(match((fn = fns[i]).exp)) {
push(fn(scope = scope || element.scope()));
}
}
}
}
}
});
return result;
};
/**
* Represents the application currently being tested and abstracts usage
* of iframes or separate windows.
*
* @param {Object} context jQuery wrapper around HTML context.
*/
angular.scenario.Application = function(context) {
this.context = context;
context.append(
'<h2>Current URL: <a href="about:blank">None</a></h2>' +
'<div id="test-frames"></div>'
);
};
/**
* Gets the jQuery collection of frames. Don't use this directly because
* frames may go stale.
*
* @private
* @return {Object} jQuery collection
*/
angular.scenario.Application.prototype.getFrame_ = function() {
return this.context.find('#test-frames iframe:last');
};
/**
* Gets the window of the test runner frame. Always favor executeAction()
* instead of this method since it prevents you from getting a stale window.
*
* @private
* @return {Object} the window of the frame
*/
angular.scenario.Application.prototype.getWindow_ = function() {
var contentWindow = this.getFrame_().prop('contentWindow');
if (!contentWindow)
throw 'Frame window is not accessible.';
return contentWindow;
};
/**
* Changes the location of the frame.
*
* @param {string} url The URL. If it begins with a # then only the
* hash of the page is changed.
* @param {function()} loadFn function($window, $document) Called when frame loads.
* @param {function()} errorFn function(error) Called if any error when loading.
*/
angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) {
var self = this;
var frame = this.getFrame_();
//TODO(esprehn): Refactor to use rethrow()
errorFn = errorFn || function(e) { throw e; };
if (url === 'about:blank') {
errorFn('Sandbox Error: Navigating to about:blank is not allowed.');
} else if (url.charAt(0) === '#') {
url = frame.attr('src').split('#')[0] + url;
frame.attr('src', url);
this.executeAction(loadFn);
} else {
frame.remove();
this.context.find('#test-frames').append('<iframe>');
frame = this.getFrame_();
frame.load(function() {
frame.unbind();
try {
self.executeAction(loadFn);
} catch (e) {
errorFn(e);
}
}).attr('src', url);
}
this.context.find('> h2 a').attr('href', url).text(url);
};
/**
* Executes a function in the context of the tested application. Will wait
* for all pending angular xhr requests before executing.
*
* @param {function()} action The callback to execute. function($window, $document)
* $document is a jQuery wrapped document.
*/
angular.scenario.Application.prototype.executeAction = function(action) {
var self = this;
var $window = this.getWindow_();
if (!$window.document) {
throw 'Sandbox Error: Application document not accessible.';
}
if (!$window.angular) {
return action.call(this, $window, _jQuery($window.document));
}
angularInit($window.document, function(element) {
var $injector = $window.angular.element(element).injector();
var $element = _jQuery(element);
$element.injector = function() {
return $injector;
};
$injector.invoke(function($browser){
$browser.notifyWhenNoOutstandingRequests(function() {
action.call(self, $window, $element);
});
});
});
};
/**
* The representation of define blocks. Don't used directly, instead use
* define() in your tests.
*
* @param {string} descName Name of the block
* @param {Object} parent describe or undefined if the root.
*/
angular.scenario.Describe = function(descName, parent) {
this.only = parent && parent.only;
this.beforeEachFns = [];
this.afterEachFns = [];
this.its = [];
this.children = [];
this.name = descName;
this.parent = parent;
this.id = angular.scenario.Describe.id++;
/**
* Calls all before functions.
*/
var beforeEachFns = this.beforeEachFns;
this.setupBefore = function() {
if (parent) parent.setupBefore.call(this);
angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this);
};
/**
* Calls all after functions.
*/
var afterEachFns = this.afterEachFns;
this.setupAfter = function() {
angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this);
if (parent) parent.setupAfter.call(this);
};
};
// Shared Unique ID generator for every describe block
angular.scenario.Describe.id = 0;
// Shared Unique ID generator for every it (spec)
angular.scenario.Describe.specId = 0;
/**
* Defines a block to execute before each it or nested describe.
*
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.beforeEach = function(body) {
this.beforeEachFns.push(body);
};
/**
* Defines a block to execute after each it or nested describe.
*
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.afterEach = function(body) {
this.afterEachFns.push(body);
};
/**
* Creates a new describe block that's a child of this one.
*
* @param {string} name Name of the block. Appended to the parent block's name.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.describe = function(name, body) {
var child = new angular.scenario.Describe(name, this);
this.children.push(child);
body.call(child);
};
/**
* Same as describe() but makes ddescribe blocks the only to run.
*
* @param {string} name Name of the test.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.ddescribe = function(name, body) {
var child = new angular.scenario.Describe(name, this);
child.only = true;
this.children.push(child);
body.call(child);
};
/**
* Use to disable a describe block.
*/
angular.scenario.Describe.prototype.xdescribe = angular.noop;
/**
* Defines a test.
*
* @param {string} name Name of the test.
* @param {function()} vody Body of the block.
*/
angular.scenario.Describe.prototype.it = function(name, body) {
this.its.push({
id: angular.scenario.Describe.specId++,
definition: this,
only: this.only,
name: name,
before: this.setupBefore,
body: body,
after: this.setupAfter
});
};
/**
* Same as it() but makes iit tests the only test to run.
*
* @param {string} name Name of the test.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.iit = function(name, body) {
this.it.apply(this, arguments);
this.its[this.its.length-1].only = true;
};
/**
* Use to disable a test block.
*/
angular.scenario.Describe.prototype.xit = angular.noop;
/**
* Gets an array of functions representing all the tests (recursively).
* that can be executed with SpecRunner's.
*
* @return {Array<Object>} Array of it blocks {
* definition : Object // parent Describe
* only: boolean
* name: string
* before: Function
* body: Function
* after: Function
* }
*/
angular.scenario.Describe.prototype.getSpecs = function() {
var specs = arguments[0] || [];
angular.forEach(this.children, function(child) {
child.getSpecs(specs);
});
angular.forEach(this.its, function(it) {
specs.push(it);
});
var only = [];
angular.forEach(specs, function(it) {
if (it.only) {
only.push(it);
}
});
return (only.length && only) || specs;
};
/**
* A future action in a spec.
*
* @param {string} name of the future action
* @param {function()} future callback(error, result)
* @param {function()} Optional. function that returns the file/line number.
*/
angular.scenario.Future = function(name, behavior, line) {
this.name = name;
this.behavior = behavior;
this.fulfilled = false;
this.value = undefined;
this.parser = angular.identity;
this.line = line || function() { return ''; };
};
/**
* Executes the behavior of the closure.
*
* @param {function()} doneFn Callback function(error, result)
*/
angular.scenario.Future.prototype.execute = function(doneFn) {
var self = this;
this.behavior(function(error, result) {
self.fulfilled = true;
if (result) {
try {
result = self.parser(result);
} catch(e) {
error = e;
}
}
self.value = error || result;
doneFn(error, result);
});
};
/**
* Configures the future to convert it's final with a function fn(value)
*
* @param {function()} fn function(value) that returns the parsed value
*/
angular.scenario.Future.prototype.parsedWith = function(fn) {
this.parser = fn;
return this;
};
/**
* Configures the future to parse it's final value from JSON
* into objects.
*/
angular.scenario.Future.prototype.fromJson = function() {
return this.parsedWith(angular.fromJson);
};
/**
* Configures the future to convert it's final value from objects
* into JSON.
*/
angular.scenario.Future.prototype.toJson = function() {
return this.parsedWith(angular.toJson);
};
/**
* Maintains an object tree from the runner events.
*
* @param {Object} runner The scenario Runner instance to connect to.
*
* TODO(esprehn): Every output type creates one of these, but we probably
* want one global shared instance. Need to handle events better too
* so the HTML output doesn't need to do spec model.getSpec(spec.id)
* silliness.
*
* TODO(vojta) refactor on, emit methods (from all objects) - use inheritance
*/
angular.scenario.ObjectModel = function(runner) {
var self = this;
this.specMap = {};
this.listeners = [];
this.value = {
name: '',
children: {}
};
runner.on('SpecBegin', function(spec) {
var block = self.value,
definitions = [];
angular.forEach(self.getDefinitionPath(spec), function(def) {
if (!block.children[def.name]) {
block.children[def.name] = {
id: def.id,
name: def.name,
children: {},
specs: {}
};
}
block = block.children[def.name];
definitions.push(def.name);
});
var it = self.specMap[spec.id] =
block.specs[spec.name] =
new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions);
// forward the event
self.emit('SpecBegin', it);
});
runner.on('SpecError', function(spec, error) {
var it = self.getSpec(spec.id);
it.status = 'error';
it.error = error;
// forward the event
self.emit('SpecError', it, error);
});
runner.on('SpecEnd', function(spec) {
var it = self.getSpec(spec.id);
complete(it);
// forward the event
self.emit('SpecEnd', it);
});
runner.on('StepBegin', function(spec, step) {
var it = self.getSpec(spec.id);
var step = new angular.scenario.ObjectModel.Step(step.name);
it.steps.push(step);
// forward the event
self.emit('StepBegin', it, step);
});
runner.on('StepEnd', function(spec) {
var it = self.getSpec(spec.id);
var step = it.getLastStep();
if (step.name !== step.name)
throw 'Events fired in the wrong order. Step names don\'t match.';
complete(step);
// forward the event
self.emit('StepEnd', it, step);
});
runner.on('StepFailure', function(spec, step, error) {
var it = self.getSpec(spec.id),
modelStep = it.getLastStep();
modelStep.setErrorStatus('failure', error, step.line());
it.setStatusFromStep(modelStep);
// forward the event
self.emit('StepFailure', it, modelStep, error);
});
runner.on('StepError', function(spec, step, error) {
var it = self.getSpec(spec.id),
modelStep = it.getLastStep();
modelStep.setErrorStatus('error', error, step.line());
it.setStatusFromStep(modelStep);
// forward the event
self.emit('StepError', it, modelStep, error);
});
runner.on('RunnerBegin', function() {
self.emit('RunnerBegin');
});
runner.on('RunnerEnd', function() {
self.emit('RunnerEnd');
});
function complete(item) {
item.endTime = new Date().getTime();
item.duration = item.endTime - item.startTime;
item.status = item.status || 'success';
}
};
/**
* Adds a listener for an event.
*
* @param {string} eventName Name of the event to add a handler for
* @param {function()} listener Function that will be called when event is fired
*/
angular.scenario.ObjectModel.prototype.on = function(eventName, listener) {
eventName = eventName.toLowerCase();
this.listeners[eventName] = this.listeners[eventName] || [];
this.listeners[eventName].push(listener);
};
/**
* Emits an event which notifies listeners and passes extra
* arguments.
*
* @param {string} eventName Name of the event to fire.
*/
angular.scenario.ObjectModel.prototype.emit = function(eventName) {
var self = this,
args = Array.prototype.slice.call(arguments, 1),
eventName = eventName.toLowerCase();
if (this.listeners[eventName]) {
angular.forEach(this.listeners[eventName], function(listener) {
listener.apply(self, args);
});
}
};
/**
* Computes the path of definition describe blocks that wrap around
* this spec.
*
* @param spec Spec to compute the path for.
* @return {Array<Describe>} The describe block path
*/
angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) {
var path = [];
var currentDefinition = spec.definition;
while (currentDefinition && currentDefinition.name) {
path.unshift(currentDefinition);
currentDefinition = currentDefinition.parent;
}
return path;
};
/**
* Gets a spec by id.
*
* @param {string} The id of the spec to get the object for.
* @return {Object} the Spec instance
*/
angular.scenario.ObjectModel.prototype.getSpec = function(id) {
return this.specMap[id];
};
/**
* A single it block.
*
* @param {string} id Id of the spec
* @param {string} name Name of the spec
* @param {Array<string>=} definitionNames List of all describe block names that wrap this spec
*/
angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) {
this.id = id;
this.name = name;
this.startTime = new Date().getTime();
this.steps = [];
this.fullDefinitionName = (definitionNames || []).join(' ');
};
/**
* Adds a new step to the Spec.
*
* @param {string} step Name of the step (really name of the future)
* @return {Object} the added step
*/
angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) {
var step = new angular.scenario.ObjectModel.Step(name);
this.steps.push(step);
return step;
};
/**
* Gets the most recent step.
*
* @return {Object} the step
*/
angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() {
return this.steps[this.steps.length-1];
};
/**
* Set status of the Spec from given Step
*
* @param {angular.scenario.ObjectModel.Step} step
*/
angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) {
if (!this.status || step.status == 'error') {
this.status = step.status;
this.error = step.error;
this.line = step.line;
}
};
/**
* A single step inside a Spec.
*
* @param {string} step Name of the step
*/
angular.scenario.ObjectModel.Step = function(name) {
this.name = name;
this.startTime = new Date().getTime();
};
/**
* Helper method for setting all error status related properties
*
* @param {string} status
* @param {string} error
* @param {string} line
*/
angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) {
this.status = status;
this.error = error;
this.line = line;
};
/**
* Runner for scenarios
*
* Has to be initialized before any test is loaded,
* because it publishes the API into window (global space).
*/
angular.scenario.Runner = function($window) {
this.listeners = [];
this.$window = $window;
this.rootDescribe = new angular.scenario.Describe();
this.currentDescribe = this.rootDescribe;
this.api = {
it: this.it,
iit: this.iit,
xit: angular.noop,
describe: this.describe,
ddescribe: this.ddescribe,
xdescribe: angular.noop,
beforeEach: this.beforeEach,
afterEach: this.afterEach
};
angular.forEach(this.api, angular.bind(this, function(fn, key) {
this.$window[key] = angular.bind(this, fn);
}));
};
/**
* Emits an event which notifies listeners and passes extra
* arguments.
*
* @param {string} eventName Name of the event to fire.
*/
angular.scenario.Runner.prototype.emit = function(eventName) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
eventName = eventName.toLowerCase();
if (!this.listeners[eventName])
return;
angular.forEach(this.listeners[eventName], function(listener) {
listener.apply(self, args);
});
};
/**
* Adds a listener for an event.
*
* @param {string} eventName The name of the event to add a handler for
* @param {string} listener The fn(...) that takes the extra arguments from emit()
*/
angular.scenario.Runner.prototype.on = function(eventName, listener) {
eventName = eventName.toLowerCase();
this.listeners[eventName] = this.listeners[eventName] || [];
this.listeners[eventName].push(listener);
};
/**
* Defines a describe block of a spec.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.describe = function(name, body) {
var self = this;
this.currentDescribe.describe(name, function() {
var parentDescribe = self.currentDescribe;
self.currentDescribe = this;
try {
body.call(this);
} finally {
self.currentDescribe = parentDescribe;
}
});
};
/**
* Same as describe, but makes ddescribe the only blocks to run.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.ddescribe = function(name, body) {
var self = this;
this.currentDescribe.ddescribe(name, function() {
var parentDescribe = self.currentDescribe;
self.currentDescribe = this;
try {
body.call(this);
} finally {
self.currentDescribe = parentDescribe;
}
});
};
/**
* Defines a test in a describe block of a spec.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.it = function(name, body) {
this.currentDescribe.it(name, body);
};
/**
* Same as it, but makes iit tests the only tests to run.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.iit = function(name, body) {
this.currentDescribe.iit(name, body);
};
/**
* Defines a function to be called before each it block in the describe
* (and before all nested describes).
*
* @see Describe.js
*
* @param {function()} Callback to execute
*/
angular.scenario.Runner.prototype.beforeEach = function(body) {
this.currentDescribe.beforeEach(body);
};
/**
* Defines a function to be called after each it block in the describe
* (and before all nested describes).
*
* @see Describe.js
*
* @param {function()} Callback to execute
*/
angular.scenario.Runner.prototype.afterEach = function(body) {
this.currentDescribe.afterEach(body);
};
/**
* Creates a new spec runner.
*
* @private
* @param {Object} scope parent scope
*/
angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) {
var child = scope.$new();
var Cls = angular.scenario.SpecRunner;
// Export all the methods to child scope manually as now we don't mess controllers with scopes
// TODO(vojta): refactor scenario runner so that these objects are not tightly coupled as current
for (var name in Cls.prototype)
child[name] = angular.bind(child, Cls.prototype[name]);
Cls.call(child);
return child;
};
/**
* Runs all the loaded tests with the specified runner class on the
* provided application.
*
* @param {angular.scenario.Application} application App to remote control.
*/
angular.scenario.Runner.prototype.run = function(application) {
var self = this;
var $root = angular.injector(['ng']).get('$rootScope');
angular.extend($root, this);
angular.forEach(angular.scenario.Runner.prototype, function(fn, name) {
$root[name] = angular.bind(self, fn);
});
$root.application = application;
$root.emit('RunnerBegin');
asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) {
var dslCache = {};
var runner = self.createSpecRunner_($root);
angular.forEach(angular.scenario.dsl, function(fn, key) {
dslCache[key] = fn.call($root);
});
angular.forEach(angular.scenario.dsl, function(fn, key) {
self.$window[key] = function() {
var line = callerFile(3);
var scope = runner.$new();
// Make the dsl accessible on the current chain
scope.dsl = {};
angular.forEach(dslCache, function(fn, key) {
scope.dsl[key] = function() {
return dslCache[key].apply(scope, arguments);
};
});
// Make these methods work on the current chain
scope.addFuture = function() {
Array.prototype.push.call(arguments, line);
return angular.scenario.SpecRunner.
prototype.addFuture.apply(scope, arguments);
};
scope.addFutureAction = function() {
Array.prototype.push.call(arguments, line);
return angular.scenario.SpecRunner.
prototype.addFutureAction.apply(scope, arguments);
};
return scope.dsl[key].apply(scope, arguments);
};
});
runner.run(spec, function() {
runner.$destroy();
specDone.apply(this, arguments);
});
},
function(error) {
if (error) {
self.emit('RunnerError', error);
}
self.emit('RunnerEnd');
});
};
/**
* This class is the "this" of the it/beforeEach/afterEach method.
* Responsibilities:
* - "this" for it/beforeEach/afterEach
* - keep state for single it/beforeEach/afterEach execution
* - keep track of all of the futures to execute
* - run single spec (execute each future)
*/
angular.scenario.SpecRunner = function() {
this.futures = [];
this.afterIndex = 0;
};
/**
* Executes a spec which is an it block with associated before/after functions
* based on the describe nesting.
*
* @param {Object} spec A spec object
* @param {function()} specDone function that is called when the spec finshes. Function(error, index)
*/
angular.scenario.SpecRunner.prototype.run = function(spec, specDone) {
var self = this;
this.spec = spec;
this.emit('SpecBegin', spec);
try {
spec.before.call(this);
spec.body.call(this);
this.afterIndex = this.futures.length;
spec.after.call(this);
} catch (e) {
this.emit('SpecError', spec, e);
this.emit('SpecEnd', spec);
specDone();
return;
}
var handleError = function(error, done) {
if (self.error) {
return done();
}
self.error = true;
done(null, self.afterIndex);
};
asyncForEach(
this.futures,
function(future, futureDone) {
self.step = future;
self.emit('StepBegin', spec, future);
try {
future.execute(function(error) {
if (error) {
self.emit('StepFailure', spec, future, error);
self.emit('StepEnd', spec, future);
return handleError(error, futureDone);
}
self.emit('StepEnd', spec, future);
self.$window.setTimeout(function() { futureDone(); }, 0);
});
} catch (e) {
self.emit('StepError', spec, future, e);
self.emit('StepEnd', spec, future);
handleError(e, futureDone);
}
},
function(e) {
if (e) {
self.emit('SpecError', spec, e);
}
self.emit('SpecEnd', spec);
// Call done in a timeout so exceptions don't recursively
// call this function
self.$window.setTimeout(function() { specDone(); }, 0);
}
);
};
/**
* Adds a new future action.
*
* Note: Do not pass line manually. It happens automatically.
*
* @param {string} name Name of the future
* @param {function()} behavior Behavior of the future
* @param {function()} line fn() that returns file/line number
*/
angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) {
var future = new angular.scenario.Future(name, angular.bind(this, behavior), line);
this.futures.push(future);
return future;
};
/**
* Adds a new future action to be executed on the application window.
*
* Note: Do not pass line manually. It happens automatically.
*
* @param {string} name Name of the future
* @param {function()} behavior Behavior of the future
* @param {function()} line fn() that returns file/line number
*/
angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) {
var self = this;
var NG = /\[ng\\\:/;
return this.addFuture(name, function(done) {
this.application.executeAction(function($window, $document) {
//TODO(esprehn): Refactor this so it doesn't need to be in here.
$document.elements = function(selector) {
var args = Array.prototype.slice.call(arguments, 1);
selector = (self.selector || '') + ' ' + (selector || '');
selector = _jQuery.trim(selector) || '*';
angular.forEach(args, function(value, index) {
selector = selector.replace('$' + (index + 1), value);
});
var result = $document.find(selector);
if (selector.match(NG)) {
angular.forEach(['[ng-','[data-ng-','[x-ng-'], function(value, index){
result = result.add(selector.replace(NG, value), $document);
});
}
if (!result.length) {
throw {
type: 'selector',
message: 'Selector ' + selector + ' did not match any elements.'
};
}
return result;
};
try {
behavior.call(self, $window, $document, done);
} catch(e) {
if (e.type && e.type === 'selector') {
done(e.message);
} else {
throw e;
}
}
});
}, line);
};
/**
* Shared DSL statements that are useful to all scenarios.
*/
/**
* Usage:
* pause() pauses until you call resume() in the console
*/
angular.scenario.dsl('pause', function() {
return function() {
return this.addFuture('pausing for you to resume', function(done) {
this.emit('InteractivePause', this.spec, this.step);
this.$window.resume = function() { done(); };
});
};
});
/**
* Usage:
* sleep(seconds) pauses the test for specified number of seconds
*/
angular.scenario.dsl('sleep', function() {
return function(time) {
return this.addFuture('sleep for ' + time + ' seconds', function(done) {
this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000);
});
};
});
/**
* Usage:
* browser().navigateTo(url) Loads the url into the frame
* browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to
* browser().reload() refresh the page (reload the same URL)
* browser().window.href() window.location.href
* browser().window.path() window.location.pathname
* browser().window.search() window.location.search
* browser().window.hash() window.location.hash without # prefix
* browser().location().url() see ng.$location#url
* browser().location().path() see ng.$location#path
* browser().location().search() see ng.$location#search
* browser().location().hash() see ng.$location#hash
*/
angular.scenario.dsl('browser', function() {
var chain = {};
chain.navigateTo = function(url, delegate) {
var application = this.application;
return this.addFuture("browser navigate to '" + url + "'", function(done) {
if (delegate) {
url = delegate.call(this, url);
}
application.navigateTo(url, function() {
done(null, url);
}, done);
});
};
chain.reload = function() {
var application = this.application;
return this.addFutureAction('browser reload', function($window, $document, done) {
var href = $window.location.href;
application.navigateTo(href, function() {
done(null, href);
}, done);
});
};
chain.window = function() {
var api = {};
api.href = function() {
return this.addFutureAction('window.location.href', function($window, $document, done) {
done(null, $window.location.href);
});
};
api.path = function() {
return this.addFutureAction('window.location.path', function($window, $document, done) {
done(null, $window.location.pathname);
});
};
api.search = function() {
return this.addFutureAction('window.location.search', function($window, $document, done) {
done(null, $window.location.search);
});
};
api.hash = function() {
return this.addFutureAction('window.location.hash', function($window, $document, done) {
done(null, $window.location.hash.replace('#', ''));
});
};
return api;
};
chain.location = function() {
var api = {};
api.url = function() {
return this.addFutureAction('$location.url()', function($window, $document, done) {
done(null, $document.injector().get('$location').url());
});
};
api.path = function() {
return this.addFutureAction('$location.path()', function($window, $document, done) {
done(null, $document.injector().get('$location').path());
});
};
api.search = function() {
return this.addFutureAction('$location.search()', function($window, $document, done) {
done(null, $document.injector().get('$location').search());
});
};
api.hash = function() {
return this.addFutureAction('$location.hash()', function($window, $document, done) {
done(null, $document.injector().get('$location').hash());
});
};
return api;
};
return function() {
return chain;
};
});
/**
* Usage:
* expect(future).{matcher} where matcher is one of the matchers defined
* with angular.scenario.matcher
*
* ex. expect(binding("name")).toEqual("Elliott")
*/
angular.scenario.dsl('expect', function() {
var chain = angular.extend({}, angular.scenario.matcher);
chain.not = function() {
this.inverse = true;
return chain;
};
return function(future) {
this.future = future;
return chain;
};
});
/**
* Usage:
* using(selector, label) scopes the next DSL element selection
*
* ex.
* using('#foo', "'Foo' text field").input('bar')
*/
angular.scenario.dsl('using', function() {
return function(selector, label) {
this.selector = _jQuery.trim((this.selector||'') + ' ' + selector);
if (angular.isString(label) && label.length) {
this.label = label + ' ( ' + this.selector + ' )';
} else {
this.label = this.selector;
}
return this.dsl;
};
});
/**
* Usage:
* binding(name) returns the value of the first matching binding
*/
angular.scenario.dsl('binding', function() {
return function(name) {
return this.addFutureAction("select binding '" + name + "'", function($window, $document, done) {
var values = $document.elements().bindings($window.angular.element, name);
if (!values.length) {
return done("Binding selector '" + name + "' did not match.");
}
done(null, values[0]);
});
};
});
/**
* Usage:
* input(name).enter(value) enters value in input with specified name
* input(name).check() checks checkbox
* input(name).select(value) selects the radio button with specified name/value
* input(name).val() returns the value of the input.
*/
angular.scenario.dsl('input', function() {
var chain = {};
var supportInputEvent = 'oninput' in document.createElement('div') && msie != 9;
chain.enter = function(value, event) {
return this.addFutureAction("input '" + this.name + "' enter '" + value + "'", function($window, $document, done) {
var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input');
input.val(value);
input.trigger(event || (supportInputEvent ? 'input' : 'change'));
done();
});
};
chain.check = function() {
return this.addFutureAction("checkbox '" + this.name + "' toggle", function($window, $document, done) {
var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':checkbox');
input.trigger('click');
done();
});
};
chain.select = function(value) {
return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'", function($window, $document, done) {
var input = $document.
elements('[ng\\:model="$1"][value="$2"]', this.name, value).filter(':radio');
input.trigger('click');
done();
});
};
chain.val = function() {
return this.addFutureAction("return input val", function($window, $document, done) {
var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input');
done(null,input.val());
});
};
return function(name) {
this.name = name;
return chain;
};
});
/**
* Usage:
* repeater('#products table', 'Product List').count() number of rows
* repeater('#products table', 'Product List').row(1) all bindings in row as an array
* repeater('#products table', 'Product List').column('product.name') all values across all rows in an array
*/
angular.scenario.dsl('repeater', function() {
var chain = {};
chain.count = function() {
return this.addFutureAction("repeater '" + this.label + "' count", function($window, $document, done) {
try {
done(null, $document.elements().length);
} catch (e) {
done(null, 0);
}
});
};
chain.column = function(binding) {
return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'", function($window, $document, done) {
done(null, $document.elements().bindings($window.angular.element, binding));
});
};
chain.row = function(index) {
return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'", function($window, $document, done) {
var matches = $document.elements().slice(index, index + 1);
if (!matches.length)
return done('row ' + index + ' out of bounds');
done(null, matches.bindings($window.angular.element));
});
};
return function(selector, label) {
this.dsl.using(selector, label);
return chain;
};
});
/**
* Usage:
* select(name).option('value') select one option
* select(name).options('value1', 'value2', ...) select options from a multi select
*/
angular.scenario.dsl('select', function() {
var chain = {};
chain.option = function(value) {
return this.addFutureAction("select '" + this.name + "' option '" + value + "'", function($window, $document, done) {
var select = $document.elements('select[ng\\:model="$1"]', this.name);
var option = select.find('option[value="' + value + '"]');
if (option.length) {
select.val(value);
} else {
option = select.find('option:contains("' + value + '")');
if (option.length) {
select.val(option.val());
}
}
select.trigger('change');
done();
});
};
chain.options = function() {
var values = arguments;
return this.addFutureAction("select '" + this.name + "' options '" + values + "'", function($window, $document, done) {
var select = $document.elements('select[multiple][ng\\:model="$1"]', this.name);
select.val(values);
select.trigger('change');
done();
});
};
return function(name) {
this.name = name;
return chain;
};
});
/**
* Usage:
* element(selector, label).count() get the number of elements that match selector
* element(selector, label).click() clicks an element
* element(selector, label).query(fn) executes fn(selectedElements, done)
* element(selector, label).{method}() gets the value (as defined by jQuery, ex. val)
* element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val)
* element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr)
* element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr)
*/
angular.scenario.dsl('element', function() {
var KEY_VALUE_METHODS = ['attr', 'css', 'prop'];
var VALUE_METHODS = [
'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width',
'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset'
];
var chain = {};
chain.count = function() {
return this.addFutureAction("element '" + this.label + "' count", function($window, $document, done) {
try {
done(null, $document.elements().length);
} catch (e) {
done(null, 0);
}
});
};
chain.click = function() {
return this.addFutureAction("element '" + this.label + "' click", function($window, $document, done) {
var elements = $document.elements();
var href = elements.attr('href');
var eventProcessDefault = elements.trigger('click')[0];
if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) {
this.application.navigateTo(href, function() {
done();
}, done);
} else {
done();
}
});
};
chain.query = function(fn) {
return this.addFutureAction('element ' + this.label + ' custom query', function($window, $document, done) {
fn.call(this, $document.elements(), done);
});
};
angular.forEach(KEY_VALUE_METHODS, function(methodName) {
chain[methodName] = function(name, value) {
var args = arguments,
futureName = (args.length == 1)
? "element '" + this.label + "' get " + methodName + " '" + name + "'"
: "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" + value + "'";
return this.addFutureAction(futureName, function($window, $document, done) {
var element = $document.elements();
done(null, element[methodName].apply(element, args));
});
};
});
angular.forEach(VALUE_METHODS, function(methodName) {
chain[methodName] = function(value) {
var args = arguments,
futureName = (args.length == 0)
? "element '" + this.label + "' " + methodName
: futureName = "element '" + this.label + "' set " + methodName + " to '" + value + "'";
return this.addFutureAction(futureName, function($window, $document, done) {
var element = $document.elements();
done(null, element[methodName].apply(element, args));
});
};
});
return function(selector, label) {
this.dsl.using(selector, label);
return chain;
};
});
/**
* Matchers for implementing specs. Follows the Jasmine spec conventions.
*/
angular.scenario.matcher('toEqual', function(expected) {
return angular.equals(this.actual, expected);
});
angular.scenario.matcher('toBe', function(expected) {
return this.actual === expected;
});
angular.scenario.matcher('toBeDefined', function() {
return angular.isDefined(this.actual);
});
angular.scenario.matcher('toBeTruthy', function() {
return this.actual;
});
angular.scenario.matcher('toBeFalsy', function() {
return !this.actual;
});
angular.scenario.matcher('toMatch', function(expected) {
return new RegExp(expected).test(this.actual);
});
angular.scenario.matcher('toBeNull', function() {
return this.actual === null;
});
angular.scenario.matcher('toContain', function(expected) {
return includes(this.actual, expected);
});
angular.scenario.matcher('toBeLessThan', function(expected) {
return this.actual < expected;
});
angular.scenario.matcher('toBeGreaterThan', function(expected) {
return this.actual > expected;
});
/**
* User Interface for the Scenario Runner.
*
* TODO(esprehn): This should be refactored now that ObjectModel exists
* to use angular bindings for the UI.
*/
angular.scenario.output('html', function(context, runner, model) {
var specUiMap = {},
lastStepUiMap = {};
context.append(
'<div id="header">' +
' <h1><span class="angular">AngularJS</span>: Scenario Test Runner</h1>' +
' <ul id="status-legend" class="status-display">' +
' <li class="status-error">0 Errors</li>' +
' <li class="status-failure">0 Failures</li>' +
' <li class="status-success">0 Passed</li>' +
' </ul>' +
'</div>' +
'<div id="specs">' +
' <div class="test-children"></div>' +
'</div>'
);
runner.on('InteractivePause', function(spec) {
var ui = lastStepUiMap[spec.id];
ui.find('.test-title').
html('paused... <a href="javascript:resume()">resume</a> when ready.');
});
runner.on('SpecBegin', function(spec) {
var ui = findContext(spec);
ui.find('> .tests').append(
'<li class="status-pending test-it"></li>'
);
ui = ui.find('> .tests li:last');
ui.append(
'<div class="test-info">' +
' <p class="test-title">' +
' <span class="timer-result"></span>' +
' <span class="test-name"></span>' +
' </p>' +
'</div>' +
'<div class="scrollpane">' +
' <ol class="test-actions"></ol>' +
'</div>'
);
ui.find('> .test-info .test-name').text(spec.name);
ui.find('> .test-info').click(function() {
var scrollpane = ui.find('> .scrollpane');
var actions = scrollpane.find('> .test-actions');
var name = context.find('> .test-info .test-name');
if (actions.find(':visible').length) {
actions.hide();
name.removeClass('open').addClass('closed');
} else {
actions.show();
scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
name.removeClass('closed').addClass('open');
}
});
specUiMap[spec.id] = ui;
});
runner.on('SpecError', function(spec, error) {
var ui = specUiMap[spec.id];
ui.append('<pre></pre>');
ui.find('> pre').text(formatException(error));
});
runner.on('SpecEnd', function(spec) {
var ui = specUiMap[spec.id];
spec = model.getSpec(spec.id);
ui.removeClass('status-pending');
ui.addClass('status-' + spec.status);
ui.find("> .test-info .timer-result").text(spec.duration + "ms");
if (spec.status === 'success') {
ui.find('> .test-info .test-name').addClass('closed');
ui.find('> .scrollpane .test-actions').hide();
}
updateTotals(spec.status);
});
runner.on('StepBegin', function(spec, step) {
var ui = specUiMap[spec.id];
spec = model.getSpec(spec.id);
step = spec.getLastStep();
ui.find('> .scrollpane .test-actions').append('<li class="status-pending"></li>');
var stepUi = lastStepUiMap[spec.id] = ui.find('> .scrollpane .test-actions li:last');
stepUi.append(
'<div class="timer-result"></div>' +
'<div class="test-title"></div>'
);
stepUi.find('> .test-title').text(step.name);
var scrollpane = stepUi.parents('.scrollpane');
scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
});
runner.on('StepFailure', function(spec, step, error) {
var ui = lastStepUiMap[spec.id];
addError(ui, step.line, error);
});
runner.on('StepError', function(spec, step, error) {
var ui = lastStepUiMap[spec.id];
addError(ui, step.line, error);
});
runner.on('StepEnd', function(spec, step) {
var stepUi = lastStepUiMap[spec.id];
spec = model.getSpec(spec.id);
step = spec.getLastStep();
stepUi.find('.timer-result').text(step.duration + 'ms');
stepUi.removeClass('status-pending');
stepUi.addClass('status-' + step.status);
var scrollpane = specUiMap[spec.id].find('> .scrollpane');
scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
});
/**
* Finds the context of a spec block defined by the passed definition.
*
* @param {Object} The definition created by the Describe object.
*/
function findContext(spec) {
var currentContext = context.find('#specs');
angular.forEach(model.getDefinitionPath(spec), function(defn) {
var id = 'describe-' + defn.id;
if (!context.find('#' + id).length) {
currentContext.find('> .test-children').append(
'<div class="test-describe" id="' + id + '">' +
' <h2></h2>' +
' <div class="test-children"></div>' +
' <ul class="tests"></ul>' +
'</div>'
);
context.find('#' + id).find('> h2').text('describe: ' + defn.name);
}
currentContext = context.find('#' + id);
});
return context.find('#describe-' + spec.definition.id);
}
/**
* Updates the test counter for the status.
*
* @param {string} the status.
*/
function updateTotals(status) {
var legend = context.find('#status-legend .status-' + status);
var parts = legend.text().split(' ');
var value = (parts[0] * 1) + 1;
legend.text(value + ' ' + parts[1]);
}
/**
* Add an error to a step.
*
* @param {Object} The JQuery wrapped context
* @param {function()} fn() that should return the file/line number of the error
* @param {Object} the error.
*/
function addError(context, line, error) {
context.find('.test-title').append('<pre></pre>');
var message = _jQuery.trim(line() + '\n\n' + formatException(error));
context.find('.test-title pre:last').text(message);
}
});
/**
* Generates JSON output into a context.
*/
angular.scenario.output('json', function(context, runner, model) {
model.on('RunnerEnd', function() {
context.text(angular.toJson(model.value));
});
});
/**
* Generates XML output into a context.
*/
angular.scenario.output('xml', function(context, runner, model) {
var $ = function(args) {return new context.init(args);};
model.on('RunnerEnd', function() {
var scenario = $('<scenario></scenario>');
context.append(scenario);
serializeXml(scenario, model.value);
});
/**
* Convert the tree into XML.
*
* @param {Object} context jQuery context to add the XML to.
* @param {Object} tree node to serialize
*/
function serializeXml(context, tree) {
angular.forEach(tree.children, function(child) {
var describeContext = $('<describe></describe>');
describeContext.attr('id', child.id);
describeContext.attr('name', child.name);
context.append(describeContext);
serializeXml(describeContext, child);
});
var its = $('<its></its>');
context.append(its);
angular.forEach(tree.specs, function(spec) {
var it = $('<it></it>');
it.attr('id', spec.id);
it.attr('name', spec.name);
it.attr('duration', spec.duration);
it.attr('status', spec.status);
its.append(it);
angular.forEach(spec.steps, function(step) {
var stepContext = $('<step></step>');
stepContext.attr('name', step.name);
stepContext.attr('duration', step.duration);
stepContext.attr('status', step.status);
it.append(stepContext);
if (step.error) {
var error = $('<error></error>');
stepContext.append(error);
error.text(formatException(step.error));
}
});
});
}
});
/**
* Creates a global value $result with the result of the runner.
*/
angular.scenario.output('object', function(context, runner, model) {
runner.$window.$result = model.value;
});
bindJQuery();
publishExternalAPI(angular);
var $runner = new angular.scenario.Runner(window),
scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1],
config = {};
angular.forEach(script.attributes, function(attr) {
var match = attr.name.match(/ng[:\-](.*)/);
if (match) {
config[match[1]] = attr.value || true;
}
});
if (config.autotest) {
JQLite(document).ready(function() {
angular.scenario.setUpAndRun(config);
});
}
})(window, document);
angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n\n[ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],\n.ng-cloak, .x-ng-cloak {\n display: none;\n}\n\nng\\:form {\n display: block;\n}\n</style>');
angular.element(document).find('head').append('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>'); | begriffs/cdnjs | ajax/libs/angular.js/1.0.7/angular-scenario.js | JavaScript | mit | 810,395 |
<?php
/*
* This file is part of Twig.
*
* (c) 2009 Fabien Potencier
* (c) 2009 Armin Ronacher
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
class Twig_Node_Expression_Filter extends Twig_Node_Expression_Call
{
public function __construct(Twig_NodeInterface $node, Twig_Node_Expression_Constant $filterName, Twig_NodeInterface $arguments, $lineno, $tag = null)
{
parent::__construct(array('node' => $node, 'filter' => $filterName, 'arguments' => $arguments), array(), $lineno, $tag);
}
public function compile(Twig_Compiler $compiler)
{
$name = $this->getNode('filter')->getAttribute('value');
$filter = $compiler->getEnvironment()->getFilter($name);
$this->setAttribute('name', $name);
$this->setAttribute('type', 'filter');
$this->setAttribute('thing', $filter);
$this->setAttribute('needs_environment', $filter->needsEnvironment());
$this->setAttribute('needs_context', $filter->needsContext());
$this->setAttribute('arguments', $filter->getArguments());
if ($filter instanceof Twig_FilterCallableInterface || $filter instanceof Twig_SimpleFilter) {
$this->setAttribute('callable', $filter->getCallable());
}
$this->compileCallable($compiler);
}
}
| PierreZerouali/Cherry | vendor/twig/twig/lib/Twig/Node/Expression/Filter.php | PHP | mit | 1,378 |
YUI.add('event-simulate', function(Y) {
(function() {
/**
* Synthetic DOM events
* @module event-simulate
* @requires event
*/
//shortcuts
var L = Y.Lang,
array = Y.Array,
isFunction = L.isFunction,
isString = L.isString,
isBoolean = L.isBoolean,
isObject = L.isObject,
isNumber = L.isNumber,
doc = Y.config.doc,
//mouse events supported
mouseEvents = {
click: 1,
dblclick: 1,
mouseover: 1,
mouseout: 1,
mousedown: 1,
mouseup: 1,
mousemove: 1
},
//key events supported
keyEvents = {
keydown: 1,
keyup: 1,
keypress: 1
},
//HTML events supported
uiEvents = {
blur: 1,
change: 1,
focus: 1,
resize: 1,
scroll: 1,
select: 1
},
//events that bubble by default
bubbleEvents = {
scroll: 1,
resize: 1,
reset: 1,
submit: 1,
change: 1,
select: 1,
error: 1,
abort: 1
};
//all key and mouse events bubble
Y.mix(bubbleEvents, mouseEvents);
Y.mix(bubbleEvents, keyEvents);
/*
* Note: Intentionally not for YUIDoc generation.
* Simulates a key event using the given event information to populate
* the generated event object. This method does browser-equalizing
* calculations to account for differences in the DOM and IE event models
* as well as different browser quirks. Note: keydown causes Safari 2.x to
* crash.
* @method simulateKeyEvent
* @private
* @static
* @param {HTMLElement} target The target of the given event.
* @param {String} type The type of event to fire. This can be any one of
* the following: keyup, keydown, and keypress.
* @param {Boolean} bubbles (Optional) Indicates if the event can be
* bubbled up. DOM Level 3 specifies that all key events bubble by
* default. The default is true.
* @param {Boolean} cancelable (Optional) Indicates if the event can be
* canceled using preventDefault(). DOM Level 3 specifies that all
* key events can be cancelled. The default
* is true.
* @param {Window} view (Optional) The view containing the target. This is
* typically the window object. The default is window.
* @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} altKey (Optional) Indicates if one of the ALT keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} metaKey (Optional) Indicates if one of the META keys
* is pressed while the event is firing. The default is false.
* @param {int} keyCode (Optional) The code for the key that is in use.
* The default is 0.
* @param {int} charCode (Optional) The Unicode code for the character
* associated with the key being used. The default is 0.
*/
function simulateKeyEvent(target /*:HTMLElement*/, type /*:String*/,
bubbles /*:Boolean*/, cancelable /*:Boolean*/,
view /*:Window*/,
ctrlKey /*:Boolean*/, altKey /*:Boolean*/,
shiftKey /*:Boolean*/, metaKey /*:Boolean*/,
keyCode /*:int*/, charCode /*:int*/) /*:Void*/
{
//check target
if (!target){
Y.error("simulateKeyEvent(): Invalid target.");
}
//check event type
if (isString(type)){
type = type.toLowerCase();
switch(type){
case "textevent": //DOM Level 3
type = "keypress";
break;
case "keyup":
case "keydown":
case "keypress":
break;
default:
Y.error("simulateKeyEvent(): Event type '" + type + "' not supported.");
}
} else {
Y.error("simulateKeyEvent(): Event type must be a string.");
}
//setup default values
if (!isBoolean(bubbles)){
bubbles = true; //all key events bubble
}
if (!isBoolean(cancelable)){
cancelable = true; //all key events can be cancelled
}
if (!isObject(view)){
view = window; //view is typically window
}
if (!isBoolean(ctrlKey)){
ctrlKey = false;
}
if (!isBoolean(altKey)){
altKey = false;
}
if (!isBoolean(shiftKey)){
shiftKey = false;
}
if (!isBoolean(metaKey)){
metaKey = false;
}
if (!isNumber(keyCode)){
keyCode = 0;
}
if (!isNumber(charCode)){
charCode = 0;
}
//try to create a mouse event
var customEvent /*:MouseEvent*/ = null;
//check for DOM-compliant browsers first
if (isFunction(doc.createEvent)){
try {
//try to create key event
customEvent = doc.createEvent("KeyEvents");
/*
* Interesting problem: Firefox implemented a non-standard
* version of initKeyEvent() based on DOM Level 2 specs.
* Key event was removed from DOM Level 2 and re-introduced
* in DOM Level 3 with a different interface. Firefox is the
* only browser with any implementation of Key Events, so for
* now, assume it's Firefox if the above line doesn't error.
*/
// @TODO: Decipher between Firefox's implementation and a correct one.
customEvent.initKeyEvent(type, bubbles, cancelable, view, ctrlKey,
altKey, shiftKey, metaKey, keyCode, charCode);
} catch (ex /*:Error*/){
/*
* If it got here, that means key events aren't officially supported.
* Safari/WebKit is a real problem now. WebKit 522 won't let you
* set keyCode, charCode, or other properties if you use a
* UIEvent, so we first must try to create a generic event. The
* fun part is that this will throw an error on Safari 2.x. The
* end result is that we need another try...catch statement just to
* deal with this mess.
*/
try {
//try to create generic event - will fail in Safari 2.x
customEvent = doc.createEvent("Events");
} catch (uierror /*:Error*/){
//the above failed, so create a UIEvent for Safari 2.x
customEvent = doc.createEvent("UIEvents");
} finally {
customEvent.initEvent(type, bubbles, cancelable);
//initialize
customEvent.view = view;
customEvent.altKey = altKey;
customEvent.ctrlKey = ctrlKey;
customEvent.shiftKey = shiftKey;
customEvent.metaKey = metaKey;
customEvent.keyCode = keyCode;
customEvent.charCode = charCode;
}
}
//fire the event
target.dispatchEvent(customEvent);
} else if (isObject(doc.createEventObject)){ //IE
//create an IE event object
customEvent = doc.createEventObject();
//assign available properties
customEvent.bubbles = bubbles;
customEvent.cancelable = cancelable;
customEvent.view = view;
customEvent.ctrlKey = ctrlKey;
customEvent.altKey = altKey;
customEvent.shiftKey = shiftKey;
customEvent.metaKey = metaKey;
/*
* IE doesn't support charCode explicitly. CharCode should
* take precedence over any keyCode value for accurate
* representation.
*/
customEvent.keyCode = (charCode > 0) ? charCode : keyCode;
//fire the event
target.fireEvent("on" + type, customEvent);
} else {
Y.error("simulateKeyEvent(): No event simulation framework present.");
}
}
/*
* Note: Intentionally not for YUIDoc generation.
* Simulates a mouse event using the given event information to populate
* the generated event object. This method does browser-equalizing
* calculations to account for differences in the DOM and IE event models
* as well as different browser quirks.
* @method simulateMouseEvent
* @private
* @static
* @param {HTMLElement} target The target of the given event.
* @param {String} type The type of event to fire. This can be any one of
* the following: click, dblclick, mousedown, mouseup, mouseout,
* mouseover, and mousemove.
* @param {Boolean} bubbles (Optional) Indicates if the event can be
* bubbled up. DOM Level 2 specifies that all mouse events bubble by
* default. The default is true.
* @param {Boolean} cancelable (Optional) Indicates if the event can be
* canceled using preventDefault(). DOM Level 2 specifies that all
* mouse events except mousemove can be cancelled. The default
* is true for all events except mousemove, for which the default
* is false.
* @param {Window} view (Optional) The view containing the target. This is
* typically the window object. The default is window.
* @param {int} detail (Optional) The number of times the mouse button has
* been used. The default value is 1.
* @param {int} screenX (Optional) The x-coordinate on the screen at which
* point the event occured. The default is 0.
* @param {int} screenY (Optional) The y-coordinate on the screen at which
* point the event occured. The default is 0.
* @param {int} clientX (Optional) The x-coordinate on the client at which
* point the event occured. The default is 0.
* @param {int} clientY (Optional) The y-coordinate on the client at which
* point the event occured. The default is 0.
* @param {Boolean} ctrlKey (Optional) Indicates if one of the CTRL keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} altKey (Optional) Indicates if one of the ALT keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} shiftKey (Optional) Indicates if one of the SHIFT keys
* is pressed while the event is firing. The default is false.
* @param {Boolean} metaKey (Optional) Indicates if one of the META keys
* is pressed while the event is firing. The default is false.
* @param {int} button (Optional) The button being pressed while the event
* is executing. The value should be 0 for the primary mouse button
* (typically the left button), 1 for the terciary mouse button
* (typically the middle button), and 2 for the secondary mouse button
* (typically the right button). The default is 0.
* @param {HTMLElement} relatedTarget (Optional) For mouseout events,
* this is the element that the mouse has moved to. For mouseover
* events, this is the element that the mouse has moved from. This
* argument is ignored for all other events. The default is null.
*/
function simulateMouseEvent(target /*:HTMLElement*/, type /*:String*/,
bubbles /*:Boolean*/, cancelable /*:Boolean*/,
view /*:Window*/, detail /*:int*/,
screenX /*:int*/, screenY /*:int*/,
clientX /*:int*/, clientY /*:int*/,
ctrlKey /*:Boolean*/, altKey /*:Boolean*/,
shiftKey /*:Boolean*/, metaKey /*:Boolean*/,
button /*:int*/, relatedTarget /*:HTMLElement*/) /*:Void*/
{
//check target
if (!target){
Y.error("simulateMouseEvent(): Invalid target.");
}
//check event type
if (isString(type)){
type = type.toLowerCase();
//make sure it's a supported mouse event
if (!mouseEvents[type]){
Y.error("simulateMouseEvent(): Event type '" + type + "' not supported.");
}
} else {
Y.error("simulateMouseEvent(): Event type must be a string.");
}
//setup default values
if (!isBoolean(bubbles)){
bubbles = true; //all mouse events bubble
}
if (!isBoolean(cancelable)){
cancelable = (type != "mousemove"); //mousemove is the only one that can't be cancelled
}
if (!isObject(view)){
view = window; //view is typically window
}
if (!isNumber(detail)){
detail = 1; //number of mouse clicks must be at least one
}
if (!isNumber(screenX)){
screenX = 0;
}
if (!isNumber(screenY)){
screenY = 0;
}
if (!isNumber(clientX)){
clientX = 0;
}
if (!isNumber(clientY)){
clientY = 0;
}
if (!isBoolean(ctrlKey)){
ctrlKey = false;
}
if (!isBoolean(altKey)){
altKey = false;
}
if (!isBoolean(shiftKey)){
shiftKey = false;
}
if (!isBoolean(metaKey)){
metaKey = false;
}
if (!isNumber(button)){
button = 0;
}
relatedTarget = relatedTarget || null;
//try to create a mouse event
var customEvent /*:MouseEvent*/ = null;
//check for DOM-compliant browsers first
if (isFunction(doc.createEvent)){
customEvent = doc.createEvent("MouseEvents");
//Safari 2.x (WebKit 418) still doesn't implement initMouseEvent()
if (customEvent.initMouseEvent){
customEvent.initMouseEvent(type, bubbles, cancelable, view, detail,
screenX, screenY, clientX, clientY,
ctrlKey, altKey, shiftKey, metaKey,
button, relatedTarget);
} else { //Safari
//the closest thing available in Safari 2.x is UIEvents
customEvent = doc.createEvent("UIEvents");
customEvent.initEvent(type, bubbles, cancelable);
customEvent.view = view;
customEvent.detail = detail;
customEvent.screenX = screenX;
customEvent.screenY = screenY;
customEvent.clientX = clientX;
customEvent.clientY = clientY;
customEvent.ctrlKey = ctrlKey;
customEvent.altKey = altKey;
customEvent.metaKey = metaKey;
customEvent.shiftKey = shiftKey;
customEvent.button = button;
customEvent.relatedTarget = relatedTarget;
}
/*
* Check to see if relatedTarget has been assigned. Firefox
* versions less than 2.0 don't allow it to be assigned via
* initMouseEvent() and the property is readonly after event
* creation, so in order to keep YAHOO.util.getRelatedTarget()
* working, assign to the IE proprietary toElement property
* for mouseout event and fromElement property for mouseover
* event.
*/
if (relatedTarget && !customEvent.relatedTarget){
if (type == "mouseout"){
customEvent.toElement = relatedTarget;
} else if (type == "mouseover"){
customEvent.fromElement = relatedTarget;
}
}
//fire the event
target.dispatchEvent(customEvent);
} else if (isObject(doc.createEventObject)){ //IE
//create an IE event object
customEvent = doc.createEventObject();
//assign available properties
customEvent.bubbles = bubbles;
customEvent.cancelable = cancelable;
customEvent.view = view;
customEvent.detail = detail;
customEvent.screenX = screenX;
customEvent.screenY = screenY;
customEvent.clientX = clientX;
customEvent.clientY = clientY;
customEvent.ctrlKey = ctrlKey;
customEvent.altKey = altKey;
customEvent.metaKey = metaKey;
customEvent.shiftKey = shiftKey;
//fix button property for IE's wacky implementation
switch(button){
case 0:
customEvent.button = 1;
break;
case 1:
customEvent.button = 4;
break;
case 2:
//leave as is
break;
default:
customEvent.button = 0;
}
/*
* Have to use relatedTarget because IE won't allow assignment
* to toElement or fromElement on generic events. This keeps
* YAHOO.util.customEvent.getRelatedTarget() functional.
*/
customEvent.relatedTarget = relatedTarget;
//fire the event
target.fireEvent("on" + type, customEvent);
} else {
Y.error("simulateMouseEvent(): No event simulation framework present.");
}
}
/*
* Note: Intentionally not for YUIDoc generation.
* Simulates a UI event using the given event information to populate
* the generated event object. This method does browser-equalizing
* calculations to account for differences in the DOM and IE event models
* as well as different browser quirks.
* @method simulateHTMLEvent
* @private
* @static
* @param {HTMLElement} target The target of the given event.
* @param {String} type The type of event to fire. This can be any one of
* the following: click, dblclick, mousedown, mouseup, mouseout,
* mouseover, and mousemove.
* @param {Boolean} bubbles (Optional) Indicates if the event can be
* bubbled up. DOM Level 2 specifies that all mouse events bubble by
* default. The default is true.
* @param {Boolean} cancelable (Optional) Indicates if the event can be
* canceled using preventDefault(). DOM Level 2 specifies that all
* mouse events except mousemove can be cancelled. The default
* is true for all events except mousemove, for which the default
* is false.
* @param {Window} view (Optional) The view containing the target. This is
* typically the window object. The default is window.
* @param {int} detail (Optional) The number of times the mouse button has
* been used. The default value is 1.
*/
function simulateUIEvent(target /*:HTMLElement*/, type /*:String*/,
bubbles /*:Boolean*/, cancelable /*:Boolean*/,
view /*:Window*/, detail /*:int*/) /*:Void*/
{
//check target
if (!target){
Y.error("simulateUIEvent(): Invalid target.");
}
//check event type
if (isString(type)){
type = type.toLowerCase();
//make sure it's a supported mouse event
if (!uiEvents[type]){
Y.error("simulateUIEvent(): Event type '" + type + "' not supported.");
}
} else {
Y.error("simulateUIEvent(): Event type must be a string.");
}
//try to create a mouse event
var customEvent = null;
//setup default values
if (!isBoolean(bubbles)){
bubbles = (type in bubbleEvents); //not all events bubble
}
if (!isBoolean(cancelable)){
cancelable = (type == "submit"); //submit is the only one that can be cancelled
}
if (!isObject(view)){
view = window; //view is typically window
}
if (!isNumber(detail)){
detail = 1; //usually not used but defaulted to this
}
//check for DOM-compliant browsers first
if (isFunction(doc.createEvent)){
//just a generic UI Event object is needed
customEvent = doc.createEvent("UIEvents");
customEvent.initUIEvent(type, bubbles, cancelable, view, detail);
//fire the event
target.dispatchEvent(customEvent);
} else if (isObject(doc.createEventObject)){ //IE
//create an IE event object
customEvent = doc.createEventObject();
//assign available properties
customEvent.bubbles = bubbles;
customEvent.cancelable = cancelable;
customEvent.view = view;
customEvent.detail = detail;
//fire the event
target.fireEvent("on" + type, customEvent);
} else {
Y.error("simulateUIEvent(): No event simulation framework present.");
}
}
/**
* Simulates the event with the given name on a target.
* @param {HTMLElement} target The DOM element that's the target of the event.
* @param {String} type The type of event to simulate (i.e., "click").
* @param {Object} options (Optional) Extra options to copy onto the event object.
* @return {void}
* @for Event
* @method simulate
* @static
*/
Y.Event.simulate = function(target, type, options){
options = options || {};
if (mouseEvents[type]){
simulateMouseEvent(target, type, options.bubbles,
options.cancelable, options.view, options.detail, options.screenX,
options.screenY, options.clientX, options.clientY, options.ctrlKey,
options.altKey, options.shiftKey, options.metaKey, options.button,
options.relatedTarget);
} else if (keyEvents[type]){
simulateKeyEvent(target, type, options.bubbles,
options.cancelable, options.view, options.ctrlKey,
options.altKey, options.shiftKey, options.metaKey,
options.keyCode, options.charCode);
} else if (uiEvents[type]){
simulateUIEvent(target, type, options.bubbles,
options.cancelable, options.view, options.detail);
} else {
Y.error("simulate(): Event '" + type + "' can't be simulated.");
}
};
})();
}, '@VERSION@' ,{requires:['event-base']});
| iamJoeTaylor/cdnjs | ajax/libs/yui/3.4.0pr3/event-simulate/event-simulate.js | JavaScript | mit | 21,630 |
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/date",["./has","./_base/lang"],function(_1,_2){
var _3={};
_3.getDaysInMonth=function(_4){
var _5=_4.getMonth();
var _6=[31,28,31,30,31,30,31,31,30,31,30,31];
if(_5==1&&_3.isLeapYear(_4)){
return 29;
}
return _6[_5];
};
_3.isLeapYear=function(_7){
var _8=_7.getFullYear();
return !(_8%400)||(!(_8%4)&&!!(_8%100));
};
_3.getTimezoneName=function(_9){
var _a=_9.toString();
var tz="";
var _b;
var _c=_a.indexOf("(");
if(_c>-1){
tz=_a.substring(++_c,_a.indexOf(")"));
}else{
var _d=/([A-Z\/]+) \d{4}$/;
if((_b=_a.match(_d))){
tz=_b[1];
}else{
_a=_9.toLocaleString();
_d=/ ([A-Z\/]+)$/;
if((_b=_a.match(_d))){
tz=_b[1];
}
}
}
return (tz=="AM"||tz=="PM")?"":tz;
};
_3.compare=function(_e,_f,_10){
_e=new Date(+_e);
_f=new Date(+(_f||new Date()));
if(_10=="date"){
_e.setHours(0,0,0,0);
_f.setHours(0,0,0,0);
}else{
if(_10=="time"){
_e.setFullYear(0,0,0);
_f.setFullYear(0,0,0);
}
}
if(_e>_f){
return 1;
}
if(_e<_f){
return -1;
}
return 0;
};
_3.add=function(_11,_12,_13){
var sum=new Date(+_11);
var _14=false;
var _15="Date";
switch(_12){
case "day":
break;
case "weekday":
var _16,_17;
var mod=_13%5;
if(!mod){
_16=(_13>0)?5:-5;
_17=(_13>0)?((_13-5)/5):((_13+5)/5);
}else{
_16=mod;
_17=parseInt(_13/5);
}
var _18=_11.getDay();
var adj=0;
if(_18==6&&_13>0){
adj=1;
}else{
if(_18==0&&_13<0){
adj=-1;
}
}
var _19=_18+_16;
if(_19==0||_19==6){
adj=(_13>0)?2:-2;
}
_13=(7*_17)+_16+adj;
break;
case "year":
_15="FullYear";
_14=true;
break;
case "week":
_13*=7;
break;
case "quarter":
_13*=3;
case "month":
_14=true;
_15="Month";
break;
default:
_15="UTC"+_12.charAt(0).toUpperCase()+_12.substring(1)+"s";
}
if(_15){
sum["set"+_15](sum["get"+_15]()+_13);
}
if(_14&&(sum.getDate()<_11.getDate())){
sum.setDate(0);
}
return sum;
};
_3.difference=function(_1a,_1b,_1c){
_1b=_1b||new Date();
_1c=_1c||"day";
var _1d=_1b.getFullYear()-_1a.getFullYear();
var _1e=1;
switch(_1c){
case "quarter":
var m1=_1a.getMonth();
var m2=_1b.getMonth();
var q1=Math.floor(m1/3)+1;
var q2=Math.floor(m2/3)+1;
q2+=(_1d*4);
_1e=q2-q1;
break;
case "weekday":
var _1f=Math.round(_3.difference(_1a,_1b,"day"));
var _20=parseInt(_3.difference(_1a,_1b,"week"));
var mod=_1f%7;
if(mod==0){
_1f=_20*5;
}else{
var adj=0;
var _21=_1a.getDay();
var _22=_1b.getDay();
_20=parseInt(_1f/7);
mod=_1f%7;
var _23=new Date(_1a);
_23.setDate(_23.getDate()+(_20*7));
var _24=_23.getDay();
if(_1f>0){
switch(true){
case _21==6:
adj=-1;
break;
case _21==0:
adj=0;
break;
case _22==6:
adj=-1;
break;
case _22==0:
adj=-2;
break;
case (_24+mod)>5:
adj=-2;
}
}else{
if(_1f<0){
switch(true){
case _21==6:
adj=0;
break;
case _21==0:
adj=1;
break;
case _22==6:
adj=2;
break;
case _22==0:
adj=1;
break;
case (_24+mod)<0:
adj=2;
}
}
}
_1f+=adj;
_1f-=(_20*2);
}
_1e=_1f;
break;
case "year":
_1e=_1d;
break;
case "month":
_1e=(_1b.getMonth()-_1a.getMonth())+(_1d*12);
break;
case "week":
_1e=parseInt(_3.difference(_1a,_1b,"day")/7);
break;
case "day":
_1e/=24;
case "hour":
_1e/=60;
case "minute":
_1e/=60;
case "second":
_1e/=1000;
case "millisecond":
_1e*=_1b.getTime()-_1a.getTime();
}
return Math.round(_1e);
};
1&&_2.mixin(_2.getObject("dojo.date",true),_3);
return _3;
});
| algolia/cdnjs | ajax/libs/dojo/1.9.0/date.js | JavaScript | mit | 3,334 |
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/date",["./has","./_base/lang"],function(_1,_2){
var _3={};
_3.getDaysInMonth=function(_4){
var _5=_4.getMonth();
var _6=[31,28,31,30,31,30,31,31,30,31,30,31];
if(_5==1&&_3.isLeapYear(_4)){
return 29;
}
return _6[_5];
};
_3.isLeapYear=function(_7){
var _8=_7.getFullYear();
return !(_8%400)||(!(_8%4)&&!!(_8%100));
};
_3.getTimezoneName=function(_9){
var _a=_9.toString();
var tz="";
var _b;
var _c=_a.indexOf("(");
if(_c>-1){
tz=_a.substring(++_c,_a.indexOf(")"));
}else{
var _d=/([A-Z\/]+) \d{4}$/;
if((_b=_a.match(_d))){
tz=_b[1];
}else{
_a=_9.toLocaleString();
_d=/ ([A-Z\/]+)$/;
if((_b=_a.match(_d))){
tz=_b[1];
}
}
}
return (tz=="AM"||tz=="PM")?"":tz;
};
_3.compare=function(_e,_f,_10){
_e=new Date(+_e);
_f=new Date(+(_f||new Date()));
if(_10=="date"){
_e.setHours(0,0,0,0);
_f.setHours(0,0,0,0);
}else{
if(_10=="time"){
_e.setFullYear(0,0,0);
_f.setFullYear(0,0,0);
}
}
if(_e>_f){
return 1;
}
if(_e<_f){
return -1;
}
return 0;
};
_3.add=function(_11,_12,_13){
var sum=new Date(+_11);
var _14=false;
var _15="Date";
switch(_12){
case "day":
break;
case "weekday":
var _16,_17;
var mod=_13%5;
if(!mod){
_16=(_13>0)?5:-5;
_17=(_13>0)?((_13-5)/5):((_13+5)/5);
}else{
_16=mod;
_17=parseInt(_13/5);
}
var _18=_11.getDay();
var adj=0;
if(_18==6&&_13>0){
adj=1;
}else{
if(_18==0&&_13<0){
adj=-1;
}
}
var _19=_18+_16;
if(_19==0||_19==6){
adj=(_13>0)?2:-2;
}
_13=(7*_17)+_16+adj;
break;
case "year":
_15="FullYear";
_14=true;
break;
case "week":
_13*=7;
break;
case "quarter":
_13*=3;
case "month":
_14=true;
_15="Month";
break;
default:
_15="UTC"+_12.charAt(0).toUpperCase()+_12.substring(1)+"s";
}
if(_15){
sum["set"+_15](sum["get"+_15]()+_13);
}
if(_14&&(sum.getDate()<_11.getDate())){
sum.setDate(0);
}
return sum;
};
_3.difference=function(_1a,_1b,_1c){
_1b=_1b||new Date();
_1c=_1c||"day";
var _1d=_1b.getFullYear()-_1a.getFullYear();
var _1e=1;
switch(_1c){
case "quarter":
var m1=_1a.getMonth();
var m2=_1b.getMonth();
var q1=Math.floor(m1/3)+1;
var q2=Math.floor(m2/3)+1;
q2+=(_1d*4);
_1e=q2-q1;
break;
case "weekday":
var _1f=Math.round(_3.difference(_1a,_1b,"day"));
var _20=parseInt(_3.difference(_1a,_1b,"week"));
var mod=_1f%7;
if(mod==0){
_1f=_20*5;
}else{
var adj=0;
var _21=_1a.getDay();
var _22=_1b.getDay();
_20=parseInt(_1f/7);
mod=_1f%7;
var _23=new Date(_1a);
_23.setDate(_23.getDate()+(_20*7));
var _24=_23.getDay();
if(_1f>0){
switch(true){
case _21==6:
adj=-1;
break;
case _21==0:
adj=0;
break;
case _22==6:
adj=-1;
break;
case _22==0:
adj=-2;
break;
case (_24+mod)>5:
adj=-2;
}
}else{
if(_1f<0){
switch(true){
case _21==6:
adj=0;
break;
case _21==0:
adj=1;
break;
case _22==6:
adj=2;
break;
case _22==0:
adj=1;
break;
case (_24+mod)<0:
adj=2;
}
}
}
_1f+=adj;
_1f-=(_20*2);
}
_1e=_1f;
break;
case "year":
_1e=_1d;
break;
case "month":
_1e=(_1b.getMonth()-_1a.getMonth())+(_1d*12);
break;
case "week":
_1e=parseInt(_3.difference(_1a,_1b,"day")/7);
break;
case "day":
_1e/=24;
case "hour":
_1e/=60;
case "minute":
_1e/=60;
case "second":
_1e/=1000;
case "millisecond":
_1e*=_1b.getTime()-_1a.getTime();
}
return Math.round(_1e);
};
1&&_2.mixin(_2.getObject("dojo.date",true),_3);
return _3;
});
| wmkcc/cdnjs | ajax/libs/dojo/1.9.0/date.js | JavaScript | mit | 3,334 |
/**
* lodash 3.6.1 (Custom Build) <https://lodash.com/>
* Build: `lodash modern modularize exports="npm" -o ./`
* Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/>
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
* Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
* Available under MIT license <https://lodash.com/license>
*/
/** Used as the `TypeError` message for "Functions" methods. */
var FUNC_ERROR_TEXT = 'Expected a function';
/* Native method references for those with the same name as other `lodash` methods. */
var nativeMax = Math.max;
/**
* Creates a function that invokes `func` with the `this` binding of the
* created function and arguments from `start` and beyond provided as an array.
*
* **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters).
*
* @static
* @memberOf _
* @category Function
* @param {Function} func The function to apply a rest parameter to.
* @param {number} [start=func.length-1] The start position of the rest parameter.
* @returns {Function} Returns the new function.
* @example
*
* var say = _.restParam(function(what, names) {
* return what + ' ' + _.initial(names).join(', ') +
* (_.size(names) > 1 ? ', & ' : '') + _.last(names);
* });
*
* say('hello', 'fred', 'barney', 'pebbles');
* // => 'hello fred, barney, & pebbles'
*/
function restParam(func, start) {
if (typeof func != 'function') {
throw new TypeError(FUNC_ERROR_TEXT);
}
start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0);
return function() {
var args = arguments,
index = -1,
length = nativeMax(args.length - start, 0),
rest = Array(length);
while (++index < length) {
rest[index] = args[start + index];
}
switch (start) {
case 0: return func.call(this, rest);
case 1: return func.call(this, args[0], rest);
case 2: return func.call(this, args[0], args[1], rest);
}
var otherArgs = Array(start + 1);
index = -1;
while (++index < start) {
otherArgs[index] = args[index];
}
otherArgs[start] = rest;
return func.apply(this, otherArgs);
};
}
module.exports = restParam;
| jfehrman/extend | node_modules/lodash.restparam/index.js | JavaScript | mit | 2,319 |
videojs.addLanguage("vi",{
"Play": "Phát",
"Pause": "Tạm dừng",
"Current Time": "Thời gian hiện tại",
"Duration Time": "Độ dài",
"Remaining Time": "Thời gian còn lại",
"Stream Type": "Kiểu Stream",
"LIVE": "TRỰC TIẾP",
"Loaded": "Đã tải",
"Progress": "Tiến trình",
"Fullscreen": "Toàn màn hình",
"Non-Fullscreen": "Thoát toàn màn hình",
"Mute": "Tắt tiếng",
"Unmuted": "Bật âm thanh",
"Playback Rate": "Tốc độ phát",
"Subtitles": "Phụ đề",
"subtitles off": "Tắt phụ đề",
"Captions": "Chú thích",
"captions off": "Tắt chú thích",
"Chapters": "Chương",
"You aborted the video playback": "Bạn đã hủy việc phát video.",
"A network error caused the video download to fail part-way.": "Một lỗi mạng dẫn đến việc tải video bị lỗi.",
"The video could not be loaded, either because the server or network failed or because the format is not supported.": "Video không tải được, mạng hay server có lỗi hoặc định dạng không được hỗ trợ.",
"The video playback was aborted due to a corruption problem or because the video used features your browser did not support.": "Phát video đã bị hủy do một sai lỗi hoặc video sử dụng những tính năng trình duyệt không hỗ trợ.",
"No compatible source was found for this video.": "Không có nguồn tương thích cho video này."
}); | shallaa/cdnjs | ajax/libs/video.js/4.12.0/lang/vi.js | JavaScript | mit | 1,440 |
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),(f.jsondiffpatch||(f.jsondiffpatch={})).formatters=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
module.exports=require("./formatters");
},{"./formatters":6}],2:[function(require,module,exports){
exports.isBrowser="undefined"!=typeof window;
},{}],3:[function(require,module,exports){
var base=require("./base"),BaseFormatter=base.BaseFormatter,AnnotatedFormatter=function(){this.includeMoveDestinations=!1};AnnotatedFormatter.prototype=new BaseFormatter,AnnotatedFormatter.prototype.prepareContext=function(t){BaseFormatter.prototype.prepareContext.call(this,t),t.indent=function(t){this.indentLevel=(this.indentLevel||0)+("undefined"==typeof t?1:t),this.indentPad=new Array(this.indentLevel+1).join(" ")},t.row=function(e,n){t.out('<tr><td style="white-space: nowrap;"><pre class="jsondiffpatch-annotated-indent" style="display: inline-block">'),t.out(t.indentPad),t.out('</pre><pre style="display: inline-block">'),t.out(e),t.out('</pre></td><td class="jsondiffpatch-delta-note"><div>'),t.out(n),t.out("</div></td></tr>")}},AnnotatedFormatter.prototype.typeFormattterErrorFormatter=function(t,e){t.row("",'<pre class="jsondiffpatch-error">'+e+"</pre>")},AnnotatedFormatter.prototype.formatTextDiffString=function(t,e){var n=this.parseTextDiff(e);t.out('<ul class="jsondiffpatch-textdiff">');for(var o=0,r=n.length;r>o;o++){var a=n[o];t.out('<li><div class="jsondiffpatch-textdiff-location"><span class="jsondiffpatch-textdiff-line-number">'+a.location.line+'</span><span class="jsondiffpatch-textdiff-char">'+a.location.chr+'</span></div><div class="jsondiffpatch-textdiff-line">');for(var i=a.pieces,d=0,p=i.length;p>d;d++){var f=i[d];t.out('<span class="jsondiffpatch-textdiff-'+f.type+'">'+f.text+"</span>")}t.out("</div></li>")}t.out("</ul>")},AnnotatedFormatter.prototype.rootBegin=function(t,e,n){t.out('<table class="jsondiffpatch-annotated-delta">'),"node"===e&&(t.row("{"),t.indent()),"array"===n&&t.row('"_t": "a",',"Array delta (member names indicate array indices)")},AnnotatedFormatter.prototype.rootEnd=function(t,e){"node"===e&&(t.indent(-1),t.row("}")),t.out("</table>")},AnnotatedFormatter.prototype.nodeBegin=function(t,e,n,o,r){t.row("""+e+"": {"),"node"===o&&t.indent(),"array"===r&&t.row('"_t": "a",',"Array delta (member names indicate array indices)")},AnnotatedFormatter.prototype.nodeEnd=function(t,e,n,o,r,a){"node"===o&&t.indent(-1),t.row("}"+(a?"":","))},AnnotatedFormatter.prototype.format_unchanged=function(){},AnnotatedFormatter.prototype.format_movedestination=function(){},AnnotatedFormatter.prototype.format_node=function(t,e,n){this.formatDeltaChildren(t,e,n)};var wrapPropertyName=function(t){return'<pre style="display:inline-block">"'+t+""</pre>"},deltaAnnotations={added:function(t,e,n,o){var r=" <pre>([newValue])</pre>";return"undefined"==typeof o?"new value"+r:"number"==typeof o?"insert at index "+o+r:"add property "+wrapPropertyName(o)+r},modified:function(t,e,n,o){var r=" <pre>([previousValue, newValue])</pre>";return"undefined"==typeof o?"modify value"+r:"number"==typeof o?"modify at index "+o+r:"modify property "+wrapPropertyName(o)+r},deleted:function(t,e,n,o){var r=" <pre>([previousValue, 0, 0])</pre>";return"undefined"==typeof o?"delete value"+r:"number"==typeof o?"remove index "+o+r:"delete property "+wrapPropertyName(o)+r},moved:function(t,e,n,o){return'move from <span title="(position to remove at original state)">index '+o+'</span> to <span title="(position to insert at final state)">index '+t[1]+"</span>"},textdiff:function(t,e,n,o){var r="undefined"==typeof o?"":"number"==typeof o?" at index "+o:" at property "+wrapPropertyName(o);return"text diff"+r+', format is <a href="https://code.google.com/p/google-diff-match-patch/wiki/Unidiff">a variation of Unidiff</a>'}},formatAnyChange=function(t,e){var n=this.getDeltaType(e),o=deltaAnnotations[n],r=o&&o.apply(o,Array.prototype.slice.call(arguments,1)),a=JSON.stringify(e,null,2);"textdiff"===n&&(a=a.split("\\n").join('\\n"+\n "')),t.indent(),t.row(a,r),t.indent(-1)};AnnotatedFormatter.prototype.format_added=formatAnyChange,AnnotatedFormatter.prototype.format_modified=formatAnyChange,AnnotatedFormatter.prototype.format_deleted=formatAnyChange,AnnotatedFormatter.prototype.format_moved=formatAnyChange,AnnotatedFormatter.prototype.format_textdiff=formatAnyChange,exports.AnnotatedFormatter=AnnotatedFormatter;var defaultInstance;exports.format=function(t,e){return defaultInstance||(defaultInstance=new AnnotatedFormatter),defaultInstance.format(t,e)};
},{"./base":4}],4:[function(require,module,exports){
var isArray="function"==typeof Array.isArray?Array.isArray:function(e){return e instanceof Array},getObjectKeys="function"==typeof Object.keys?function(e){return Object.keys(e)}:function(e){var t=[];for(var r in e)e.hasOwnProperty(r)&&t.push(r);return t},trimUnderscore=function(e){return"_"===e.substr(0,1)?e.slice(1):e},arrayKeyToSortNumber=function(e){return"_t"===e?-1:"_"===e.substr(0,1)?parseInt(e.slice(1),10):parseInt(e,10)+.1},arrayKeyComparer=function(e,t){return arrayKeyToSortNumber(e)-arrayKeyToSortNumber(t)},BaseFormatter=function(){};BaseFormatter.prototype.format=function(e,t){var r={};return this.prepareContext(r),this.recurse(r,e,t),this.finalize(r)},BaseFormatter.prototype.prepareContext=function(e){e.buffer=[],e.out=function(){this.buffer.push.apply(this.buffer,arguments)}},BaseFormatter.prototype.typeFormattterNotFound=function(e,t){throw new Error("cannot format delta type: "+t)},BaseFormatter.prototype.typeFormattterErrorFormatter=function(e,t){return t.toString()},BaseFormatter.prototype.finalize=function(e){return isArray(e.buffer)?e.buffer.join(""):void 0},BaseFormatter.prototype.recurse=function(e,t,r,o,n,a,i){var f=t&&a,s=f?a.value:r;if("undefined"==typeof t&&"undefined"==typeof o)return void 0;var u=this.getDeltaType(t,a),p="node"===u?"a"===t._t?"array":"object":"";"undefined"!=typeof o?this.nodeBegin(e,o,n,u,p,i):this.rootBegin(e,u,p);var y;try{y=this["format_"+u]||this.typeFormattterNotFound(e,u),y.call(this,e,t,s,o,n,a)}catch(d){this.typeFormattterErrorFormatter(e,d,t,s,o,n,a),"undefined"!=typeof console&&console.error&&console.error(d.stack)}"undefined"!=typeof o?this.nodeEnd(e,o,n,u,p,i):this.rootEnd(e,u,p)},BaseFormatter.prototype.formatDeltaChildren=function(e,t,r){var o=this;this.forEachDeltaKey(t,r,function(n,a,i,f){o.recurse(e,t[n],r?r[a]:void 0,n,a,i,f)})},BaseFormatter.prototype.forEachDeltaKey=function(e,t,r){var o,n=getObjectKeys(e),a="a"===e._t,i={};if("undefined"!=typeof t)for(o in t)"undefined"!=typeof e[o]||a&&"undefined"!=typeof e["_"+o]||n.push(o);for(o in e){var f=e[o];isArray(f)&&3===f[2]&&(i[f[1].toString()]={key:o,value:t&&t[parseInt(o.substr(1))]},this.includeMoveDestinations!==!1&&"undefined"==typeof t&&"undefined"==typeof e[f[1]]&&n.push(f[1].toString()))}a?n.sort(arrayKeyComparer):n.sort();for(var s=0,u=n.length;u>s;s++){var p=n[s];if(!a||"_t"!==p){var y=a?"number"==typeof p?p:parseInt(trimUnderscore(p),10):p,d=s===u-1;r(p,y,i[y],d)}}},BaseFormatter.prototype.getDeltaType=function(e,t){if("undefined"==typeof e)return"undefined"!=typeof t?"movedestination":"unchanged";if(isArray(e)){if(1===e.length)return"added";if(2===e.length)return"modified";if(3===e.length&&0===e[2])return"deleted";if(3===e.length&&2===e[2])return"textdiff";if(3===e.length&&3===e[2])return"moved"}else if("object"==typeof e)return"node";return"unknown"},BaseFormatter.prototype.parseTextDiff=function(e){for(var t=[],r=e.split("\n@@ "),o=0,n=r.length;n>o;o++){var a=r[o],i={pieces:[]},f=/^(?:@@ )?[-+]?(\d+),(\d+)/.exec(a).slice(1);i.location={line:f[0],chr:f[1]};for(var s=a.split("\n").slice(1),u=0,p=s.length;p>u;u++){var y=s[u];if(y.length){var d={type:"context"};"+"===y.substr(0,1)?d.type="added":"-"===y.substr(0,1)&&(d.type="deleted"),d.text=y.slice(1),i.pieces.push(d)}}t.push(i)}return t},exports.BaseFormatter=BaseFormatter;
},{}],5:[function(require,module,exports){
function htmlEscape(t){for(var e=t,o=[[/&/g,"&"],[/</g,"<"],[/>/g,">"],[/'/g,"'"],[/"/g,"""]],r=0;r<o.length;r++)e=e.replace(o[r][0],o[r][1]);return e}var base=require("./base"),BaseFormatter=base.BaseFormatter,HtmlFormatter=function(){};HtmlFormatter.prototype=new BaseFormatter,HtmlFormatter.prototype.typeFormattterErrorFormatter=function(t,e){t.out('<pre class="jsondiffpatch-error">'+e+"</pre>")},HtmlFormatter.prototype.formatValue=function(t,e){t.out("<pre>"+htmlEscape(JSON.stringify(e,null,2))+"</pre>")},HtmlFormatter.prototype.formatTextDiffString=function(t,e){var o=this.parseTextDiff(e);t.out('<ul class="jsondiffpatch-textdiff">');for(var r=0,a=o.length;a>r;r++){var i=o[r];t.out('<li><div class="jsondiffpatch-textdiff-location"><span class="jsondiffpatch-textdiff-line-number">'+i.location.line+'</span><span class="jsondiffpatch-textdiff-char">'+i.location.chr+'</span></div><div class="jsondiffpatch-textdiff-line">');for(var n=i.pieces,s=0,d=n.length;d>s;s++){var f=n[s];t.out('<span class="jsondiffpatch-textdiff-'+f.type+'">'+htmlEscape(f.text)+"</span>")}t.out("</div></li>")}t.out("</ul>")};var adjustArrows=function(t){t=t||document;var e=function(t){return t.textContent||t.innerText},o=function(t,e,o){for(var r=t.querySelectorAll(e),a=0,i=r.length;i>a;a++)o(r[a])},r=function(t,e){for(var o=0,r=t.children.length;r>o;o++)e(t.children[o],o)};o(t,".jsondiffpatch-arrow",function(t){var o=t.parentNode,a=t.children[0],i=a.children[1];a.style.display="none";var n,s=e(o.querySelector(".jsondiffpatch-moved-destination")),d=o.parentNode;if(r(d,function(t){t.getAttribute("data-key")===s&&(n=t)}),n)try{var f=n.offsetTop-o.offsetTop;a.setAttribute("height",Math.abs(f)+6),t.style.top=-8+(f>0?0:f)+"px";var l=f>0?"M30,0 Q-10,"+Math.round(f/2)+" 26,"+(f-4):"M30,"+-f+" Q-10,"+Math.round(-f/2)+" 26,4";i.setAttribute("d",l),a.style.display=""}catch(c){return}})};HtmlFormatter.prototype.rootBegin=function(t,e,o){var r="jsondiffpatch-"+e+(o?" jsondiffpatch-child-node-type-"+o:"");t.out('<div class="jsondiffpatch-delta '+r+'">')},HtmlFormatter.prototype.rootEnd=function(t){t.out("</div>"+(t.hasArrows?'<script type="text/javascript">setTimeout('+adjustArrows.toString()+",10);</script>":""))},HtmlFormatter.prototype.nodeBegin=function(t,e,o,r,a){var i="jsondiffpatch-"+r+(a?" jsondiffpatch-child-node-type-"+a:"");t.out('<li class="'+i+'" data-key="'+o+'"><div class="jsondiffpatch-property-name">'+o+"</div>")},HtmlFormatter.prototype.nodeEnd=function(t){t.out("</li>")},HtmlFormatter.prototype.format_unchanged=function(t,e,o){"undefined"!=typeof o&&(t.out('<div class="jsondiffpatch-value">'),this.formatValue(t,o),t.out("</div>"))},HtmlFormatter.prototype.format_movedestination=function(t,e,o){"undefined"!=typeof o&&(t.out('<div class="jsondiffpatch-value">'),this.formatValue(t,o),t.out("</div>"))},HtmlFormatter.prototype.format_node=function(t,e,o){var r="a"===e._t?"array":"object";t.out('<ul class="jsondiffpatch-node jsondiffpatch-node-type-'+r+'">'),this.formatDeltaChildren(t,e,o),t.out("</ul>")},HtmlFormatter.prototype.format_added=function(t,e){t.out('<div class="jsondiffpatch-value">'),this.formatValue(t,e[0]),t.out("</div>")},HtmlFormatter.prototype.format_modified=function(t,e){t.out('<div class="jsondiffpatch-value jsondiffpatch-left-value">'),this.formatValue(t,e[0]),t.out('</div><div class="jsondiffpatch-value jsondiffpatch-right-value">'),this.formatValue(t,e[1]),t.out("</div>")},HtmlFormatter.prototype.format_deleted=function(t,e){t.out('<div class="jsondiffpatch-value">'),this.formatValue(t,e[0]),t.out("</div>")},HtmlFormatter.prototype.format_moved=function(t,e){t.out('<div class="jsondiffpatch-value">'),this.formatValue(t,e[0]),t.out('</div><div class="jsondiffpatch-moved-destination">'+e[1]+"</div>"),t.out('<div class="jsondiffpatch-arrow" style="position: relative; left: -34px;"> <svg width="30" height="60" style="position: absolute; display: none;"> <defs> <marker id="markerArrow" markerWidth="8" markerHeight="8" refx="2" refy="4" orient="auto" markerUnits="userSpaceOnUse"> <path d="M1,1 L1,7 L7,4 L1,1" style="fill: #339;" /> </marker> </defs> <path d="M30,0 Q-10,25 26,50" style="stroke: #88f; stroke-width: 2px; fill: none; stroke-opacity: 0.5; marker-end: url(#markerArrow);"></path> </svg> </div>'),t.hasArrows=!0},HtmlFormatter.prototype.format_textdiff=function(t,e){t.out('<div class="jsondiffpatch-value">'),this.formatTextDiffString(t,e[0]),t.out("</div>")};var showUnchanged=function(t,e,o){var r=e||document.body,a="jsondiffpatch-unchanged-",i={showing:a+"showing",hiding:a+"hiding",visible:a+"visible",hidden:a+"hidden"},n=r.classList;if(n){if(!o)return n.remove(i.showing),n.remove(i.hiding),n.remove(i.visible),n.remove(i.hidden),void(t===!1&&n.add(i.hidden));t===!1?(n.remove(i.showing),n.add(i.visible),setTimeout(function(){n.add(i.hiding)},10)):(n.remove(i.hiding),n.add(i.showing),n.remove(i.hidden));var s=setInterval(function(){adjustArrows(r)},100);setTimeout(function(){n.remove(i.showing),n.remove(i.hiding),t===!1?(n.add(i.hidden),n.remove(i.visible)):(n.add(i.visible),n.remove(i.hidden)),setTimeout(function(){n.remove(i.visible),clearInterval(s)},o+400)},o)}},hideUnchanged=function(t,e){return showUnchanged(!1,t,e)};exports.HtmlFormatter=HtmlFormatter,exports.showUnchanged=showUnchanged,exports.hideUnchanged=hideUnchanged;var defaultInstance;exports.format=function(t,e){return defaultInstance||(defaultInstance=new HtmlFormatter),defaultInstance.format(t,e)};
},{"./base":4}],6:[function(require,module,exports){
var environment=require("../environment");if(exports.base=require("./base"),exports.html=require("./html"),exports.annotated=require("./annotated"),!environment.isBrowser){var consoleModuleName="./console";exports.console=require(consoleModuleName)}
},{"../environment":2,"./annotated":3,"./base":4,"./html":5}]},{},[1])(1)
});
//# sourceMappingURL=jsondiffpatch-formatters.min.map | Amomo/cdnjs | ajax/libs/jsondiffpatch/0.1.36/jsondiffpatch-formatters.min.js | JavaScript | mit | 14,692 |
/**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @emails sema@fb.com
*/
/*jshint evil:true*/
require('mock-modules').autoMockOff();
describe('es7-spread-property-visitors', function() {
var transformFn;
var originalAssign = Object.assign;
var visitors;
// These are placeholder variables in scope that we can use to assert that a
// specific variable reference was passed, rather than an object clone of it.
var x = 123456;
var y = 789012;
var z = 345678;
beforeEach(function() {
require('mock-modules').dumpCache();
transformFn = require('../../src/jstransform').transform;
visitors = require('../es7-spread-property-visitors').visitorList;
});
function transform(code) {
return transformFn(visitors, code).code;
}
function expectTransform(code, result) {
expect(transform(code)).toEqual(result);
}
function expectObjectAssign(code) {
var objectAssignMock = jest.genMockFunction();
Object.assign = objectAssignMock;
eval(transform(code));
return expect(objectAssignMock);
}
afterEach(function() {
Object.assign = originalAssign;
});
// Polyfill sanity checks
it('has access to a working Object.assign implementation', function() {
expect(typeof Object.assign).toBe('function');
expect(Object.assign({ b: 2 }, null, { a: 1 })).toEqual({ a: 1, b: 2 });
});
// Semantic tests.
it('uses Object.assign with an empty new target object', function() {
expectObjectAssign(
'var xy = { ...x, y: 2 }'
).toBeCalledWith({}, x, { y: 2 });
});
it('coalesces consecutive properties into a single object', function() {
expectObjectAssign(
'var xyz = { ...x, y: 2, z: z }'
).toBeCalledWith({}, x, { y: 2, z: z });
});
it('avoids an unnecessary empty object when spread is not first', function() {
expectObjectAssign(
'var xy = { x: 1, ...y }'
).toBeCalledWith({ x: 1}, y);
});
it('passes the same value multiple times to Object.assign', function() {
expectObjectAssign(
'var xyz = { x: 1, y: 2, ...z, ...z }'
).toBeCalledWith({ x: 1, y: 2}, z, z);
});
it('keeps object literals as separate arguments to assign', function() {
expectObjectAssign(
'var xyz = { x: 1, ...({ y: 2 }), z: 3 }'
).toBeCalledWith({ x: 1}, { y: 2 }, {z: 3 });
});
it('does not call assign when there are no spread properties', function() {
expectObjectAssign(
'var xy = { x: 1, y: 2 }'
).not.toBeCalled();
});
// Syntax tests.
it('should preserve extra whitespace', function() {
expectTransform(
'let xyz = { x: 1, y : \n 2, ... \nz, ... z }',
'let xyz = Object.assign({ x: 1, y : \n 2}, \nz, z )'
);
});
it('should preserve parenthesis', function() {
expectTransform(
'let xyz = { x: 1, ...({ y: 2 }), z: 3 }',
'let xyz = Object.assign({ x: 1}, ({ y: 2 }), {z: 3 })'
);
});
it('should remove trailing commas after properties', function() {
expectTransform(
'let xyz = { ...x, y: 1, }',
'let xyz = Object.assign({}, x, {y: 1 })'
);
});
it('should remove trailing commas after spread', function() {
expectTransform(
'let xyz = { x: 1, ...y, }',
'let xyz = Object.assign({ x: 1}, y )'
);
});
// Don't transform
it('should not transform destructuring assignment', function() {
expectTransform(
'let { x, ...y } = z',
'let { x, ...y } = z'
);
});
// Accessors are unsupported. We leave it unprocessed so that other,
// chained transforms, can take over.
it('should not transform when there are getters', function() {
expectTransform(
'let xy = { ...x, get x() { } }',
'let xy = { ...x, get x() { } }'
);
});
it('should not transform when there are setters', function() {
expectTransform(
'let xy = { set x(v) { }, ...y }',
'let xy = { set x(v) { }, ...y }'
);
});
it('should silently ignore falsy values', function() {
/*globals obj*/
var code = transform([
'var x = null;',
'var y = { y: "y" };',
'var obj = { ...x, ...y, ...{ ...false, z: "z", ...y } };'
].join('\n'));
eval(code);
expect(obj).toEqual({ y: 'y', z: 'z' });
});
});
| NickingMeSpace/questionnaire | node_modules/jstransform/visitors/__tests__/es7-spread-property-visitors-test.js | JavaScript | mit | 4,505 |
/*!
* @author Sean Coker <sean@seancoker.com>
* @version 1.5.1
* @url http://sean.is/poppin/tags
* @license MIT
* @description Taggle is a dependency-less tagging library
*/
(function(e,t){function n(){if(!(2>arguments.length)){for(var e=arguments[0],t=1,n=arguments.length;n>t;t++){var a=arguments[t];for(var l in a)a.hasOwnProperty(l)&&(e[l]=a[l])}return e}}function a(e){return Array.isArray?Array.isArray(e):"[object Array]"===Object.prototype.toString.call(e)}function l(e,t){var n="a"===e.tagName.toLowerCase()?e.parentNode:e,a=t.elements.indexOf(n);t.elements.splice(a,1),t.values.splice(a,1)}function s(e,t,n){e.addEventListener?e.addEventListener(t,n,!1):e.attachEvent?e.attachEvent("on"+t,n):e["on"+t]=n}function i(e){return e.replace(/^\s+|\s+$/g,"")}function r(t,n){e.attachEvent&&!e.addEventListener?t.innerText=n:t.textContent=n}var o={additionalTagClasses:"",allowDuplicates:!1,duplicateTagClass:"",containerFocusClass:"active",hiddenInputName:"taggles[]",tags:[],allowedTags:[],tabIndex:1,placeholder:"Enter tags...",submitKeys:[],preserveCase:!1,onTagAdd:function(){},onTagRemove:function(){}},c=8,u=188,d=9,g=13,p=function(p,f){function v(){h(),m(),y()}function h(){var t,n,a;D.container.rect=K.getBoundingClientRect(),D.container.style=e.getComputedStyle(K),t=D.container.style,n=parseInt(t["padding-left"]||t.paddingLeft,10),a=parseInt(t["padding-right"]||t.paddingRight,10),D.container.padding=n+a}function m(){var t;if(V.className="taggle_list",M.type="text",M.className="taggle_input",M.tabIndex=z.tabIndex,P.className="taggle_sizer",z.tags.length)for(var n=0,a=z.tags.length;a>n;n++){var l=O(z.tags[n]);V.appendChild(l)}B&&(B.style.opacity=0,B.classList.add("taggle_placeholder"),K.appendChild(B),r(B,z.placeholder),z.tags.length||(B.style.opacity=1)),H.appendChild(M),V.appendChild(H),K.appendChild(V),K.appendChild(P),t=e.getComputedStyle(M).fontSize,P.style.fontSize=t}function y(){s(K,"click",function(){M.focus()}),M.onfocus=N,M.onblur=I,s(M,"keydown",S),s(M,"keyup",_)}function C(){var e,t,n,a,l;E(),t=M.getBoundingClientRect(),n=D.container.rect,e=~~n.width,e||(e=~~n.right-~~n.left),a=~~t.left-~~n.left,l=D.container.padding,E(e-a-l)}function L(e){return e?!z.allowDuplicates&&x(e)?!1:z.allowedTags.length&&-1===z.allowedTags.indexOf(e)?!1:!0:!1}function T(e,t){var n,a,l,s=q("string"==typeof t?t:i(M.value));L(s)&&(n=O(s),a=V.querySelectorAll("li"),l=a[a.length-1],V.insertBefore(n,l),z.onTagAdd(e,s),M.value="",E(),C(),N())}function w(t){t=t||e.event;var n=K.querySelectorAll(".taggle"),a=n[n.length-1],l="taggle_hot",s=M.classList.contains("taggle_back");""!==M.value||t.keyCode!==c||s?a.classList.contains(l)&&a.classList.remove(l):a.classList.contains(l)?(M.classList.add("taggle_back"),R(a,t),C(),N()):a.classList.add(l)}function E(e){M.style.width=(e||10)+"px"}function x(e){var t,n=j.values.indexOf(e),a=K.querySelector(".taggle_list");if(z.duplicateTagClass){t=a.querySelectorAll("."+z.duplicateTagClass);for(var l=0,s=t.length;s>l;l++)t[l].classList.remove(z.duplicateTagClass)}return n>-1?(z.duplicateTagClass&&a.childNodes[n].classList.add(z.duplicateTagClass),!0):!1}function b(e){var t=!1;return z.submitKeys.indexOf(e)>-1&&(t=!0),t}function N(){C(),K.classList.contains(z.containerFocusClass)||K.classList.add(z.containerFocusClass),B&&(B.style.opacity=0)}function I(){M.value="",E(),K.classList.contains(z.containerFocusClass)&&K.classList.remove(z.containerFocusClass),!j.values.length&&B&&(B.style.opacity=1)}function S(t){t=t||e.event;var n=t.keyCode;return k(),b(n)&&""!==M.value?(A(t),undefined):(j.values.length&&w(t),undefined)}function _(t){t=t||e.event,M.classList.remove("taggle_back"),r(P,M.value)}function A(t){t=t||e.event,T(t),t.preventDefault?t.preventDefault():t.returnValue=!1}function k(){var e=P.getBoundingClientRect().width,t=D.container.rect.width-D.container.padding,n=parseInt(P.style.fontSize,10);e+1.5*n>parseInt(M.style.width,10)&&(M.style.width=t+"px")}function O(e){var n=t.createElement("li"),a=t.createElement("a"),l=t.createElement("input"),s=t.createElement("span");return e=q(e),a.href="javascript:void(0)",a.innerHTML="×",a.className="close",a.onclick=R.bind(null,a),r(s,e),s.className="taggle_text",n.className="taggle "+z.additionalTagClasses,l.type="hidden",l.value=e,l.name=z.hiddenInputName,n.appendChild(s),n.appendChild(a),n.appendChild(l),j.values.push(e),j.elements.push(n),n}function R(e,t){var n,a;"li"!==e.tagName.toLowerCase()&&(e=e.parentNode),n=e.querySelector(".taggle_text"),a=n.innerText||n.textContent,e.parentNode.removeChild(e),l(e,j),z.onTagRemove(t,a),N()}function q(e){return z.preserveCase?e:e.toLowerCase()}var B,F=this,z=n({},o,f),D={container:{rect:null,style:null,padding:null}},K=p,j={values:[],elements:[]},V=t.createElement("ul"),H=t.createElement("li"),M=t.createElement("input"),P=t.createElement("div");z.placeholder&&(B=t.createElement("span")),z.submitKeys.length||(z.submitKeys=[u,d,g]),"string"==typeof p&&(K=t.getElementById(p)),F.getTags=function(){return j},F.getTagElements=function(){return j.elements},F.getTagValues=function(){return j.values},F.getInput=function(){return M},F.getContainer=function(){return K},F.add=function(e){var t=a(e);if("string"==typeof e)return T(null,e);if(t)for(var n=0,l=e.length;l>n;n++)"string"==typeof e[n]&&T(null,e[n]);return F},F.remove=function(e,t){for(var n=j.values.length-1,a=!1;n>-1&&(j.values[n]===e&&(a=!0,R(j.elements[n])),!a||t);)n--;return F},v()};e.Taggle=p})(window,document); | sufuf3/cdnjs | ajax/libs/taggle/1.6.2/taggle.min.js | JavaScript | mit | 5,458 |
/*
* jcinit.c
*
* Copyright (C) 1991-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains initialization logic for the JPEG compressor.
* This routine is in charge of selecting the modules to be executed and
* making an initialization call to each one.
*
* Logically, this code belongs in jcmaster.c. It's split out because
* linking this routine implies linking the entire compression library.
* For a transcoding-only application, we want to be able to use jcmaster.c
* without linking in the whole library.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/*
* Master selection of compression modules.
* This is done once at the start of processing an image. We determine
* which modules will be used and give them appropriate initialization calls.
*/
GLOBAL(void)
jinit_compress_master (j_compress_ptr cinfo)
{
/* Initialize master control (includes parameter checking/processing) */
jinit_c_master_control(cinfo, FALSE /* full compression */);
/* Preprocessing */
if (! cinfo->raw_data_in) {
jinit_color_converter(cinfo);
jinit_downsampler(cinfo);
jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
}
/* Forward DCT */
jinit_forward_dct(cinfo);
/* Entropy encoding: either Huffman or arithmetic coding. */
if (cinfo->arith_code) {
ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
} else {
if (cinfo->progressive_mode) {
#ifdef C_PROGRESSIVE_SUPPORTED
jinit_phuff_encoder(cinfo);
#else
ERREXIT(cinfo, JERR_NOT_COMPILED);
#endif
} else
jinit_huff_encoder(cinfo);
}
/* Need a full-image coefficient buffer in any multi-pass mode. */
jinit_c_coef_controller(cinfo,
(boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
jinit_marker_writer(cinfo);
/* We can now tell the memory manager to allocate virtual arrays. */
(*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
/* Write the datastream header (SOI) immediately.
* Frame and scan headers are postponed till later.
* This lets application insert special markers after the SOI.
*/
(*cinfo->marker->write_file_header) (cinfo);
}
| jeremywrnr/life-of-the-party | SensorKinect-unstable/Source/External/LibJPEG/jcinit.c | C | mit | 2,421 |
var isLength = require('../internal/isLength'),
isObjectLike = require('../internal/isObjectLike');
/** `Object#toString` result references. */
var argsTag = '[object Arguments]';
/** Used for native method references. */
var objectProto = Object.prototype;
/**
* Used to resolve the `toStringTag` of values.
* See the [ES spec](https://people.mozilla.org/~jorendorff/es6-draft.html#sec-object.prototype.tostring)
* for more details.
*/
var objToString = objectProto.toString;
/**
* Checks if `value` is classified as an `arguments` object.
*
* @static
* @memberOf _
* @category Lang
* @param {*} value The value to check.
* @returns {boolean} Returns `true` if `value` is correctly classified, else `false`.
* @example
*
* _.isArguments(function() { return arguments; }());
* // => true
*
* _.isArguments([1, 2, 3]);
* // => false
*/
function isArguments(value) {
var length = isObjectLike(value) ? value.length : undefined;
return (isLength(length) && objToString.call(value) == argsTag) || false;
}
module.exports = isArguments;
| devsalman/id-laravel.github.io | node_modules/gulp-less/node_modules/accord/node_modules/lodash/lang/isArguments.js | JavaScript | mit | 1,064 |
<!DOCTYPE html>
<!--[if lt IE 7 ]><html class="ie ie6" lang="en"> <![endif]-->
<!--[if IE 7 ]><html class="ie ie7" lang="en"> <![endif]-->
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><!-->
<html lang="en" xmlns="http://www.w3.org/1999/html"> <!--<![endif]-->
<head>
<!-- Basic Page Needs
================================================== -->
<meta charset="utf-8" />
<title>icon-off: Font Awesome Icons</title>
<meta name="description" content="Font Awesome, the iconic font designed for Bootstrap">
<meta name="author" content="Dave Gandy">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!--<meta name="viewport" content="initial-scale=1; maximum-scale=1">-->
<!--[if lt IE 9]>
<script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<!-- CSS
================================================== -->
<link rel="stylesheet" href="../../assets/css/site.css">
<link rel="stylesheet" href="../../assets/css/pygments.css">
<link rel="stylesheet" href="../../assets/font-awesome/css/font-awesome.css">
<!--[if IE 7]>
<link rel="stylesheet" href="../../assets/font-awesome/css/font-awesome-ie7.css">
<![endif]-->
<!-- Le fav and touch icons -->
<link rel="shortcut icon" href="../../assets/ico/favicon.ico">
<script type="text/javascript" src="//use.typekit.net/wnc7ioh.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-30136587-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body data-spy="scroll" data-target=".navbar">
<div class="wrapper"> <!-- necessary for sticky footer. wrap all content except footer -->
<div class="navbar navbar-inverse navbar-static-top hidden-print">
<div class="navbar-inner">
<div class="container">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="../../"><i class="icon-flag"></i> Font Awesome</a>
<div class="nav-collapse collapse">
<ul class="nav">
<li class="hidden-tablet "><a href="../../">Home</a></li>
<li><a href="../../get-started/">Get Started</a></li>
<li class="dropdown-split-left"><a href="../../icons/">Icons</a></li>
<li class="dropdown dropdown-split-right hidden-phone">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-caret-down"></i>
</a>
<ul class="dropdown-menu pull-right">
<li><a href="../../icons/"><i class="icon-flag icon-fixed-width"></i> Icons</a></li>
<li class="divider"></li>
<li><a href="../../icons/#new"><i class="icon-shield icon-fixed-width"></i> New Icons in 3.2.1</a></li>
<li><a href="../../icons/#web-application"><i class="icon-camera-retro icon-fixed-width"></i> Web Application Icons</a></li>
<li><a href="../../icons/#currency"><i class="icon-won icon-fixed-width"></i> Currency Icons</a></li>
<li><a href="../../icons/#text-editor"><i class="icon-file-text-alt icon-fixed-width"></i> Text Editor Icons</a></li>
<li><a href="../../icons/#directional"><i class="icon-hand-right icon-fixed-width"></i> Directional Icons</a></li>
<li><a href="../../icons/#video-player"><i class="icon-play-sign icon-fixed-width"></i> Video Player Icons</a></li>
<li><a href="../../icons/#brand"><i class="icon-github icon-fixed-width"></i> Brand Icons</a></li>
<li><a href="../../icons/#medical"><i class="icon-medkit icon-fixed-width"></i> Medical Icons</a></li>
</ul>
</li>
<li class="dropdown-split-left"><a href="../../examples/">Examples</a></li>
<li class="dropdown dropdown-split-right hidden-phone">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
<i class="icon-caret-down"></i>
</a>
<ul class="dropdown-menu pull-right">
<li><a href="../../examples/">Examples</a></li>
<li class="divider"></li>
<li><a href="../../examples/#new-styles">New Styles</a></li>
<li><a href="../../examples/#inline-icons">Inline Icons</a></li>
<li><a href="../../examples/#larger-icons">Larger Icons</a></li>
<li><a href="../../examples/#bordered-pulled">Bordered & Pulled</a></li>
<li><a href="../../examples/#buttons">Buttons</a></li>
<li><a href="../../examples/#button-groups">Button Groups</a></li>
<li><a href="../../examples/#button-dropdowns">Button Dropdowns</a></li>
<li><a href="../../examples/#bulleted-lists">Bulleted Lists</a></li>
<li><a href="../../examples/#navigation">Navigation</a></li>
<li><a href="../../examples/#form-inputs">Form Inputs</a></li>
<li><a href="../../examples/#animated-spinner">Animated Spinner</a></li>
<li><a href="../../examples/#rotated-flipped">Rotated & Flipped</a></li>
<li><a href="../../examples/#stacked">Stacked</a></li>
<li><a href="../../examples/#custom">Custom CSS</a></li>
</ul>
</li>
<li><a href="../../whats-new/">
<span class="hidden-tablet">What's </span>New</a>
</li>
<li><a href="../../community/">Community</a></li>
<li><a href="../../license/">License</a></li>
</ul>
<ul class="nav pull-right">
<li><a href="http://blog.fontawesome.io">Blog</a></li>
</ul>
</div>
</div>
</div>
</div>
<div class="jumbotron jumbotron-icon">
<div class="container">
<div class="info-icons">
<i class="icon-off icon-6"></i>
<span class="hidden-phone">
<i class="icon-off icon-5"></i>
<span class="hidden-tablet"><i class="icon-off icon-4"></i> </span>
<i class="icon-off icon-3"></i>
<i class="icon-off icon-2"></i>
</span>
<i class="icon-off icon-1"></i>
</div>
<h1 class="info-class">
icon-off
<small>
<i class="icon-off"></i> ·
Unicode: <span class="upper">f011</span> ·
Created: v1.0 ·
Categories:
Web Application Icons
· Aliases:
icon-power-off
</small>
</h1>
</div>
</div>
<div class="container">
<section>
<div class="row-fluid">
<div class="span9">
<p>After you get <a href="../../integration/">up and running</a>, you can place Font Awesome icons just about anywhere with the <code><i></code> tag:</p>
<div class="well well-transparent">
<div style="font-size: 24px; line-height: 1.5em;">
<i class="icon-off"></i> icon-off
</div>
</div>
<div class="highlight"><pre><code class="html"><span class="nt"><i</span> <span class="na">class=</span><span class="s">"icon-off"</span><span class="nt">></i></span> icon-off
</code></pre></div>
<br>
<div class="lead"><i class="icon-info-sign"></i> Looking for more? Check out the <a href="../../examples/">examples</a>.</div>
</div>
<div class="span3">
<div class="info-ad"><div id="carbonads-container"><div class="carbonad"><div id="azcarbon"></div><script type="text/javascript">var z = document.createElement("script"); z.type = "text/javascript"; z.async = true; z.src = "http://engine.carbonads.com/z/32291/azcarbon_2_1_0_VERT"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(z, s);</script></div></div>
</div>
</div>
</div>
</section>
</div>
<div class="push"><!-- necessary for sticky footer --></div>
</div>
<footer class="footer hidden-print">
<div class="container text-center">
<div>
<i class="icon-flag"></i> Font Awesome 3.2.1
<span class="hidden-phone">·</span><br class="visible-phone">
Created and Maintained by <a href="http://twitter.com/davegandy">Dave Gandy</a>
</div>
<div>
Font Awesome licensed under <a href="http://scripts.sil.org/OFL">SIL OFL 1.1</a>
<span class="hidden-phone">·</span><br class="visible-phone">
Code licensed under <a href="http://opensource.org/licenses/mit-license.html">MIT License</a>
<span class="hidden-phone hidden-tablet">·</span><br class="visible-phone visible-tablet">
Documentation licensed under <a href="http://creativecommons.org/licenses/by/3.0/">CC BY 3.0</a>
</div>
<div>
Thanks to <a href="http://maxcdn.com"><i class="icon-maxcdn"></i> MaxCDN</a> for providing the excellent <a href="http://www.bootstrapcdn.com/#tab_fontawesome">BootstrapCDN for Font Awesome</a>
</div>
<div class="project">
<a href="https://github.com/FortAwesome/Font-Awesome">GitHub Project</a> ·
<a href="https://github.com/FortAwesome/Font-Awesome/issues">Issues</a>
</div>
</div>
</footer>
<script src="http://platform.twitter.com/widgets.js"></script>
<script src="../../assets/js/jquery-1.7.1.min.js"></script>
<script src="../../assets/js/ZeroClipboard-1.1.7.min.js"></script>
<script src="../../assets/js/bootstrap-2.3.1.min.js"></script>
<script src="../../assets/js/site.js"></script>
</body>
</html>
| abax-quicklog/bootswatch | bower_components/font-awesome/src/3.2.1/icon/off/index.html | HTML | mit | 10,103 |
(function($){
var webshims = window.webshims;
setTimeout(function(){
webshims.isReady('geolocation', true);
});
var domWrite = function(){
setTimeout(function(){
throw('document.write is overwritten by geolocation shim. This method is incompatible with this plugin');
}, 1);
},
id = 0
;
var geoOpts = webshims.cfg.geolocation || {};
if(!navigator.geolocation){
navigator.geolocation = {};
}
$.extend(navigator.geolocation, (function(){
var pos;
var api = {
getCurrentPosition: function(success, error, opts){
var locationAPIs = 2,
errorTimer,
googleTimer,
calledEnd,
createAjax,
endCallback = function(){
if(calledEnd){return;}
if(pos){
calledEnd = true;
success($.extend({timestamp: new Date().getTime()}, pos));
resetCallback();
if(window.JSON && window.sessionStorage){
try{
sessionStorage.setItem('storedGeolocationData654321', JSON.stringify(pos));
} catch(e){}
}
} else if(error && !locationAPIs) {
calledEnd = true;
resetCallback();
error({ code: 2, message: "POSITION_UNAVAILABLE"});
}
},
googleCallback = function(){
locationAPIs--;
getGoogleCoords();
endCallback();
},
resetCallback = function(){
$(document).off('google-loader', resetCallback);
clearTimeout(googleTimer);
clearTimeout(errorTimer);
},
getGoogleCoords = function(){
if(pos || !window.google || !google.loader || !google.loader.ClientLocation){return false;}
var cl = google.loader.ClientLocation;
pos = {
coords: {
latitude: cl.latitude,
longitude: cl.longitude,
altitude: null,
accuracy: 43000,
altitudeAccuracy: null,
heading: parseInt('NaN', 10),
velocity: null
},
//extension similiar to FF implementation
address: $.extend({streetNumber: '', street: '', premises: '', county: '', postalCode: ''}, cl.address)
};
return true;
},
getInitCoords = function(){
if(pos){return;}
getGoogleCoords();
if(pos || !window.JSON || !window.sessionStorage){return;}
try{
pos = sessionStorage.getItem('storedGeolocationData654321');
pos = (pos) ? JSON.parse(pos) : false;
if(!pos.coords){pos = false;}
} catch(e){
pos = false;
}
}
;
getInitCoords();
if(!pos){
if(geoOpts.confirmText && !confirm(geoOpts.confirmText.replace('{location}', location.hostname))){
if(error){
error({ code: 1, message: "PERMISSION_DENIED"});
}
return;
}
$.ajax({
url: 'http://freegeoip.net/json/',
dataType: 'jsonp',
cache: true,
jsonp: 'callback',
success: function(data){
locationAPIs--;
if(!data){return;}
pos = pos || {
coords: {
latitude: data.latitude,
longitude: data.longitude,
altitude: null,
accuracy: 43000,
altitudeAccuracy: null,
heading: parseInt('NaN', 10),
velocity: null
},
//extension similiar to FF implementation
address: {
city: data.city,
country: data.country_name,
countryCode: data.country_code,
county: "",
postalCode: data.zipcode,
premises: "",
region: data.region_name,
street: "",
streetNumber: ""
}
};
endCallback();
},
error: function(){
locationAPIs--;
endCallback();
}
});
clearTimeout(googleTimer);
if (!window.google || !window.google.loader) {
googleTimer = setTimeout(function(){
//destroys document.write!!!
if (geoOpts.destroyWrite) {
document.write = domWrite;
document.writeln = domWrite;
}
$(document).one('google-loader', googleCallback);
webshims.loader.loadScript('http://www.google.com/jsapi', false, 'google-loader');
}, 800);
} else {
locationAPIs--;
}
} else {
setTimeout(endCallback, 1);
return;
}
if(opts && opts.timeout){
errorTimer = setTimeout(function(){
resetCallback();
if(error) {
error({ code: 3, message: "TIMEOUT"});
}
}, opts.timeout);
} else {
errorTimer = setTimeout(function(){
locationAPIs = 0;
endCallback();
}, 10000);
}
},
clearWatch: $.noop
};
api.watchPosition = function(a, b, c){
api.getCurrentPosition(a, b, c);
id++;
return id;
};
return api;
})());
webshims.isReady('geolocation', true);
})(webshims.$);
;webshims.register('details', function($, webshims, window, doc, undefined, options){
var isInterActiveSummary = function(summary){
var details = $(summary).parent('details');
if(details[0] && details.children(':first').get(0) === summary){
return details;
}
};
var bindDetailsSummary = function(summary, details){
summary = $(summary);
details = $(details);
var oldSummary = $.data(details[0], 'summaryElement');
$.data(summary[0], 'detailsElement', details);
if(!oldSummary || summary[0] !== oldSummary[0]){
if(oldSummary){
if(oldSummary.hasClass('fallback-summary')){
oldSummary.remove();
} else {
oldSummary
.off('.summaryPolyfill')
.removeData('detailsElement')
.removeAttr('role')
.removeAttr('tabindex')
.removeAttr('aria-expanded')
.removeClass('summary-button')
.find('span.details-open-indicator')
.remove()
;
}
}
$.data(details[0], 'summaryElement', summary);
details.prop('open', details.prop('open'));
}
};
var getSummary = function(details){
var summary = $.data(details, 'summaryElement');
if(!summary){
summary = $(details).children('summary:first-child');
if(!summary[0]){
$(details).prependPolyfill('<summary class="fallback-summary">'+ options.text +'</summary>');
summary = $.data(details, 'summaryElement');
} else {
bindDetailsSummary(summary, details);
}
}
return summary;
};
// var isOriginalPrevented = function(e){
// var src = e.originalEvent;
// if(!src){return e.isDefaultPrevented();}
//
// return src.defaultPrevented || src.returnValue === false ||
// src.getPreventDefault && src.getPreventDefault();
// };
webshims.createElement('summary', function(){
var details = isInterActiveSummary(this);
if(!details || $.data(this, 'detailsElement')){return;}
var timer;
var stopNativeClickTest;
var tabindex = $.attr(this, 'tabIndex') || '0';
bindDetailsSummary(this, details);
$(this)
.on({
'focus.summaryPolyfill': function(){
$(this).addClass('summary-has-focus');
},
'blur.summaryPolyfill': function(){
$(this).removeClass('summary-has-focus');
},
'mouseenter.summaryPolyfill': function(){
$(this).addClass('summary-has-hover');
},
'mouseleave.summaryPolyfill': function(){
$(this).removeClass('summary-has-hover');
},
'click.summaryPolyfill': function(e){
var details = isInterActiveSummary(this);
if(details){
if(!stopNativeClickTest && e.originalEvent){
stopNativeClickTest = true;
e.stopImmediatePropagation();
e.preventDefault();
$(this).trigger('click');
stopNativeClickTest = false;
return false;
} else {
clearTimeout(timer);
timer = setTimeout(function(){
if(!e.isDefaultPrevented()){
details.prop('open', !details.prop('open'));
}
}, 0);
}
}
},
'keydown.summaryPolyfill': function(e){
if( (e.keyCode == 13 || e.keyCode == 32) && !e.isDefaultPrevented()){
stopNativeClickTest = true;
e.preventDefault();
$(this).trigger('click');
stopNativeClickTest = false;
}
}
})
.attr({tabindex: tabindex, role: 'button'})
.prepend('<span class="details-open-indicator" />')
;
webshims.moveToFirstEvent(this, 'click');
});
var initDetails;
webshims.defineNodeNamesBooleanProperty('details', 'open', function(val){
var summary = $($.data(this, 'summaryElement'));
if(!summary){return;}
var action = (val) ? 'removeClass' : 'addClass';
var details = $(this);
if (!initDetails && options.animate){
details.stop().css({width: '', height: ''});
var start = {
width: details.width(),
height: details.height()
};
}
summary.attr('aria-expanded', ''+val);
details[action]('closed-details-summary').children().not(summary[0])[action]('closed-details-child');
if(!initDetails && options.animate){
var end = {
width: details.width(),
height: details.height()
};
details.css(start).animate(end, {
complete: function(){
$(this).css({width: '', height: ''});
}
});
}
});
webshims.createElement('details', function(){
initDetails = true;
var summary = getSummary(this);
$.prop(this, 'open', $.prop(this, 'open'));
initDetails = false;
});
});
;webshims.register('mediaelement-jaris', function($, webshims, window, document, undefined, options){
"use strict";
var mediaelement = webshims.mediaelement;
var swfmini = window.swfmini;
var support = webshims.support;
var hasNative = support.mediaelement;
var hasFlash = swfmini.hasFlashPlayerVersion('11.3');
var loadedSwf = 0;
var needsLoadPreload = 'ActiveXObject' in window && hasNative;
var getProps = {
paused: true,
ended: false,
currentSrc: '',
duration: window.NaN,
readyState: 0,
networkState: 0,
videoHeight: 0,
videoWidth: 0,
seeking: false,
error: null,
buffered: {
start: function(index){
if(index){
webshims.error('buffered index size error');
return;
}
return 0;
},
end: function(index){
if(index){
webshims.error('buffered index size error');
return;
}
return 0;
},
length: 0
}
};
var getPropKeys = Object.keys(getProps);
var getSetProps = {
currentTime: 0,
volume: 1,
muted: false
};
var getSetPropKeys = Object.keys(getSetProps);
var playerStateObj = $.extend({
isActive: 'html5',
activating: 'html5',
wasSwfReady: false,
_usermedia: null,
_bufferedEnd: 0,
_bufferedStart: 0,
currentTime: 0,
lastCalledTime: -500,
_ppFlag: undefined,
_calledMeta: false,
lastDuration: 0,
_timeDif: 0.3
}, getProps, getSetProps);
var getSwfDataFromElem = function(elem){
try {
(elem.nodeName);
} catch(er){
return null;
}
var data = webshims.data(elem, 'mediaelement');
return (data && data.isActive == 'third') ? data : null;
};
var trigger = function(elem, evt){
evt = $.Event(evt);
evt.preventDefault();
$.event.trigger(evt, undefined, elem);
};
var playerSwfPath = options.playerPath || webshims.cfg.basePath + "swf/" + (options.playerName || 'JarisFLVPlayer.swf');
webshims.extendUNDEFProp(options.params, {
allowscriptaccess: 'always',
allowfullscreen: 'true',
wmode: 'transparent',
allowNetworking: 'all'
});
webshims.extendUNDEFProp(options.vars, {
controltype: '1',
jsapi: '1'
});
webshims.extendUNDEFProp(options.attrs, {
bgcolor: '#000000'
});
options.playerPath = playerSwfPath;
var setReadyState = function(readyState, data){
if(readyState < 3){
clearTimeout(data._canplaythroughTimer);
}
if(readyState >= 3 && data.readyState < 3){
data.readyState = readyState;
trigger(data._elem, 'canplay');
if(!data.paused){
trigger(data._elem, 'playing');
}
clearTimeout(data._canplaythroughTimer);
data._canplaythroughTimer = setTimeout(function(){
setReadyState(4, data);
}, 4000);
}
if(readyState >= 4 && data.readyState < 4){
data.readyState = readyState;
trigger(data._elem, 'canplaythrough');
}
data.readyState = readyState;
};
var callSeeked = function(data){
if(data.seeking && Math.abs(data.currentTime - data._lastSeektime) < 2){
data.seeking = false;
$(data._elem).triggerHandler('seeked');
}
};
mediaelement.jarisEvent = mediaelement.jarisEvent || {};
var localConnectionTimer;
var onEvent = {
onPlayPause: function(jaris, data, override){
var playing, type;
var idled = data.paused || data.ended;
if(override == null){
try {
playing = data.api.api_get("isPlaying");
} catch(e){}
} else {
playing = override;
}
if(playing == idled || playing == null){
data.paused = !playing;
type = data.paused ? 'pause' : 'play';
data._ppFlag = true;
trigger(data._elem, type);
}
if(!data.paused || playing == idled || playing == null){
if(data.readyState < 3){
setReadyState(3, data);
}
}
if(!data.paused){
trigger(data._elem, 'playing');
}
},
onSeek: function(jaris, data){
data._lastSeektime = jaris.seekTime;
data.seeking = true;
$(data._elem).triggerHandler('seeking');
clearTimeout(data._seekedTimer);
data._seekedTimer = setTimeout(function(){
callSeeked(data);
data.seeking = false;
}, 300);
},
onConnectionFailed: function(jaris, data){
mediaelement.setError(data._elem, 'flash connection error');
},
onNotBuffering: function(jaris, data){
setReadyState(3, data);
},
onDataInitialized: function(jaris, data){
var oldDur = data.duration;
var durDelta;
data.duration = jaris.duration;
if(oldDur == data.duration || isNaN(data.duration)){return;}
if(data._calledMeta && ((durDelta = Math.abs(data.lastDuration - data.duration)) < 2)){return;}
data.videoHeight = jaris.height;
data.videoWidth = jaris.width;
if(!data.networkState){
data.networkState = 2;
}
if(data.readyState < 1){
setReadyState(1, data);
}
clearTimeout(data._durationChangeTimer);
if(data._calledMeta && data.duration){
data._durationChangeTimer = setTimeout(function(){
data.lastDuration = data.duration;
trigger(data._elem, 'durationchange');
}, durDelta > 50 ? 0 : durDelta > 9 ? 9 : 99);
} else {
data.lastDuration = data.duration;
if(data.duration){
trigger(data._elem, 'durationchange');
}
if(!data._calledMeta){
trigger(data._elem, 'loadedmetadata');
}
if(data.duration > 1 && data.duration < 140){
data._timeDif = 0.2;
} else if(data.duration < 600) {
data._timeDif = 0.25;
} else {
data._timeDif = 0.30;
}
}
data._calledMeta = true;
},
onBuffering: function(jaris, data){
if(data.ended){
data.ended = false;
}
setReadyState(1, data);
trigger(data._elem, 'waiting');
},
onTimeUpdate: function(jaris, data){
var timeDif = data.currentTime - data.lastCalledTime;
if(data.ended){
data.ended = false;
}
if(data.readyState < 3){
setReadyState(3, data);
trigger(data._elem, 'playing');
}
if(data.seeking){
callSeeked(data);
}
if(timeDif > data._timeDif || timeDif < -0.3){
data.lastCalledTime = data.currentTime;
$.event.trigger('timeupdate', undefined, data._elem, true);
}
},
onProgress: function(jaris, data){
if(data.ended){
data.ended = false;
}
if(!data.duration || isNaN(data.duration)){
return;
}
var percentage = jaris.loaded / jaris.total;
if(percentage > 0.02 && percentage < 0.2){
setReadyState(3, data);
} else if(percentage > 0.2){
if(percentage > 0.95){
percentage = 1;
data.networkState = 1;
}
setReadyState(4, data);
}
if(data._bufferedEnd && (data._bufferedEnd > percentage)){
data._bufferedStart = data.currentTime || 0;
}
data._bufferedEnd = percentage;
data.buffered.length = 1;
$.event.trigger('progress', undefined, data._elem, true);
},
onPlaybackFinished: function(jaris, data){
if(data.readyState < 4){
setReadyState(4, data);
}
data.ended = true;
trigger(data._elem, 'ended');
},
onVolumeChange: function(jaris, data){
if(data.volume != jaris.volume || data.muted != jaris.mute){
data.volume = jaris.volume;
data.muted = jaris.mute;
trigger(data._elem, 'volumechange');
}
},
ready: (function(){
var testAPI = function(data){
var passed = true;
try {
data.api.api_get('volume');
} catch(er){
passed = false;
}
return passed;
};
return function(jaris, data){
var i = 0;
var doneFn = function(){
if(i > 9){
data.tryedReframeing = 0;
return;
}
i++;
data.tryedReframeing++;
if(testAPI(data)){
data.wasSwfReady = true;
data.tryedReframeing = 0;
startAutoPlay(data);
workActionQueue(data);
} else if(data.tryedReframeing < 6) {
if(data.tryedReframeing < 3){
data.reframeTimer = setTimeout(doneFn, 9);
data.shadowElem.css({overflow: 'visible'});
setTimeout(function(){
data.shadowElem.css({overflow: 'hidden'});
}, 1);
} else {
data.shadowElem.css({overflow: 'hidden'});
$(data._elem).mediaLoad();
}
} else {
clearTimeout(data.reframeTimer);
webshims.error("reframing error");
}
};
if(!data || !data.api){return;}
if(!data.tryedReframeing){
data.tryedReframeing = 0;
}
clearTimeout(localConnectionTimer);
clearTimeout(data.reframeTimer);
data.shadowElem.removeClass('flashblocker-assumed');
if(!i){
doneFn();
} else {
data.reframeTimer = setTimeout(doneFn, 9);
}
};
})()
};
onEvent.onMute = onEvent.onVolumeChange;
mediaelement.onEvent = onEvent;
var workActionQueue = function(data){
var actionLen = data.actionQueue.length;
var i = 0;
var operation;
if(actionLen && data.isActive == 'third'){
while(data.actionQueue.length && actionLen > i){
i++;
operation = data.actionQueue.shift();
try{
data.api[operation.fn].apply(data.api, operation.args);
} catch(er){
webshims.warn(er);
}
}
}
if(data.actionQueue.length){
data.actionQueue = [];
}
};
var startAutoPlay = function(data){
if(!data){return;}
if( (data._ppFlag === undefined && ($.prop(data._elem, 'autoplay')) || !data.paused)){
setTimeout(function(){
if(data.isActive == 'third' && (data._ppFlag === undefined || !data.paused)){
try {
$(data._elem).play();
data._ppFlag = true;
} catch(er){}
}
}, 1);
}
if(data.muted){
$.prop(data._elem, 'muted', true);
}
if(data.volume != 1){
$.prop(data._elem, 'volume', data.volume);
}
};
var addMediaToStopEvents = $.noop;
if(hasNative){
var stopEvents = {
play: 1,
playing: 1
};
var hideEvtArray = ['play', 'pause', 'playing', 'loadstart', 'canplay', 'progress', 'waiting', 'ended', 'loadedmetadata', 'durationchange', 'emptied'];
var hidevents = hideEvtArray.map(function(evt){
return evt +'.webshimspolyfill';
}).join(' ');
var hidePlayerEvents = function(event){
var data = webshims.data(event.target, 'mediaelement');
if(!data){return;}
var isNativeHTML5 = ( event.originalEvent && event.originalEvent.type === event.type );
if( isNativeHTML5 == (data.activating == 'third') ){
event.stopImmediatePropagation();
if(stopEvents[event.type]){
if(data.isActive != data.activating){
$(event.target).pause();
} else if(isNativeHTML5){
($.prop(event.target, 'pause')._supvalue || $.noop).apply(event.target);
}
}
}
};
addMediaToStopEvents = function(elem){
$(elem)
.off(hidevents)
.on(hidevents, hidePlayerEvents)
;
hideEvtArray.forEach(function(evt){
webshims.moveToFirstEvent(elem, evt);
});
};
addMediaToStopEvents(document);
}
mediaelement.setActive = function(elem, type, data){
if(!data){
data = webshims.data(elem, 'mediaelement');
}
if(!data || data.isActive == type){return;}
if(type != 'html5' && type != 'third'){
webshims.warn('wrong type for mediaelement activating: '+ type);
}
var shadowData = webshims.data(elem, 'shadowData');
data.activating = type;
$(elem).pause();
data.isActive = type;
if(type == 'third'){
shadowData.shadowElement = shadowData.shadowFocusElement = data.shadowElem[0];
$(elem).addClass('swf-api-active nonnative-api-active').hide().getShadowElement().show();
} else {
$(elem).removeClass('swf-api-active nonnative-api-active').show().getShadowElement().hide();
shadowData.shadowElement = shadowData.shadowFocusElement = false;
}
$(elem).trigger('mediaelementapichange');
};
var resetSwfProps = (function(){
var resetProtoProps = ['_calledMeta', 'lastDuration', '_bufferedEnd', 'lastCalledTime', '_usermedia', '_bufferedStart', '_ppFlag', 'currentSrc', 'currentTime', 'duration', 'ended', 'networkState', 'paused', 'seeking', 'videoHeight', 'videoWidth'];
var len = resetProtoProps.length;
return function(data){
if(!data){return;}
clearTimeout(data._seekedTimer);
var lenI = len;
var networkState = data.networkState;
setReadyState(0, data);
clearTimeout(data._durationChangeTimer);
while(--lenI > -1){
delete data[resetProtoProps[lenI]];
}
data.actionQueue = [];
data.buffered.length = 0;
if(networkState){
trigger(data._elem, 'emptied');
}
};
})();
var getComputedDimension = (function(){
var dimCache = {};
var getVideoDims = function(data){
var ret, poster, img;
if(dimCache[data.currentSrc]){
ret = dimCache[data.currentSrc];
} else if(data.videoHeight && data.videoWidth){
dimCache[data.currentSrc] = {
width: data.videoWidth,
height: data.videoHeight
};
ret = dimCache[data.currentSrc];
} else if((poster = $.attr(data._elem, 'poster'))){
ret = dimCache[poster];
if(!ret){
img = document.createElement('img');
img.onload = function(){
dimCache[poster] = {
width: this.width,
height: this.height
};
if(dimCache[poster].height && dimCache[poster].width){
setElementDimension(data, $.prop(data._elem, 'controls'));
} else {
delete dimCache[poster];
}
img.onload = null;
};
img.src = poster;
if(img.complete && img.onload){
img.onload();
}
}
}
return ret || {width: 300, height: data._elemNodeName == 'video' ? 150 : 50};
};
var getCssStyle = function(elem, style){
return elem.style[style] || (elem.currentStyle && elem.currentStyle[style]) || (window.getComputedStyle && (window.getComputedStyle( elem, null ) || {} )[style]) || '';
};
var minMaxProps = ['minWidth', 'maxWidth', 'minHeight', 'maxHeight'];
var addMinMax = function(elem, ret){
var i, prop;
var hasMinMax = false;
for (i = 0; i < 4; i++) {
prop = getCssStyle(elem, minMaxProps[i]);
if(parseFloat(prop, 10)){
hasMinMax = true;
ret[minMaxProps[i]] = prop;
}
}
return hasMinMax;
};
var retFn = function(data){
var videoDims, ratio;
var elem = data._elem;
var autos = {
width: getCssStyle(elem, 'width') == 'auto',
height: getCssStyle(elem, 'height') == 'auto'
};
var ret = {
width: !autos.width && $(elem).width(),
height: !autos.height && $(elem).height()
};
if(autos.width || autos.height){
videoDims = getVideoDims(data);
ratio = videoDims.width / videoDims.height;
if(autos.width && autos.height){
ret.width = videoDims.width;
ret.height = videoDims.height;
} else if(autos.width){
ret.width = ret.height * ratio;
} else if(autos.height){
ret.height = ret.width / ratio;
}
if(addMinMax(elem, ret)){
data.shadowElem.css(ret);
if(autos.width){
ret.width = data.shadowElem.height() * ratio;
}
if(autos.height){
ret.height = ((autos.width) ? ret.width : data.shadowElem.width()) / ratio;
}
if(autos.width && autos.height){
data.shadowElem.css(ret);
ret.height = data.shadowElem.width() / ratio;
ret.width = ret.height * ratio;
data.shadowElem.css(ret);
ret.width = data.shadowElem.height() * ratio;
ret.height = ret.width / ratio;
}
if(!webshims.support.mediaelement){
ret.width = data.shadowElem.width();
ret.height = data.shadowElem.height();
}
}
}
return ret;
};
return retFn;
})();
var setElementDimension = function(data, hasControls){
var dims;
var box = data.shadowElem;
$(data._elem)[hasControls ? 'addClass' : 'removeClass']('webshims-controls');
if(data.isActive == 'third' || data.activating == 'third'){
if(data._elemNodeName == 'audio' && !hasControls){
box.css({width: 0, height: 0});
} else {
data._elem.style.display = '';
dims = getComputedDimension(data);
data._elem.style.display = 'none';
box.css(dims);
}
}
};
var bufferSrc = (function(){
var preloads = {
'': 1,
'auto': 1
};
return function(elem){
var preload = $.attr(elem, 'preload');
if(preload == null || preload == 'none' || $.prop(elem, 'autoplay')){
return false;
}
preload = $.prop(elem, 'preload');
return !!(preloads[preload] || (preload == 'metadata' && $(elem).is('.preload-in-doubt, video:not([poster])')));
};
})();
var regs = {
A: /&/g,
a: /&/g,
e: /\=/g,
q: /\?/g
},
replaceVar = function(val){
return (val.replace) ? val.replace(regs.A, '%26').replace(regs.a, '%26').replace(regs.e, '%3D').replace(regs.q, '%3F') : val;
};
if('matchMedia' in window){
var allowMediaSorting = false;
try {
allowMediaSorting = window.matchMedia('only all').matches;
} catch(er){}
if(allowMediaSorting){
mediaelement.sortMedia = function(src1, src2){
try {
src1 = !src1.media || matchMedia( src1.media ).matches;
src2 = !src2.media || matchMedia( src2.media ).matches;
} catch(er){
return 0;
}
return src1 == src2 ?
0 :
src1 ? -1
: 1;
};
}
}
mediaelement.resetSwfProps = resetSwfProps;
mediaelement.createSWF = function( elem, canPlaySrc, data ){
if(!hasFlash){
setTimeout(function(){
$(elem).mediaLoad(); //<- this should produce a mediaerror
}, 1);
return;
}
var attrStyle = {};
if(loadedSwf < 1){
loadedSwf = 1;
} else {
loadedSwf++;
}
if(!data){
data = webshims.data(elem, 'mediaelement');
}
if((attrStyle.height = $.attr(elem, 'height') || '') || (attrStyle.width = $.attr(elem, 'width') || '')){
$(elem).css(attrStyle);
webshims.warn("width or height content attributes used. Webshims prefers the usage of CSS (computed styles or inline styles) to detect size of a video/audio. It's really more powerfull.");
}
var box;
var streamRequest = canPlaySrc.streamrequest;
var isStream = canPlaySrc.type == 'jarisplayer/stream';
var hasControls = $.prop(elem, 'controls');
var elemId = 'jarisplayer-'+ webshims.getID(elem);
var elemNodeName = elem.nodeName.toLowerCase();
var setDimension = function(){
if(data.isActive == 'third'){
setElementDimension(data, $.prop(elem, 'controls'));
}
};
if(isStream && !streamRequest){
webshim.usermedia.attach(elem, canPlaySrc, data);
return;
}
if(data && data.swfCreated){
mediaelement.setActive(elem, 'third', data);
data.currentSrc = '';
data.shadowElem.html('<div id="'+ elemId +'">');
data.api = false;
data.actionQueue = [];
box = data.shadowElem;
resetSwfProps(data);
data.currentSrc = canPlaySrc.srcProp;
} else {
$(document.getElementById('wrapper-'+ elemId )).remove();
box = $('<div class="polyfill-'+ (elemNodeName) +' polyfill-mediaelement '+ webshims.shadowClass +'" id="wrapper-'+ elemId +'"><div id="'+ elemId +'"></div>')
.css({
position: 'relative',
overflow: 'hidden'
})
;
data = webshims.data(elem, 'mediaelement', webshims.objectCreate(playerStateObj, {
actionQueue: {
value: []
},
shadowElem: {
value: box
},
_elemNodeName: {
value: elemNodeName
},
_elem: {
value: elem
},
currentSrc: {
value: streamRequest ? '' : canPlaySrc.srcProp
},
swfCreated: {
value: true
},
id: {
value: elemId.replace(/-/g, '')
},
buffered: {
value: {
start: function(index){
if(index >= data.buffered.length){
webshims.error('buffered index size error');
return;
}
return 0;
},
end: function(index){
if(index >= data.buffered.length){
webshims.error('buffered index size error');
return;
}
return ( (data.duration - data._bufferedStart) * data._bufferedEnd) + data._bufferedStart;
},
length: 0
}
}
}));
box.insertBefore(elem);
if(hasNative){
$.extend(data, {volume: $.prop(elem, 'volume'), muted: $.prop(elem, 'muted'), paused: $.prop(elem, 'paused')});
}
webshims.addShadowDom(elem, box);
if(!webshims.data(elem, 'mediaelement')){
webshims.data(elem, 'mediaelement', data);
}
addMediaToStopEvents(elem);
mediaelement.setActive(elem, 'third', data);
setElementDimension(data, hasControls);
$(elem)
.on({
'updatemediaelementdimensions loadedmetadata emptied': setDimension,
'remove': function(e){
if(!e.originalEvent && mediaelement.jarisEvent[data.id] && mediaelement.jarisEvent[data.id].elem == elem){
delete mediaelement.jarisEvent[data.id];
clearTimeout(localConnectionTimer);
clearTimeout(data.flashBlock);
}
}
})
.onWSOff('updateshadowdom', setDimension)
;
}
if(mediaelement.jarisEvent[data.id] && mediaelement.jarisEvent[data.id].elem != elem){
webshims.error('something went wrong');
return;
} else if(!mediaelement.jarisEvent[data.id]){
mediaelement.jarisEvent[data.id] = function(jaris){
if(jaris.type == 'ready'){
var onReady = function(){
if(data.api){
if(!data.paused){
data.api.api_play();
}
if(bufferSrc(elem)){
data.api.api_preload();
}
onEvent.ready(jaris, data);
}
};
if(data.api){
onReady();
} else {
setTimeout(onReady, 9);
}
} else {
data.currentTime = jaris.position;
if(data.api){
if(!data._calledMeta && isNaN(jaris.duration) && data.duration != jaris.duration && isNaN(data.duration)){
onEvent.onDataInitialized(jaris, data);
}
if(!data._ppFlag && jaris.type != 'onPlayPause'){
onEvent.onPlayPause(jaris, data);
}
if(onEvent[jaris.type]){
onEvent[jaris.type](jaris, data);
}
}
data.duration = jaris.duration;
}
};
mediaelement.jarisEvent[data.id].elem = elem;
}
createSwf(elem, canPlaySrc, data, elemId, hasControls, elemNodeName);
if(!streamRequest){
trigger(data._elem, 'loadstart');
}
};
var createSwf = function(elem, canPlaySrc, data, elemId, hasControls, elemNodeName){
var vars, elemVars, params, attrs;
var isRtmp = canPlaySrc.type == 'audio/rtmp' || canPlaySrc.type == 'video/rtmp';
var isUserStream = canPlaySrc.type == 'jarisplayer/stream';
vars = $.extend({}, options.vars, {
poster: replaceVar($.attr(elem, 'poster') && $.prop(elem, 'poster') || ''),
source: replaceVar(canPlaySrc.streamId || canPlaySrc.srcProp),
server: replaceVar(canPlaySrc.server || '')
});
elemVars = $(elem).data('vars') || {};
$.extend(vars,
{
id: elemId,
evtId: data.id,
controls: ''+(!isUserStream && hasControls),
autostart: 'false',
nodename: elemNodeName
},
elemVars
);
if(isRtmp){
vars.streamtype = 'rtmp';
} else if(isUserStream){
vars.streamtype = 'usermedia';
} else if(canPlaySrc.type == 'audio/mpeg' || canPlaySrc.type == 'audio/mp3'){
vars.type = 'audio';
vars.streamtype = 'file';
} else if(canPlaySrc.type == 'video/youtube'){
vars.streamtype = 'youtube';
}
attrs = $.extend(
{},
options.attrs,
{
name: elemId,
id: elemId
},
$(elem).data('attrs')
);
params = $.extend(
{},
options.params,
$(elem).data('params')
);
options.changeSWF(vars, elem, canPlaySrc, data, 'embed');
clearTimeout(data.flashBlock);
swfmini.embedSWF(playerSwfPath, elemId, "100%", "100%", "11.3", false, vars, params, attrs, function(swfData){
if(swfData.success){
var fBlocker = function(){
if((!swfData.ref.parentNode) || swfData.ref.style.display == "none"){
$(elem).trigger('flashblocker');
webshims.warn("flashblocker assumed");
}
$(swfData.ref).css({'minHeight': '2px', 'minWidth': '2px', display: 'block'});
};
data.api = swfData.ref;
if(!hasControls){
$(swfData.ref).attr('tabindex', '-1').css('outline', 'none');
}
data.flashBlock = setTimeout(fBlocker, 99);
if(!localConnectionTimer){
clearTimeout(localConnectionTimer);
localConnectionTimer = setTimeout(function(){
fBlocker();
var flash = $(swfData.ref);
if(flash[0].offsetWidth > 1 && flash[0].offsetHeight > 1 && location.protocol.indexOf('file:') === 0){
webshims.error("Add your local development-directory to the local-trusted security sandbox: http://www.macromedia.com/support/documentation/en/flashplayer/help/settings_manager04.html");
} else if(flash[0].offsetWidth < 2 || flash[0].offsetHeight < 2) {
webshims.warn("JS-SWF connection can't be established on hidden or unconnected flash objects");
}
flash = null;
}, 8000);
}
if(isUserStream){
webshim.usermedia.request(elem, canPlaySrc, data);
}
}
});
};
var queueSwfMethod = function(elem, fn, args, data){
data = data || getSwfDataFromElem(elem);
if(data){
if(data.api && data.api[fn]){
data.api[fn].apply(data.api, args || []);
} else {
//todo add to queue
data.actionQueue.push({fn: fn, args: args});
if(data.actionQueue.length > 10){
setTimeout(function(){
if(data.actionQueue.length > 5){
data.actionQueue.shift();
}
}, 99);
}
}
return data;
}
return false;
};
mediaelement.queueSwfMethod = queueSwfMethod;
['audio', 'video'].forEach(function(nodeName){
var descs = {};
var mediaSup;
var createGetProp = function(key){
if(nodeName == 'audio' && (key == 'videoHeight' || key == 'videoWidth')){return;}
descs[key] = {
get: function(){
var data = getSwfDataFromElem(this);
if(data){
return data[key];
} else if(hasNative && mediaSup[key].prop._supget) {
return mediaSup[key].prop._supget.apply(this);
} else {
return playerStateObj[key];
}
},
writeable: false
};
};
var createGetSetProp = function(key, setFn){
createGetProp(key);
delete descs[key].writeable;
descs[key].set = setFn;
};
createGetSetProp('seeking');
createGetSetProp('volume', function(v){
var data = getSwfDataFromElem(this);
if(data){
v *= 1;
if(!isNaN(v)){
if(v < 0 || v > 1){
webshims.error('volume greater or less than allowed '+ (v / 100));
}
queueSwfMethod(this, 'api_volume', [v], data);
if(data.volume != v){
data.volume = v;
trigger(data._elem, 'volumechange');
}
data = null;
}
} else if(mediaSup.volume.prop._supset) {
return mediaSup.volume.prop._supset.apply(this, arguments);
}
});
createGetSetProp('muted', function(m){
var data = getSwfDataFromElem(this);
if(data){
m = !!m;
queueSwfMethod(this, 'api_muted', [m], data);
if(data.muted != m){
data.muted = m;
trigger(data._elem, 'volumechange');
}
data = null;
} else if(mediaSup.muted.prop._supset) {
return mediaSup.muted.prop._supset.apply(this, arguments);
}
});
createGetSetProp('currentTime', function(t){
var data = getSwfDataFromElem(this);
if(data){
t *= 1;
if (!isNaN(t)) {
queueSwfMethod(this, 'api_seek', [t], data);
}
} else if(mediaSup.currentTime.prop._supset) {
return mediaSup.currentTime.prop._supset.apply(this, arguments);
}
});
['play', 'pause'].forEach(function(fn){
descs[fn] = {
value: function(){
var data = getSwfDataFromElem(this);
if(data){
if(data.stopPlayPause){
clearTimeout(data.stopPlayPause);
}
queueSwfMethod(this, fn == 'play' ? 'api_play' : 'api_pause', [], data);
data._ppFlag = true;
if(data.paused != (fn != 'play')){
data.paused = fn != 'play';
trigger(data._elem, fn);
}
} else if(mediaSup[fn].prop._supvalue) {
return mediaSup[fn].prop._supvalue.apply(this, arguments);
}
}
};
});
getPropKeys.forEach(createGetProp);
webshims.onNodeNamesPropertyModify(nodeName, 'controls', function(val, boolProp){
var data = getSwfDataFromElem(this);
$(this)[boolProp ? 'addClass' : 'removeClass']('webshims-controls');
if(data){
if(nodeName == 'audio'){
setElementDimension(data, boolProp);
}
queueSwfMethod(this, 'api_controls', [boolProp], data);
}
});
webshims.onNodeNamesPropertyModify(nodeName, 'preload', function(val){
var data, baseData, elem;
if(bufferSrc(this)){
data = getSwfDataFromElem(this);
if(data){
queueSwfMethod(this, 'api_preload', [], data);
} else if(needsLoadPreload && this.paused && !this.error && !$.data(this, 'mediaerror') && !this.readyState && !this.networkState && !this.autoplay && $(this).is(':not(.nonnative-api-active)')){
elem = this;
baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {});
clearTimeout(baseData.loadTimer);
baseData.loadTimer = setTimeout(function(){
$(elem).mediaLoad();
}, 9);
}
}
});
mediaSup = webshims.defineNodeNameProperties(nodeName, descs, 'prop');
if(!support.mediaDefaultMuted){
webshims.defineNodeNameProperties(nodeName, {
defaultMuted: {
get: function(){
return $.attr(this, 'muted') != null;
},
set: function(val){
if(val){
$.attr(this, 'muted', '');
} else {
$(this).removeAttr('muted');
}
}
}
}, 'prop');
}
});
var addCanvasBridge = function(){
if(!window.CanvasRenderingContext2D){
return false;
}
var _drawImage = CanvasRenderingContext2D.prototype.drawImage;
var slice = Array.prototype.slice;
var isVideo = {
video: 1,
VIDEO: 1
};
var tested = {};
var addToBlob = function(){
var desc = webshim.defineNodeNameProperty('canvas', 'toBlob', {
prop: {
value: function(){
var context = $(this).callProp('getContext', ['2d']);
var that = this;
var args = arguments;
var cb = function(){
return desc.prop._supvalue.apply(that, args);
};
if(context.wsImageComplete && context._wsIsLoading){
context.wsImageComplete(cb);
} else {
return cb();
}
}
}
});
};
if(!_drawImage){
webshim.error('canvas.drawImage feature is needed. In IE8 flashvanvas pro can be used');
}
CanvasRenderingContext2D.prototype.wsImageComplete = function(cb){
if(this._wsIsLoading){
if(!this._wsLoadingCbs){
this._wsLoadingCbs = [];
}
this._wsLoadingCbs.push(cb);
} else {
cb.call(this, this);
}
};
CanvasRenderingContext2D.prototype.drawImage = function(elem){
var data, img, args, imgData, hadCachedImg;
var context = this;
if(isVideo[elem.nodeName] && (data = webshims.data(elem, 'mediaelement')) && data.isActive == 'third' && data.api.api_image){
try {
imgData = data.api.api_image();
} catch (er){
webshims.error(er);
}
if(!tested[data.currentSrc]){
tested[data.currentSrc] = true;
if(imgData == null){
webshims.error('video has to be same origin or a crossdomain.xml has to be provided. Video has to be visible for flash API');
}
}
args = slice.call(arguments, 1);
if(options.canvasSync && data.canvasImg){
args.unshift(data.canvasImg);
_drawImage.apply(context, args);
args = slice.call(arguments, 1);
hadCachedImg = true;
}
img = document.createElement('img');
//todo find a performant sync way
img.onload = function(){
args.unshift(this);
img.onload = null;
if(options.canvasSync){
data.canvasImg = img;
if(hadCachedImg && options.noDoubbleDraw){
return;
}
}
_drawImage.apply(context, args);
context._wsIsLoading = false;
if(context._wsLoadingCbs && context._wsLoadingCbs.length){
while(context._wsLoadingCbs.length){
context._wsLoadingCbs.shift().call(context, context);
}
}
};
img.src = 'data:image/jpeg;base64,'+imgData;
this._wsIsLoading = true;
if(img.complete && img.onload){
img.onload();
}
return;
}
return _drawImage.apply(this, arguments);
};
if(!document.createElement('canvas').toBlob){
webshims.ready('filereader', addToBlob);
} else {
addToBlob();
}
return true;
};
if(!addCanvasBridge()){
webshims.ready('canvas', addCanvasBridge);
}
if(hasFlash && $.cleanData){
var oldClean = $.cleanData;
var objElem = document.createElement('object');
var noRemove = {
SetVariable: 1,
GetVariable: 1,
SetReturnValue: 1,
GetReturnValue: 1
};
var flashNames = {
object: 1,
OBJECT: 1
};
$.cleanData = function(elems){
var i, len, prop;
var ret = oldClean.apply(this, arguments);
if(elems && (len = elems.length) && loadedSwf){
for(i = 0; i < len; i++){
if(flashNames[elems[i].nodeName] && 'api_destroy' in elems[i]){
loadedSwf--;
try {
elems[i].api_destroy();
if(elems[i].readyState == 4){
for (prop in elems[i]) {
if (!noRemove[prop] && !objElem[prop] && typeof elems[i][prop] == "function") {
elems[i][prop] = null;
}
}
}
} catch(er){console.log(er);}
}
}
}
return ret;
};
}
if(!hasNative){
['poster', 'src'].forEach(function(prop){
webshims.defineNodeNamesProperty(prop == 'src' ? ['audio', 'video', 'source'] : ['video'], prop, {
//attr: {},
reflect: true,
propType: 'src'
});
});
webshims.defineNodeNamesProperty(['audio', 'video'], 'preload', {
reflect: true,
propType: 'enumarated',
defaultValue: '',
limitedTo: ['', 'auto', 'metadata', 'none']
});
webshims.reflectProperties('source', ['type', 'media']);
['autoplay', 'controls'].forEach(function(name){
webshims.defineNodeNamesBooleanProperty(['audio', 'video'], name);
});
webshims.defineNodeNamesProperties(['audio', 'video'], {
HAVE_CURRENT_DATA: {
value: 2
},
HAVE_ENOUGH_DATA: {
value: 4
},
HAVE_FUTURE_DATA: {
value: 3
},
HAVE_METADATA: {
value: 1
},
HAVE_NOTHING: {
value: 0
},
NETWORK_EMPTY: {
value: 0
},
NETWORK_IDLE: {
value: 1
},
NETWORK_LOADING: {
value: 2
},
NETWORK_NO_SOURCE: {
value: 3
}
}, 'prop');
if(hasFlash){
webshims.ready('WINDOWLOAD', function(){
setTimeout(function(){
if(!loadedSwf){
document.createElement('img').src = playerSwfPath;
}
}, 9);
});
}
} else if(!('media' in document.createElement('source'))){
webshims.reflectProperties('source', ['media']);
}
if(hasNative && hasFlash && !options.preferFlash){
var switchErrors = {
3: 1,
4: 1
};
var switchOptions = function(e){
var media, error, parent;
if(
($(e.target).is('audio, video') || ((parent = e.target.parentNode) && $('source', parent).last()[0] == e.target)) &&
(media = $(e.target).closest('audio, video')) && !media.hasClass('nonnative-api-active')
){
error = media.prop('error');
setTimeout(function(){
if(!media.hasClass('nonnative-api-active')){
if(error && switchErrors[error.code]){
options.preferFlash = true;
document.removeEventListener('error', switchOptions, true);
$('audio, video').each(function(){
webshims.mediaelement.selectSource(this);
});
webshims.error("switching mediaelements option to 'preferFlash', due to an error with native player: "+e.target.currentSrc+" Mediaerror: "+ media.prop('error')+ ' error.code: '+ error.code);
}
webshims.warn('There was a mediaelement error. Run the following line in your console to get more info: webshim.mediaelement.loadDebugger();')
}
});
}
};
document.addEventListener('error', switchOptions, true);
setTimeout(function(){
$('audio, video').each(function(){
var error = $.prop(this, 'error');
if(error && switchErrors[error]){
switchOptions({target: this});
}
});
});
}
});
;webshims.register('track', function($, webshims, window, document, undefined){
"use strict";
var mediaelement = webshims.mediaelement;
var id = new Date().getTime();
//descriptions are not really shown, but they are inserted into the dom
var showTracks = {subtitles: 1, captions: 1, descriptions: 1};
var dummyTrack = $('<track />');
var support = webshims.support;
var supportTrackMod = support.ES5 && support.objectAccessor;
var createEventTarget = function(obj){
var eventList = {};
obj.addEventListener = function(name, fn){
if(eventList[name]){
webshims.error('always use $.on to the shimed event: '+ name +' already bound fn was: '+ eventList[name] +' your fn was: '+ fn);
}
eventList[name] = fn;
};
obj.removeEventListener = function(name, fn){
if(eventList[name] && eventList[name] != fn){
webshims.error('always use $.on/$.off to the shimed event: '+ name +' already bound fn was: '+ eventList[name] +' your fn was: '+ fn);
}
if(eventList[name]){
delete eventList[name];
}
};
return obj;
};
var cueListProto = {
getCueById: function(id){
var cue = null;
for(var i = 0, len = this.length; i < len; i++){
if(this[i].id === id){
cue = this[i];
break;
}
}
return cue;
}
};
var numericModes = {
0: 'disabled',
1: 'hidden',
2: 'showing'
};
var textTrackProto = {
shimActiveCues: null,
_shimActiveCues: null,
activeCues: null,
cues: null,
kind: 'subtitles',
label: '',
language: '',
id: '',
mode: 'disabled',
oncuechange: null,
toString: function() {
return "[object TextTrack]";
},
addCue: function(cue){
if(!this.cues){
this.cues = mediaelement.createCueList();
} else {
var lastCue = this.cues[this.cues.length-1];
if(lastCue && lastCue.startTime > cue.startTime){
webshims.error("cue startTime higher than previous cue's startTime");
return;
}
}
if(cue.startTime >= cue.endTime ){
webshim.error('startTime >= endTime of cue: '+ cue.text);
}
if(cue.track && cue.track.removeCue){
cue.track.removeCue(cue);
}
cue.track = this;
this.cues.push(cue);
},
//ToDo: make it more dynamic
removeCue: function(cue){
var cues = this.cues || [];
var i = 0;
var len = cues.length;
if(cue.track != this){
webshims.error("cue not part of track");
return;
}
for(; i < len; i++){
if(cues[i] === cue){
cues.splice(i, 1);
cue.track = null;
break;
}
}
if(cue.track){
webshims.error("cue not part of track");
return;
}
}/*,
DISABLED: 'disabled',
OFF: 'disabled',
HIDDEN: 'hidden',
SHOWING: 'showing',
ERROR: 3,
LOADED: 2,
LOADING: 1,
NONE: 0*/
};
var copyProps = ['kind', 'label', 'srclang'];
var copyName = {srclang: 'language'};
var updateMediaTrackList = function(baseData, trackList){
var i, len;
var callChange = false;
var removed = [];
var added = [];
var newTracks = [];
if(!baseData){
baseData = webshims.data(this, 'mediaelementBase') || webshims.data(this, 'mediaelementBase', {});
}
if(!trackList){
baseData.blockTrackListUpdate = true;
trackList = $.prop(this, 'textTracks');
baseData.blockTrackListUpdate = false;
}
clearTimeout(baseData.updateTrackListTimer);
$('track', this).each(function(){
var track = $.prop(this, 'track');
newTracks.push(track);
if(trackList.indexOf(track) == -1){
added.push(track);
}
});
if(baseData.scriptedTextTracks){
for(i = 0, len = baseData.scriptedTextTracks.length; i < len; i++){
newTracks.push(baseData.scriptedTextTracks[i]);
if(trackList.indexOf(baseData.scriptedTextTracks[i]) == -1){
added.push(baseData.scriptedTextTracks[i]);
}
}
}
for(i = 0, len = trackList.length; i < len; i++){
if(newTracks.indexOf(trackList[i]) == -1){
removed.push(trackList[i]);
}
}
if(removed.length || added.length){
trackList.splice(0);
for(i = 0, len = newTracks.length; i < len; i++){
trackList.push(newTracks[i]);
}
for(i = 0, len = removed.length; i < len; i++){
$([trackList]).triggerHandler($.Event({type: 'removetrack', track: removed[i]}));
}
for(i = 0, len = added.length; i < len; i++){
$([trackList]).triggerHandler($.Event({type: 'addtrack', track: added[i]}));
}
//todo: remove
if(baseData.scriptedTextTracks || removed.length){
$(this).triggerHandler('updatetrackdisplay');
}
}
for(i = 0, len = trackList.length; i < len; i++){
if(trackList[i].__wsmode != trackList[i].mode){
trackList[i].__wsmode = trackList[i].mode;
callChange = true;
}
}
if(callChange){
$([trackList]).triggerHandler('change');
}
};
var refreshTrack = function(track, trackData){
if(!trackData){
trackData = webshims.data(track, 'trackData');
}
if(trackData && !trackData.isTriggering){
trackData.isTriggering = true;
setTimeout(function(){
$(track).closest('audio, video').triggerHandler('updatetrackdisplay');
trackData.isTriggering = false;
}, 9);
}
};
var isDefaultTrack = (function(){
var defaultKinds = {
subtitles: {
subtitles: 1,
captions: 1
},
descriptions: {descriptions: 1},
chapters: {chapters: 1}
};
defaultKinds.captions = defaultKinds.subtitles;
return function(track){
var kind, firstDefaultTrack;
var isDefault = $.prop(track, 'default');
if(isDefault && (kind = $.prop(track, 'kind')) != 'metadata'){
firstDefaultTrack = $(track)
.parent()
.find('track[default]')
.filter(function(){
return !!(defaultKinds[kind][$.prop(this, 'kind')]);
})[0]
;
if(firstDefaultTrack != track){
isDefault = false;
webshims.error('more than one default track of a specific kind detected. Fall back to default = false');
}
}
return isDefault;
};
})();
var emptyDiv = $('<div />')[0];
function VTTCue(startTime, endTime, text){
if(arguments.length != 3){
webshims.error("wrong arguments.length for VTTCue.constructor");
}
this.startTime = startTime;
this.endTime = endTime;
this.text = text;
this.onenter = null;
this.onexit = null;
this.pauseOnExit = false;
this.track = null;
this.id = null;
this.getCueAsHTML = (function(){
var lastText = "";
var parsedText = "";
var fragment;
return function(){
var i, len;
if(!fragment){
fragment = document.createDocumentFragment();
}
if(lastText != this.text){
lastText = this.text;
parsedText = mediaelement.parseCueTextToHTML(lastText);
emptyDiv.innerHTML = parsedText;
for(i = 0, len = emptyDiv.childNodes.length; i < len; i++){
fragment.appendChild(emptyDiv.childNodes[i].cloneNode(true));
}
}
return fragment.cloneNode(true);
};
})();
}
window.VTTCue = VTTCue;
window.TextTrackCue = function(){
webshims.error("Use VTTCue constructor instead of abstract TextTrackCue constructor.");
VTTCue.apply(this, arguments);
};
window.TextTrackCue.prototype = VTTCue.prototype;
mediaelement.createCueList = function(){
return $.extend([], cueListProto);
};
mediaelement.parseCueTextToHTML = (function(){
var tagSplits = /(<\/?[^>]+>)/ig;
var allowedTags = /^(?:c|v|ruby|rt|b|i|u)/;
var regEnd = /\<\s*\//;
var addToTemplate = function(localName, attribute, tag, html){
var ret;
if(regEnd.test(html)){
ret = '</'+ localName +'>';
} else {
tag.splice(0, 1);
ret = '<'+ localName +' '+ attribute +'="'+ (tag.join(' ').replace(/\"/g, '"')) +'">';
}
return ret;
};
var replacer = function(html){
var tag = html.replace(/[<\/>]+/ig,"").split(/[\s\.]+/);
if(tag[0]){
tag[0] = tag[0].toLowerCase();
if(allowedTags.test(tag[0])){
if(tag[0] == 'c'){
html = addToTemplate('span', 'class', tag, html);
} else if(tag[0] == 'v'){
html = addToTemplate('q', 'title', tag, html);
}
} else {
html = "";
}
}
return html;
};
return function(cueText){
return cueText.replace(tagSplits, replacer);
};
})();
var mapTtmlToVtt = function(i){
var content = i+'';
var begin = this.getAttribute('begin') || '';
var end = this.getAttribute('end') || '';
var text = $.trim($.text(this));
if(!/\./.test(begin)){
begin += '.000';
}
if(!/\./.test(end)){
end += '.000';
}
content += '\n';
content += begin +' --> '+end+'\n';
content += text;
return content;
};
var ttmlTextToVTT = function(ttml){
ttml = $.parseXML(ttml) || [];
return $(ttml).find('[begin][end]').map(mapTtmlToVtt).get().join('\n\n') || '';
};
var loadingTracks = 0;
mediaelement.loadTextTrack = function(mediaelem, track, trackData, _default){
var loadEvents = 'play playing loadedmetadata loadstart';
var obj = trackData.track;
var load = function(){
var error, ajax, createAjax;
var isDisabled = obj.mode == 'disabled';
var videoState = !!($.prop(mediaelem, 'readyState') > 0 || $.prop(mediaelem, 'networkState') == 2 || !$.prop(mediaelem, 'paused'));
var src = (!isDisabled || videoState) && ($.attr(track, 'src') && $.prop(track, 'src'));
if(src){
$(mediaelem).off(loadEvents, load).off('updatetrackdisplay', load);
if(!trackData.readyState){
error = function(){
loadingTracks--;
trackData.readyState = 3;
obj.cues = null;
obj.activeCues = obj.shimActiveCues = obj._shimActiveCues = null;
$(track).triggerHandler('error');
};
trackData.readyState = 1;
try {
obj.cues = mediaelement.createCueList();
obj.activeCues = obj.shimActiveCues = obj._shimActiveCues = mediaelement.createCueList();
loadingTracks++;
createAjax = function(){
ajax = $.ajax({
dataType: 'text',
url: src,
success: function(text){
loadingTracks--;
var contentType = ajax.getResponseHeader('content-type') || '';
if(!contentType.indexOf('application/xml')){
text = ttmlTextToVTT(text);
} else if(contentType.indexOf('text/vtt')){
webshims.error('set the mime-type of your WebVTT files to text/vtt. see: http://dev.w3.org/html5/webvtt/#text/vtt');
}
mediaelement.parseCaptions(text, obj, function(cues){
if(cues && 'length' in cues){
trackData.readyState = 2;
$(track).triggerHandler('load');
$(mediaelem).triggerHandler('updatetrackdisplay');
} else {
error();
}
});
},
error: error
});
};
if(isDisabled){
setTimeout(createAjax, loadingTracks * 2);
} else {
createAjax();
}
} catch(er){
error();
webshims.error(er);
}
}
}
};
trackData.readyState = 0;
obj.shimActiveCues = null;
obj._shimActiveCues = null;
obj.activeCues = null;
obj.cues = null;
$(mediaelem).on(loadEvents, load);
if(_default){
obj.mode = showTracks[obj.kind] ? 'showing' : 'hidden';
load();
} else {
$(mediaelem).on('updatetrackdisplay', load);
}
};
mediaelement.createTextTrack = function(mediaelem, track){
var obj, trackData;
if(track.nodeName){
trackData = webshims.data(track, 'trackData');
if(trackData){
refreshTrack(track, trackData);
obj = trackData.track;
}
}
if(!obj){
obj = createEventTarget(webshims.objectCreate(textTrackProto));
if(!supportTrackMod){
copyProps.forEach(function(copyProp){
var prop = $.prop(track, copyProp);
if(prop){
obj[copyName[copyProp] || copyProp] = prop;
}
});
}
if(track.nodeName){
if(supportTrackMod){
copyProps.forEach(function(copyProp){
webshims.defineProperty(obj, copyName[copyProp] || copyProp, {
get: function(){
return $.prop(track, copyProp);
}
});
});
}
obj.id = $(track).prop('id');
trackData = webshims.data(track, 'trackData', {track: obj});
mediaelement.loadTextTrack(mediaelem, track, trackData, isDefaultTrack(track));
} else {
if(supportTrackMod){
copyProps.forEach(function(copyProp){
webshims.defineProperty(obj, copyName[copyProp] || copyProp, {
value: track[copyProp],
writeable: false
});
});
}
obj.cues = mediaelement.createCueList();
obj.activeCues = obj._shimActiveCues = obj.shimActiveCues = mediaelement.createCueList();
obj.mode = 'hidden';
obj.readyState = 2;
}
if(obj.kind == 'subtitles' && !obj.language){
webshims.error('you must provide a language for track in subtitles state');
}
obj.__wsmode = obj.mode;
webshims.defineProperty(obj, '_wsUpdateMode', {
value: function(){
$(mediaelem).triggerHandler('updatetrackdisplay');
},
enumerable: false
});
}
return obj;
};
if(!$.propHooks.mode){
$.propHooks.mode = {
set: function(obj, value){
obj.mode = value;
if(obj._wsUpdateMode && obj._wsUpdateMode.call){
obj._wsUpdateMode();
}
return obj.mode;
}
};
}
/*
taken from:
Captionator 0.5.1 [CaptionCrunch]
Christopher Giffard, 2011
Share and enjoy
https://github.com/cgiffard/Captionator
modified for webshims
*/
mediaelement.parseCaptionChunk = (function(){
// Set up timestamp parsers
var WebVTTTimestampParser = /^(\d{2})?:?(\d{2}):(\d{2})\.(\d+)\s+\-\-\>\s+(\d{2})?:?(\d{2}):(\d{2})\.(\d+)\s*(.*)/;
var WebVTTDEFAULTSCueParser = /^(DEFAULTS|DEFAULT)\s+\-\-\>\s+(.*)/g;
var WebVTTSTYLECueParser = /^(STYLE|STYLES)\s+\-\-\>\s*\n([\s\S]*)/g;
var WebVTTCOMMENTCueParser = /^(COMMENT|COMMENTS)\s+\-\-\>\s+(.*)/g;
var SRTTimestampParser = /^(\d{2})?:?(\d{2}):(\d{2})[\.\,](\d+)\s+\-\-\>\s+(\d{2})?:?(\d{2}):(\d{2})[\.\,](\d+)\s*(.*)/;
return function(subtitleElement,objectCount){
var subtitleParts, timeIn, timeOut, html, timeData, subtitlePartIndex, id;
var timestampMatch, tmpCue;
// WebVTT Special Cue Logic
if (WebVTTDEFAULTSCueParser.exec(subtitleElement) || WebVTTCOMMENTCueParser.exec(subtitleElement) || WebVTTSTYLECueParser.exec(subtitleElement)) {
return null;
}
subtitleParts = subtitleElement.split(/\n/g);
// Trim off any blank lines (logically, should only be max. one, but loop to be sure)
while (!subtitleParts[0].replace(/\s+/ig,"").length && subtitleParts.length > 0) {
subtitleParts.shift();
}
if (subtitleParts[0].match(/^\s*[a-z0-9-\_]+\s*$/ig)) {
// The identifier becomes the cue ID (when *we* load the cues from file. Programatically created cues can have an ID of whatever.)
id = String(subtitleParts.shift().replace(/\s*/ig,""));
}
for (subtitlePartIndex = 0; subtitlePartIndex < subtitleParts.length; subtitlePartIndex ++) {
var timestamp = subtitleParts[subtitlePartIndex];
if ((timestampMatch = WebVTTTimestampParser.exec(timestamp)) || (timestampMatch = SRTTimestampParser.exec(timestamp))) {
// WebVTT
timeData = timestampMatch.slice(1);
timeIn = parseInt((timeData[0]||0) * 60 * 60,10) + // Hours
parseInt((timeData[1]||0) * 60,10) + // Minutes
parseInt((timeData[2]||0),10) + // Seconds
parseFloat("0." + (timeData[3]||0)); // MS
timeOut = parseInt((timeData[4]||0) * 60 * 60,10) + // Hours
parseInt((timeData[5]||0) * 60,10) + // Minutes
parseInt((timeData[6]||0),10) + // Seconds
parseFloat("0." + (timeData[7]||0)); // MS
/*
if (timeData[8]) {
cueSettings = timeData[8];
}
*/
}
// We've got the timestamp - return all the other unmatched lines as the raw subtitle data
subtitleParts = subtitleParts.slice(0,subtitlePartIndex).concat(subtitleParts.slice(subtitlePartIndex+1));
break;
}
if (!timeIn && !timeOut) {
// We didn't extract any time information. Assume the cue is invalid!
webshims.warn("couldn't extract time information: "+[timeIn, timeOut, subtitleParts.join("\n"), id].join(' ; '));
return null;
}
/*
// Consolidate cue settings, convert defaults to object
var compositeCueSettings =
cueDefaults
.reduce(function(previous,current,index,array){
previous[current.split(":")[0]] = current.split(":")[1];
return previous;
},{});
// Loop through cue settings, replace defaults with cue specific settings if they exist
compositeCueSettings =
cueSettings
.split(/\s+/g)
.filter(function(set) { return set && !!set.length; })
// Convert array to a key/val object
.reduce(function(previous,current,index,array){
previous[current.split(":")[0]] = current.split(":")[1];
return previous;
},compositeCueSettings);
// Turn back into string like the VTTCue constructor expects
cueSettings = "";
for (var key in compositeCueSettings) {
if (compositeCueSettings.hasOwnProperty(key)) {
cueSettings += !!cueSettings.length ? " " : "";
cueSettings += key + ":" + compositeCueSettings[key];
}
}
*/
// The remaining lines are the subtitle payload itself (after removing an ID if present, and the time);
html = subtitleParts.join("\n");
tmpCue = new VTTCue(timeIn, timeOut, html);
if(id){
tmpCue.id = id;
}
return tmpCue;
};
})();
mediaelement.parseCaptions = function(captionData, track, complete) {
var cue, lazyProcess, regWevVTT, startDate, isWEBVTT;
mediaelement.createCueList();
if (captionData) {
regWevVTT = /^WEBVTT(\s*FILE)?/ig;
lazyProcess = function(i, len){
for(; i < len; i++){
cue = captionData[i];
if(regWevVTT.test(cue)){
isWEBVTT = true;
} else if(cue.replace(/\s*/ig,"").length){
cue = mediaelement.parseCaptionChunk(cue, i);
if(cue){
track.addCue(cue);
}
}
if(startDate < (new Date().getTime()) - 30){
i++;
setTimeout(function(){
startDate = new Date().getTime();
lazyProcess(i, len);
}, 90);
break;
}
}
if(i >= len){
if(!isWEBVTT){
webshims.error('please use WebVTT format. This is the standard');
}
complete(track.cues);
}
};
captionData = captionData.replace(/\r\n/g,"\n");
setTimeout(function(){
captionData = captionData.replace(/\r/g,"\n");
setTimeout(function(){
startDate = new Date().getTime();
captionData = captionData.split(/\n\n+/g);
lazyProcess(0, captionData.length);
}, 9);
}, 9);
} else {
webshims.error("Required parameter captionData not supplied.");
}
};
mediaelement.createTrackList = function(mediaelem, baseData){
baseData = baseData || webshims.data(mediaelem, 'mediaelementBase') || webshims.data(mediaelem, 'mediaelementBase', {});
if(!baseData.textTracks){
baseData.textTracks = [];
webshims.defineProperties(baseData.textTracks, {
onaddtrack: {value: null},
onremovetrack: {value: null},
onchange: {value: null},
getTrackById: {
value: function(id){
var track = null;
for(var i = 0; i < baseData.textTracks.length; i++){
if(id == baseData.textTracks[i].id){
track = baseData.textTracks[i];
break;
}
}
return track;
}
}
});
createEventTarget(baseData.textTracks);
$(mediaelem).on('updatetrackdisplay', function(){
var track;
for(var i = 0; i < baseData.textTracks.length; i++){
track = baseData.textTracks[i];
if(track.__wsmode != track.mode){
track.__wsmode = track.mode;
$([ baseData.textTracks ]).triggerHandler('change');
}
}
});
}
return baseData.textTracks;
};
if(!support.track){
webshims.defineNodeNamesBooleanProperty(['track'], 'default');
webshims.reflectProperties(['track'], ['srclang', 'label']);
webshims.defineNodeNameProperties('track', {
src: {
//attr: {},
reflect: true,
propType: 'src'
}
});
}
webshims.defineNodeNameProperties('track', {
kind: {
attr: support.track ? {
set: function(value){
var trackData = webshims.data(this, 'trackData');
this.setAttribute('data-kind', value);
if(trackData){
trackData.attrKind = value;
}
},
get: function(){
var trackData = webshims.data(this, 'trackData');
if(trackData && ('attrKind' in trackData)){
return trackData.attrKind;
}
return this.getAttribute('kind');
}
} : {},
reflect: true,
propType: 'enumarated',
defaultValue: 'subtitles',
limitedTo: ['subtitles', 'captions', 'descriptions', 'chapters', 'metadata']
}
});
$.each(copyProps, function(i, copyProp){
var name = copyName[copyProp] || copyProp;
webshims.onNodeNamesPropertyModify('track', copyProp, function(){
var trackData = webshims.data(this, 'trackData');
if(trackData){
if(copyProp == 'kind'){
refreshTrack(this, trackData);
}
if(!supportTrackMod){
trackData.track[name] = $.prop(this, copyProp);
}
}
});
});
webshims.onNodeNamesPropertyModify('track', 'src', function(val){
if(val){
var data = webshims.data(this, 'trackData');
var media;
if(data){
media = $(this).closest('video, audio');
if(media[0]){
mediaelement.loadTextTrack(media, this, data);
}
}
}
});
//
webshims.defineNodeNamesProperties(['track'], {
ERROR: {
value: 3
},
LOADED: {
value: 2
},
LOADING: {
value: 1
},
NONE: {
value: 0
},
readyState: {
get: function(){
return (webshims.data(this, 'trackData') || {readyState: 0}).readyState;
},
writeable: false
},
track: {
get: function(){
return mediaelement.createTextTrack($(this).closest('audio, video')[0], this);
},
writeable: false
}
}, 'prop');
webshims.defineNodeNamesProperties(['audio', 'video'], {
textTracks: {
get: function(){
var media = this;
var baseData = webshims.data(media, 'mediaelementBase') || webshims.data(media, 'mediaelementBase', {});
var tracks = mediaelement.createTrackList(media, baseData);
if(!baseData.blockTrackListUpdate){
updateMediaTrackList.call(media, baseData, tracks);
}
return tracks;
},
writeable: false
},
addTextTrack: {
value: function(kind, label, lang){
var textTrack = mediaelement.createTextTrack(this, {
kind: dummyTrack.prop('kind', kind || '').prop('kind'),
label: label || '',
srclang: lang || ''
});
var baseData = webshims.data(this, 'mediaelementBase') || webshims.data(this, 'mediaelementBase', {});
if (!baseData.scriptedTextTracks) {
baseData.scriptedTextTracks = [];
}
baseData.scriptedTextTracks.push(textTrack);
updateMediaTrackList.call(this);
return textTrack;
}
}
}, 'prop');
//wsmediareload
var thUpdateList = function(e){
if($(e.target).is('audio, video')){
var baseData = webshims.data(e.target, 'mediaelementBase');
if(baseData){
clearTimeout(baseData.updateTrackListTimer);
baseData.updateTrackListTimer = setTimeout(function(){
updateMediaTrackList.call(e.target, baseData);
}, 0);
}
}
};
var getNativeReadyState = function(trackElem, textTrack){
return textTrack.readyState || trackElem.readyState;
};
var stopOriginalEvent = function(e){
if(e.originalEvent){
e.stopImmediatePropagation();
}
};
var hideNativeTracks = function(){
if(webshims.implement(this, 'track')){
var kind;
var origTrack = this.track;
if(origTrack){
if (!webshims.bugs.track && (origTrack.mode || getNativeReadyState(this, origTrack))) {
$.prop(this, 'track').mode = numericModes[origTrack.mode] || origTrack.mode;
}
//disable track from showing + remove UI
kind = $.prop(this, 'kind');
origTrack.mode = (typeof origTrack.mode == 'string') ? 'disabled' : 0;
this.kind = 'metadata';
$(this).attr({kind: kind});
}
$(this).on('load error', stopOriginalEvent);
}
};
webshims.addReady(function(context, insertedElement){
var insertedMedia = insertedElement.filter('video, audio, track').closest('audio, video');
$('video, audio', context)
.add(insertedMedia)
.each(function(){
updateMediaTrackList.call(this);
})
.on('emptied updatetracklist wsmediareload', thUpdateList)
.each(function(){
if(support.track){
var shimedTextTracks = $.prop(this, 'textTracks');
var origTextTracks = this.textTracks;
if(shimedTextTracks.length != origTextTracks.length){
webshims.warn("textTracks couldn't be copied");
}
$('track', this).each(hideNativeTracks);
}
})
;
insertedMedia.each(function(){
var media = this;
var baseData = webshims.data(media, 'mediaelementBase');
if(baseData){
clearTimeout(baseData.updateTrackListTimer);
baseData.updateTrackListTimer = setTimeout(function(){
updateMediaTrackList.call(media, baseData);
}, 9);
}
});
});
if(support.texttrackapi){
$('video, audio').trigger('trackapichange');
}
});
| andrepiske/cdnjs | ajax/libs/webshim/1.15.5/dev/shims/combos/21.js | JavaScript | mit | 69,562 |
// Generated by CoffeeScript 1.3.3
(function() {
var Access, Arr, Assign, Base, Block, Call, Class, Closure, Code, Comment, Existence, Extends, For, IDENTIFIER, IDENTIFIER_STR, IS_STRING, If, In, Index, LEVEL_ACCESS, LEVEL_COND, LEVEL_LIST, LEVEL_OP, LEVEL_PAREN, LEVEL_TOP, Literal, METHOD_DEF, NEGATE, NO, Obj, Op, Param, Parens, RESERVED, Range, Return, SIMPLENUM, STRICT_PROSCRIBED, Scope, Slice, Splat, Switch, TAB, THIS, Throw, Try, UTILITIES, Value, While, YES, compact, del, ends, extend, flatten, last, merge, multident, starts, unfoldSoak, utility, _ref, _ref1,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__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; };
Scope = require('./scope').Scope;
_ref = require('./lexer'), RESERVED = _ref.RESERVED, STRICT_PROSCRIBED = _ref.STRICT_PROSCRIBED;
_ref1 = require('./helpers'), compact = _ref1.compact, flatten = _ref1.flatten, extend = _ref1.extend, merge = _ref1.merge, del = _ref1.del, starts = _ref1.starts, ends = _ref1.ends, last = _ref1.last;
exports.extend = extend;
YES = function() {
return true;
};
NO = function() {
return false;
};
THIS = function() {
return this;
};
NEGATE = function() {
this.negated = !this.negated;
return this;
};
exports.Base = Base = (function() {
function Base() {}
Base.prototype.compile = function(o, lvl) {
var node;
o = extend({}, o);
if (lvl) {
o.level = lvl;
}
node = this.unfoldSoak(o) || this;
node.tab = o.indent;
if (o.level === LEVEL_TOP || !node.isStatement(o)) {
return node.compileNode(o);
} else {
return node.compileClosure(o);
}
};
Base.prototype.compileClosure = function(o) {
if (this.jumps()) {
throw SyntaxError('cannot use a pure statement in an expression.');
}
o.sharedScope = true;
return Closure.wrap(this).compileNode(o);
};
Base.prototype.cache = function(o, level, reused) {
var ref, sub;
if (!this.isComplex()) {
ref = level ? this.compile(o, level) : this;
return [ref, ref];
} else {
ref = new Literal(reused || o.scope.freeVariable('ref'));
sub = new Assign(ref, this);
if (level) {
return [sub.compile(o, level), ref.value];
} else {
return [sub, ref];
}
}
};
Base.prototype.compileLoopReference = function(o, name) {
var src, tmp;
src = tmp = this.compile(o, LEVEL_LIST);
if (!((-Infinity < +src && +src < Infinity) || IDENTIFIER.test(src) && o.scope.check(src, true))) {
src = "" + (tmp = o.scope.freeVariable(name)) + " = " + src;
}
return [src, tmp];
};
Base.prototype.makeReturn = function(res) {
var me;
me = this.unwrapAll();
if (res) {
return new Call(new Literal("" + res + ".push"), [me]);
} else {
return new Return(me);
}
};
Base.prototype.contains = function(pred) {
var contains;
contains = false;
this.traverseChildren(false, function(node) {
if (pred(node)) {
contains = true;
return false;
}
});
return contains;
};
Base.prototype.containsType = function(type) {
return this instanceof type || this.contains(function(node) {
return node instanceof type;
});
};
Base.prototype.lastNonComment = function(list) {
var i;
i = list.length;
while (i--) {
if (!(list[i] instanceof Comment)) {
return list[i];
}
}
return null;
};
Base.prototype.toString = function(idt, name) {
var tree;
if (idt == null) {
idt = '';
}
if (name == null) {
name = this.constructor.name;
}
tree = '\n' + idt + name;
if (this.soak) {
tree += '?';
}
this.eachChild(function(node) {
return tree += node.toString(idt + TAB);
});
return tree;
};
Base.prototype.eachChild = function(func) {
var attr, child, _i, _j, _len, _len1, _ref2, _ref3;
if (!this.children) {
return this;
}
_ref2 = this.children;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
attr = _ref2[_i];
if (this[attr]) {
_ref3 = flatten([this[attr]]);
for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) {
child = _ref3[_j];
if (func(child) === false) {
return this;
}
}
}
}
return this;
};
Base.prototype.traverseChildren = function(crossScope, func) {
return this.eachChild(function(child) {
if (func(child) === false) {
return false;
}
return child.traverseChildren(crossScope, func);
});
};
Base.prototype.invert = function() {
return new Op('!', this);
};
Base.prototype.unwrapAll = function() {
var node;
node = this;
while (node !== (node = node.unwrap())) {
continue;
}
return node;
};
Base.prototype.children = [];
Base.prototype.isStatement = NO;
Base.prototype.jumps = NO;
Base.prototype.isComplex = YES;
Base.prototype.isChainable = NO;
Base.prototype.isAssignable = NO;
Base.prototype.unwrap = THIS;
Base.prototype.unfoldSoak = NO;
Base.prototype.assigns = NO;
return Base;
})();
exports.Block = Block = (function(_super) {
__extends(Block, _super);
function Block(nodes) {
this.expressions = compact(flatten(nodes || []));
}
Block.prototype.children = ['expressions'];
Block.prototype.push = function(node) {
this.expressions.push(node);
return this;
};
Block.prototype.pop = function() {
return this.expressions.pop();
};
Block.prototype.unshift = function(node) {
this.expressions.unshift(node);
return this;
};
Block.prototype.unwrap = function() {
if (this.expressions.length === 1) {
return this.expressions[0];
} else {
return this;
}
};
Block.prototype.isEmpty = function() {
return !this.expressions.length;
};
Block.prototype.isStatement = function(o) {
var exp, _i, _len, _ref2;
_ref2 = this.expressions;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
exp = _ref2[_i];
if (exp.isStatement(o)) {
return true;
}
}
return false;
};
Block.prototype.jumps = function(o) {
var exp, _i, _len, _ref2;
_ref2 = this.expressions;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
exp = _ref2[_i];
if (exp.jumps(o)) {
return exp;
}
}
};
Block.prototype.makeReturn = function(res) {
var expr, len;
len = this.expressions.length;
while (len--) {
expr = this.expressions[len];
if (!(expr instanceof Comment)) {
this.expressions[len] = expr.makeReturn(res);
if (expr instanceof Return && !expr.expression) {
this.expressions.splice(len, 1);
}
break;
}
}
return this;
};
Block.prototype.compile = function(o, level) {
if (o == null) {
o = {};
}
if (o.scope) {
return Block.__super__.compile.call(this, o, level);
} else {
return this.compileRoot(o);
}
};
Block.prototype.compileNode = function(o) {
var code, codes, node, top, _i, _len, _ref2;
this.tab = o.indent;
top = o.level === LEVEL_TOP;
codes = [];
_ref2 = this.expressions;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
node = _ref2[_i];
node = node.unwrapAll();
node = node.unfoldSoak(o) || node;
if (node instanceof Block) {
codes.push(node.compileNode(o));
} else if (top) {
node.front = true;
code = node.compile(o);
if (!node.isStatement(o)) {
code = "" + this.tab + code + ";";
if (node instanceof Literal) {
code = "" + code + "\n";
}
}
codes.push(code);
} else {
codes.push(node.compile(o, LEVEL_LIST));
}
}
if (top) {
if (this.spaced) {
return "\n" + (codes.join('\n\n')) + "\n";
} else {
return codes.join('\n');
}
}
code = codes.join(', ') || 'void 0';
if (codes.length > 1 && o.level >= LEVEL_LIST) {
return "(" + code + ")";
} else {
return code;
}
};
Block.prototype.compileRoot = function(o) {
var code, exp, i, prelude, preludeExps, rest;
o.indent = o.bare ? '' : TAB;
o.scope = new Scope(null, this, null);
o.level = LEVEL_TOP;
this.spaced = true;
prelude = "";
if (!o.bare) {
preludeExps = (function() {
var _i, _len, _ref2, _results;
_ref2 = this.expressions;
_results = [];
for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) {
exp = _ref2[i];
if (!(exp.unwrap() instanceof Comment)) {
break;
}
_results.push(exp);
}
return _results;
}).call(this);
rest = this.expressions.slice(preludeExps.length);
this.expressions = preludeExps;
if (preludeExps.length) {
prelude = "" + (this.compileNode(merge(o, {
indent: ''
}))) + "\n";
}
this.expressions = rest;
}
code = this.compileWithDeclarations(o);
if (o.bare) {
return code;
}
return "" + prelude + "(function() {\n" + code + "\n}).call(this);\n";
};
Block.prototype.compileWithDeclarations = function(o) {
var assigns, code, declars, exp, i, post, rest, scope, spaced, _i, _len, _ref2, _ref3, _ref4;
code = post = '';
_ref2 = this.expressions;
for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) {
exp = _ref2[i];
exp = exp.unwrap();
if (!(exp instanceof Comment || exp instanceof Literal)) {
break;
}
}
o = merge(o, {
level: LEVEL_TOP
});
if (i) {
rest = this.expressions.splice(i, 9e9);
_ref3 = [this.spaced, false], spaced = _ref3[0], this.spaced = _ref3[1];
_ref4 = [this.compileNode(o), spaced], code = _ref4[0], this.spaced = _ref4[1];
this.expressions = rest;
}
post = this.compileNode(o);
scope = o.scope;
if (scope.expressions === this) {
declars = o.scope.hasDeclarations();
assigns = scope.hasAssignments;
if (declars || assigns) {
if (i) {
code += '\n';
}
code += "" + this.tab + "var ";
if (declars) {
code += scope.declaredVariables().join(', ');
}
if (assigns) {
if (declars) {
code += ",\n" + (this.tab + TAB);
}
code += scope.assignedVariables().join(",\n" + (this.tab + TAB));
}
code += ';\n';
}
}
return code + post;
};
Block.wrap = function(nodes) {
if (nodes.length === 1 && nodes[0] instanceof Block) {
return nodes[0];
}
return new Block(nodes);
};
return Block;
})(Base);
exports.Literal = Literal = (function(_super) {
__extends(Literal, _super);
function Literal(value) {
this.value = value;
}
Literal.prototype.makeReturn = function() {
if (this.isStatement()) {
return this;
} else {
return Literal.__super__.makeReturn.apply(this, arguments);
}
};
Literal.prototype.isAssignable = function() {
return IDENTIFIER.test(this.value);
};
Literal.prototype.isStatement = function() {
var _ref2;
return (_ref2 = this.value) === 'break' || _ref2 === 'continue' || _ref2 === 'debugger';
};
Literal.prototype.isComplex = NO;
Literal.prototype.assigns = function(name) {
return name === this.value;
};
Literal.prototype.jumps = function(o) {
if (this.value === 'break' && !((o != null ? o.loop : void 0) || (o != null ? o.block : void 0))) {
return this;
}
if (this.value === 'continue' && !(o != null ? o.loop : void 0)) {
return this;
}
};
Literal.prototype.compileNode = function(o) {
var code, _ref2;
code = this.value === 'this' ? ((_ref2 = o.scope.method) != null ? _ref2.bound : void 0) ? o.scope.method.context : this.value : this.value.reserved ? "\"" + this.value + "\"" : this.value;
if (this.isStatement()) {
return "" + this.tab + code + ";";
} else {
return code;
}
};
Literal.prototype.toString = function() {
return ' "' + this.value + '"';
};
return Literal;
})(Base);
exports.Undefined = (function(_super) {
__extends(Undefined, _super);
function Undefined() {
return Undefined.__super__.constructor.apply(this, arguments);
}
Undefined.prototype.isAssignable = NO;
Undefined.prototype.isComplex = NO;
Undefined.prototype.compileNode = function(o) {
if (o.level >= LEVEL_ACCESS) {
return '(void 0)';
} else {
return 'void 0';
}
};
return Undefined;
})(Base);
exports.Null = (function(_super) {
__extends(Null, _super);
function Null() {
return Null.__super__.constructor.apply(this, arguments);
}
Null.prototype.isAssignable = NO;
Null.prototype.isComplex = NO;
Null.prototype.compileNode = function() {
return "null";
};
return Null;
})(Base);
exports.Bool = (function(_super) {
__extends(Bool, _super);
Bool.prototype.isAssignable = NO;
Bool.prototype.isComplex = NO;
Bool.prototype.compileNode = function() {
return this.val;
};
function Bool(val) {
this.val = val;
}
return Bool;
})(Base);
exports.Return = Return = (function(_super) {
__extends(Return, _super);
function Return(expr) {
if (expr && !expr.unwrap().isUndefined) {
this.expression = expr;
}
}
Return.prototype.children = ['expression'];
Return.prototype.isStatement = YES;
Return.prototype.makeReturn = THIS;
Return.prototype.jumps = THIS;
Return.prototype.compile = function(o, level) {
var expr, _ref2;
expr = (_ref2 = this.expression) != null ? _ref2.makeReturn() : void 0;
if (expr && !(expr instanceof Return)) {
return expr.compile(o, level);
} else {
return Return.__super__.compile.call(this, o, level);
}
};
Return.prototype.compileNode = function(o) {
return this.tab + ("return" + [this.expression ? " " + (this.expression.compile(o, LEVEL_PAREN)) : void 0] + ";");
};
return Return;
})(Base);
exports.Value = Value = (function(_super) {
__extends(Value, _super);
function Value(base, props, tag) {
if (!props && base instanceof Value) {
return base;
}
this.base = base;
this.properties = props || [];
if (tag) {
this[tag] = true;
}
return this;
}
Value.prototype.children = ['base', 'properties'];
Value.prototype.add = function(props) {
this.properties = this.properties.concat(props);
return this;
};
Value.prototype.hasProperties = function() {
return !!this.properties.length;
};
Value.prototype.isArray = function() {
return !this.properties.length && this.base instanceof Arr;
};
Value.prototype.isComplex = function() {
return this.hasProperties() || this.base.isComplex();
};
Value.prototype.isAssignable = function() {
return this.hasProperties() || this.base.isAssignable();
};
Value.prototype.isSimpleNumber = function() {
return this.base instanceof Literal && SIMPLENUM.test(this.base.value);
};
Value.prototype.isString = function() {
return this.base instanceof Literal && IS_STRING.test(this.base.value);
};
Value.prototype.isAtomic = function() {
var node, _i, _len, _ref2;
_ref2 = this.properties.concat(this.base);
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
node = _ref2[_i];
if (node.soak || node instanceof Call) {
return false;
}
}
return true;
};
Value.prototype.isStatement = function(o) {
return !this.properties.length && this.base.isStatement(o);
};
Value.prototype.assigns = function(name) {
return !this.properties.length && this.base.assigns(name);
};
Value.prototype.jumps = function(o) {
return !this.properties.length && this.base.jumps(o);
};
Value.prototype.isObject = function(onlyGenerated) {
if (this.properties.length) {
return false;
}
return (this.base instanceof Obj) && (!onlyGenerated || this.base.generated);
};
Value.prototype.isSplice = function() {
return last(this.properties) instanceof Slice;
};
Value.prototype.unwrap = function() {
if (this.properties.length) {
return this;
} else {
return this.base;
}
};
Value.prototype.cacheReference = function(o) {
var base, bref, name, nref;
name = last(this.properties);
if (this.properties.length < 2 && !this.base.isComplex() && !(name != null ? name.isComplex() : void 0)) {
return [this, this];
}
base = new Value(this.base, this.properties.slice(0, -1));
if (base.isComplex()) {
bref = new Literal(o.scope.freeVariable('base'));
base = new Value(new Parens(new Assign(bref, base)));
}
if (!name) {
return [base, bref];
}
if (name.isComplex()) {
nref = new Literal(o.scope.freeVariable('name'));
name = new Index(new Assign(nref, name.index));
nref = new Index(nref);
}
return [base.add(name), new Value(bref || base.base, [nref || name])];
};
Value.prototype.compileNode = function(o) {
var code, prop, props, _i, _len;
this.base.front = this.front;
props = this.properties;
code = this.base.compile(o, props.length ? LEVEL_ACCESS : null);
if ((this.base instanceof Parens || props.length) && SIMPLENUM.test(code)) {
code = "" + code + ".";
}
for (_i = 0, _len = props.length; _i < _len; _i++) {
prop = props[_i];
code += prop.compile(o);
}
return code;
};
Value.prototype.unfoldSoak = function(o) {
var result,
_this = this;
if (this.unfoldedSoak != null) {
return this.unfoldedSoak;
}
result = (function() {
var fst, i, ifn, prop, ref, snd, _i, _len, _ref2;
if (ifn = _this.base.unfoldSoak(o)) {
Array.prototype.push.apply(ifn.body.properties, _this.properties);
return ifn;
}
_ref2 = _this.properties;
for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) {
prop = _ref2[i];
if (!prop.soak) {
continue;
}
prop.soak = false;
fst = new Value(_this.base, _this.properties.slice(0, i));
snd = new Value(_this.base, _this.properties.slice(i));
if (fst.isComplex()) {
ref = new Literal(o.scope.freeVariable('ref'));
fst = new Parens(new Assign(ref, fst));
snd.base = ref;
}
return new If(new Existence(fst), snd, {
soak: true
});
}
return null;
})();
return this.unfoldedSoak = result || false;
};
return Value;
})(Base);
exports.Comment = Comment = (function(_super) {
__extends(Comment, _super);
function Comment(comment) {
this.comment = comment;
}
Comment.prototype.isStatement = YES;
Comment.prototype.makeReturn = THIS;
Comment.prototype.compileNode = function(o, level) {
var code;
code = '/*' + multident(this.comment, this.tab) + ("\n" + this.tab + "*/\n");
if ((level || o.level) === LEVEL_TOP) {
code = o.indent + code;
}
return code;
};
return Comment;
})(Base);
exports.Call = Call = (function(_super) {
__extends(Call, _super);
function Call(variable, args, soak) {
this.args = args != null ? args : [];
this.soak = soak;
this.isNew = false;
this.isSuper = variable === 'super';
this.variable = this.isSuper ? null : variable;
}
Call.prototype.children = ['variable', 'args'];
Call.prototype.newInstance = function() {
var base, _ref2;
base = ((_ref2 = this.variable) != null ? _ref2.base : void 0) || this.variable;
if (base instanceof Call && !base.isNew) {
base.newInstance();
} else {
this.isNew = true;
}
return this;
};
Call.prototype.superReference = function(o) {
var accesses, method, name;
method = o.scope.namedMethod();
if (!method) {
throw SyntaxError('cannot call super outside of a function.');
}
name = method.name;
if (name == null) {
throw SyntaxError('cannot call super on an anonymous function.');
}
if (method.klass) {
accesses = [new Access(new Literal('__super__'))];
if (method["static"]) {
accesses.push(new Access(new Literal('constructor')));
}
accesses.push(new Access(new Literal(name)));
return (new Value(new Literal(method.klass), accesses)).compile(o);
} else {
return "" + name + ".__super__.constructor";
}
};
Call.prototype.superThis = function(o) {
var method;
method = o.scope.method;
return (method && !method.klass && method.context) || "this";
};
Call.prototype.unfoldSoak = function(o) {
var call, ifn, left, list, rite, _i, _len, _ref2, _ref3;
if (this.soak) {
if (this.variable) {
if (ifn = unfoldSoak(o, this, 'variable')) {
return ifn;
}
_ref2 = new Value(this.variable).cacheReference(o), left = _ref2[0], rite = _ref2[1];
} else {
left = new Literal(this.superReference(o));
rite = new Value(left);
}
rite = new Call(rite, this.args);
rite.isNew = this.isNew;
left = new Literal("typeof " + (left.compile(o)) + " === \"function\"");
return new If(left, new Value(rite), {
soak: true
});
}
call = this;
list = [];
while (true) {
if (call.variable instanceof Call) {
list.push(call);
call = call.variable;
continue;
}
if (!(call.variable instanceof Value)) {
break;
}
list.push(call);
if (!((call = call.variable.base) instanceof Call)) {
break;
}
}
_ref3 = list.reverse();
for (_i = 0, _len = _ref3.length; _i < _len; _i++) {
call = _ref3[_i];
if (ifn) {
if (call.variable instanceof Call) {
call.variable = ifn;
} else {
call.variable.base = ifn;
}
}
ifn = unfoldSoak(o, call, 'variable');
}
return ifn;
};
Call.prototype.filterImplicitObjects = function(list) {
var node, nodes, obj, prop, properties, _i, _j, _len, _len1, _ref2;
nodes = [];
for (_i = 0, _len = list.length; _i < _len; _i++) {
node = list[_i];
if (!((typeof node.isObject === "function" ? node.isObject() : void 0) && node.base.generated)) {
nodes.push(node);
continue;
}
obj = null;
_ref2 = node.base.properties;
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
prop = _ref2[_j];
if (prop instanceof Assign || prop instanceof Comment) {
if (!obj) {
nodes.push(obj = new Obj(properties = [], true));
}
properties.push(prop);
} else {
nodes.push(prop);
obj = null;
}
}
}
return nodes;
};
Call.prototype.compileNode = function(o) {
var arg, args, code, _ref2;
if ((_ref2 = this.variable) != null) {
_ref2.front = this.front;
}
if (code = Splat.compileSplattedArray(o, this.args, true)) {
return this.compileSplat(o, code);
}
args = this.filterImplicitObjects(this.args);
args = ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = args.length; _i < _len; _i++) {
arg = args[_i];
_results.push(arg.compile(o, LEVEL_LIST));
}
return _results;
})()).join(', ');
if (this.isSuper) {
return this.superReference(o) + (".call(" + (this.superThis(o)) + (args && ', ' + args) + ")");
} else {
return (this.isNew ? 'new ' : '') + this.variable.compile(o, LEVEL_ACCESS) + ("(" + args + ")");
}
};
Call.prototype.compileSuper = function(args, o) {
return "" + (this.superReference(o)) + ".call(" + (this.superThis(o)) + (args.length ? ', ' : '') + args + ")";
};
Call.prototype.compileSplat = function(o, splatArgs) {
var base, fun, idt, name, ref;
if (this.isSuper) {
return "" + (this.superReference(o)) + ".apply(" + (this.superThis(o)) + ", " + splatArgs + ")";
}
if (this.isNew) {
idt = this.tab + TAB;
return "(function(func, args, ctor) {\n" + idt + "ctor.prototype = func.prototype;\n" + idt + "var child = new ctor, result = func.apply(child, args), t = typeof result;\n" + idt + "return t == \"object\" || t == \"function\" ? result || child : child;\n" + this.tab + "})(" + (this.variable.compile(o, LEVEL_LIST)) + ", " + splatArgs + ", function(){})";
}
base = new Value(this.variable);
if ((name = base.properties.pop()) && base.isComplex()) {
ref = o.scope.freeVariable('ref');
fun = "(" + ref + " = " + (base.compile(o, LEVEL_LIST)) + ")" + (name.compile(o));
} else {
fun = base.compile(o, LEVEL_ACCESS);
if (SIMPLENUM.test(fun)) {
fun = "(" + fun + ")";
}
if (name) {
ref = fun;
fun += name.compile(o);
} else {
ref = 'null';
}
}
return "" + fun + ".apply(" + ref + ", " + splatArgs + ")";
};
return Call;
})(Base);
exports.Extends = Extends = (function(_super) {
__extends(Extends, _super);
function Extends(child, parent) {
this.child = child;
this.parent = parent;
}
Extends.prototype.children = ['child', 'parent'];
Extends.prototype.compile = function(o) {
return new Call(new Value(new Literal(utility('extends'))), [this.child, this.parent]).compile(o);
};
return Extends;
})(Base);
exports.Access = Access = (function(_super) {
__extends(Access, _super);
function Access(name, tag) {
this.name = name;
this.name.asKey = true;
this.soak = tag === 'soak';
}
Access.prototype.children = ['name'];
Access.prototype.compile = function(o) {
var name;
name = this.name.compile(o);
if (IDENTIFIER.test(name)) {
return "." + name;
} else {
return "[" + name + "]";
}
};
Access.prototype.isComplex = NO;
return Access;
})(Base);
exports.Index = Index = (function(_super) {
__extends(Index, _super);
function Index(index) {
this.index = index;
}
Index.prototype.children = ['index'];
Index.prototype.compile = function(o) {
return "[" + (this.index.compile(o, LEVEL_PAREN)) + "]";
};
Index.prototype.isComplex = function() {
return this.index.isComplex();
};
return Index;
})(Base);
exports.Range = Range = (function(_super) {
__extends(Range, _super);
Range.prototype.children = ['from', 'to'];
function Range(from, to, tag) {
this.from = from;
this.to = to;
this.exclusive = tag === 'exclusive';
this.equals = this.exclusive ? '' : '=';
}
Range.prototype.compileVariables = function(o) {
var step, _ref2, _ref3, _ref4, _ref5;
o = merge(o, {
top: true
});
_ref2 = this.from.cache(o, LEVEL_LIST), this.fromC = _ref2[0], this.fromVar = _ref2[1];
_ref3 = this.to.cache(o, LEVEL_LIST), this.toC = _ref3[0], this.toVar = _ref3[1];
if (step = del(o, 'step')) {
_ref4 = step.cache(o, LEVEL_LIST), this.step = _ref4[0], this.stepVar = _ref4[1];
}
_ref5 = [this.fromVar.match(SIMPLENUM), this.toVar.match(SIMPLENUM)], this.fromNum = _ref5[0], this.toNum = _ref5[1];
if (this.stepVar) {
return this.stepNum = this.stepVar.match(SIMPLENUM);
}
};
Range.prototype.compileNode = function(o) {
var cond, condPart, from, gt, idx, idxName, known, lt, namedIndex, stepPart, to, varPart, _ref2, _ref3;
if (!this.fromVar) {
this.compileVariables(o);
}
if (!o.index) {
return this.compileArray(o);
}
known = this.fromNum && this.toNum;
idx = del(o, 'index');
idxName = del(o, 'name');
namedIndex = idxName && idxName !== idx;
varPart = "" + idx + " = " + this.fromC;
if (this.toC !== this.toVar) {
varPart += ", " + this.toC;
}
if (this.step !== this.stepVar) {
varPart += ", " + this.step;
}
_ref2 = ["" + idx + " <" + this.equals, "" + idx + " >" + this.equals], lt = _ref2[0], gt = _ref2[1];
condPart = this.stepNum ? +this.stepNum > 0 ? "" + lt + " " + this.toVar : "" + gt + " " + this.toVar : known ? ((_ref3 = [+this.fromNum, +this.toNum], from = _ref3[0], to = _ref3[1], _ref3), from <= to ? "" + lt + " " + to : "" + gt + " " + to) : (cond = "" + this.fromVar + " <= " + this.toVar, "" + cond + " ? " + lt + " " + this.toVar + " : " + gt + " " + this.toVar);
stepPart = this.stepVar ? "" + idx + " += " + this.stepVar : known ? namedIndex ? from <= to ? "++" + idx : "--" + idx : from <= to ? "" + idx + "++" : "" + idx + "--" : namedIndex ? "" + cond + " ? ++" + idx + " : --" + idx : "" + cond + " ? " + idx + "++ : " + idx + "--";
if (namedIndex) {
varPart = "" + idxName + " = " + varPart;
}
if (namedIndex) {
stepPart = "" + idxName + " = " + stepPart;
}
return "" + varPart + "; " + condPart + "; " + stepPart;
};
Range.prototype.compileArray = function(o) {
var args, body, cond, hasArgs, i, idt, post, pre, range, result, vars, _i, _ref2, _ref3, _results;
if (this.fromNum && this.toNum && Math.abs(this.fromNum - this.toNum) <= 20) {
range = (function() {
_results = [];
for (var _i = _ref2 = +this.fromNum, _ref3 = +this.toNum; _ref2 <= _ref3 ? _i <= _ref3 : _i >= _ref3; _ref2 <= _ref3 ? _i++ : _i--){ _results.push(_i); }
return _results;
}).apply(this);
if (this.exclusive) {
range.pop();
}
return "[" + (range.join(', ')) + "]";
}
idt = this.tab + TAB;
i = o.scope.freeVariable('i');
result = o.scope.freeVariable('results');
pre = "\n" + idt + result + " = [];";
if (this.fromNum && this.toNum) {
o.index = i;
body = this.compileNode(o);
} else {
vars = ("" + i + " = " + this.fromC) + (this.toC !== this.toVar ? ", " + this.toC : '');
cond = "" + this.fromVar + " <= " + this.toVar;
body = "var " + vars + "; " + cond + " ? " + i + " <" + this.equals + " " + this.toVar + " : " + i + " >" + this.equals + " " + this.toVar + "; " + cond + " ? " + i + "++ : " + i + "--";
}
post = "{ " + result + ".push(" + i + "); }\n" + idt + "return " + result + ";\n" + o.indent;
hasArgs = function(node) {
return node != null ? node.contains(function(n) {
return n instanceof Literal && n.value === 'arguments' && !n.asKey;
}) : void 0;
};
if (hasArgs(this.from) || hasArgs(this.to)) {
args = ', arguments';
}
return "(function() {" + pre + "\n" + idt + "for (" + body + ")" + post + "}).apply(this" + (args != null ? args : '') + ")";
};
return Range;
})(Base);
exports.Slice = Slice = (function(_super) {
__extends(Slice, _super);
Slice.prototype.children = ['range'];
function Slice(range) {
this.range = range;
Slice.__super__.constructor.call(this);
}
Slice.prototype.compileNode = function(o) {
var compiled, from, fromStr, to, toStr, _ref2;
_ref2 = this.range, to = _ref2.to, from = _ref2.from;
fromStr = from && from.compile(o, LEVEL_PAREN) || '0';
compiled = to && to.compile(o, LEVEL_PAREN);
if (to && !(!this.range.exclusive && +compiled === -1)) {
toStr = ', ' + (this.range.exclusive ? compiled : SIMPLENUM.test(compiled) ? "" + (+compiled + 1) : (compiled = to.compile(o, LEVEL_ACCESS), "" + compiled + " + 1 || 9e9"));
}
return ".slice(" + fromStr + (toStr || '') + ")";
};
return Slice;
})(Base);
exports.Obj = Obj = (function(_super) {
__extends(Obj, _super);
function Obj(props, generated) {
this.generated = generated != null ? generated : false;
this.objects = this.properties = props || [];
}
Obj.prototype.children = ['properties'];
Obj.prototype.compileNode = function(o) {
var i, idt, indent, join, lastNoncom, node, obj, prop, propName, propNames, props, _i, _j, _len, _len1, _ref2;
props = this.properties;
propNames = [];
_ref2 = this.properties;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
prop = _ref2[_i];
if (prop.isComplex()) {
prop = prop.variable;
}
if (prop != null) {
propName = prop.unwrapAll().value.toString();
if (__indexOf.call(propNames, propName) >= 0) {
throw SyntaxError("multiple object literal properties named \"" + propName + "\"");
}
propNames.push(propName);
}
}
if (!props.length) {
return (this.front ? '({})' : '{}');
}
if (this.generated) {
for (_j = 0, _len1 = props.length; _j < _len1; _j++) {
node = props[_j];
if (node instanceof Value) {
throw new Error('cannot have an implicit value in an implicit object');
}
}
}
idt = o.indent += TAB;
lastNoncom = this.lastNonComment(this.properties);
props = (function() {
var _k, _len2, _results;
_results = [];
for (i = _k = 0, _len2 = props.length; _k < _len2; i = ++_k) {
prop = props[i];
join = i === props.length - 1 ? '' : prop === lastNoncom || prop instanceof Comment ? '\n' : ',\n';
indent = prop instanceof Comment ? '' : idt;
if (prop instanceof Value && prop["this"]) {
prop = new Assign(prop.properties[0].name, prop, 'object');
}
if (!(prop instanceof Comment)) {
if (!(prop instanceof Assign)) {
prop = new Assign(prop, prop, 'object');
}
(prop.variable.base || prop.variable).asKey = true;
}
_results.push(indent + prop.compile(o, LEVEL_TOP) + join);
}
return _results;
})();
props = props.join('');
obj = "{" + (props && '\n' + props + '\n' + this.tab) + "}";
if (this.front) {
return "(" + obj + ")";
} else {
return obj;
}
};
Obj.prototype.assigns = function(name) {
var prop, _i, _len, _ref2;
_ref2 = this.properties;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
prop = _ref2[_i];
if (prop.assigns(name)) {
return true;
}
}
return false;
};
return Obj;
})(Base);
exports.Arr = Arr = (function(_super) {
__extends(Arr, _super);
function Arr(objs) {
this.objects = objs || [];
}
Arr.prototype.children = ['objects'];
Arr.prototype.filterImplicitObjects = Call.prototype.filterImplicitObjects;
Arr.prototype.compileNode = function(o) {
var code, obj, objs;
if (!this.objects.length) {
return '[]';
}
o.indent += TAB;
objs = this.filterImplicitObjects(this.objects);
if (code = Splat.compileSplattedArray(o, objs)) {
return code;
}
code = ((function() {
var _i, _len, _results;
_results = [];
for (_i = 0, _len = objs.length; _i < _len; _i++) {
obj = objs[_i];
_results.push(obj.compile(o, LEVEL_LIST));
}
return _results;
})()).join(', ');
if (code.indexOf('\n') >= 0) {
return "[\n" + o.indent + code + "\n" + this.tab + "]";
} else {
return "[" + code + "]";
}
};
Arr.prototype.assigns = function(name) {
var obj, _i, _len, _ref2;
_ref2 = this.objects;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
obj = _ref2[_i];
if (obj.assigns(name)) {
return true;
}
}
return false;
};
return Arr;
})(Base);
exports.Class = Class = (function(_super) {
__extends(Class, _super);
function Class(variable, parent, body) {
this.variable = variable;
this.parent = parent;
this.body = body != null ? body : new Block;
this.boundFuncs = [];
this.body.classBody = true;
}
Class.prototype.children = ['variable', 'parent', 'body'];
Class.prototype.determineName = function() {
var decl, tail;
if (!this.variable) {
return null;
}
decl = (tail = last(this.variable.properties)) ? tail instanceof Access && tail.name.value : this.variable.base.value;
if (__indexOf.call(STRICT_PROSCRIBED, decl) >= 0) {
throw SyntaxError("variable name may not be " + decl);
}
return decl && (decl = IDENTIFIER.test(decl) && decl);
};
Class.prototype.setContext = function(name) {
return this.body.traverseChildren(false, function(node) {
if (node.classBody) {
return false;
}
if (node instanceof Literal && node.value === 'this') {
return node.value = name;
} else if (node instanceof Code) {
node.klass = name;
if (node.bound) {
return node.context = name;
}
}
});
};
Class.prototype.addBoundFunctions = function(o) {
var bvar, lhs, _i, _len, _ref2, _results;
if (this.boundFuncs.length) {
_ref2 = this.boundFuncs;
_results = [];
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
bvar = _ref2[_i];
lhs = (new Value(new Literal("this"), [new Access(bvar)])).compile(o);
_results.push(this.ctor.body.unshift(new Literal("" + lhs + " = " + (utility('bind')) + "(" + lhs + ", this)")));
}
return _results;
}
};
Class.prototype.addProperties = function(node, name, o) {
var assign, base, exprs, func, props;
props = node.base.properties.slice(0);
exprs = (function() {
var _results;
_results = [];
while (assign = props.shift()) {
if (assign instanceof Assign) {
base = assign.variable.base;
delete assign.context;
func = assign.value;
if (base.value === 'constructor') {
if (this.ctor) {
throw new Error('cannot define more than one constructor in a class');
}
if (func.bound) {
throw new Error('cannot define a constructor as a bound function');
}
if (func instanceof Code) {
assign = this.ctor = func;
} else {
this.externalCtor = o.scope.freeVariable('class');
assign = new Assign(new Literal(this.externalCtor), func);
}
} else {
if (assign.variable["this"]) {
func["static"] = true;
if (func.bound) {
func.context = name;
}
} else {
assign.variable = new Value(new Literal(name), [new Access(new Literal('prototype')), new Access(base)]);
if (func instanceof Code && func.bound) {
this.boundFuncs.push(base);
func.bound = false;
}
}
}
}
_results.push(assign);
}
return _results;
}).call(this);
return compact(exprs);
};
Class.prototype.walkBody = function(name, o) {
var _this = this;
return this.traverseChildren(false, function(child) {
var exps, i, node, _i, _len, _ref2;
if (child instanceof Class) {
return false;
}
if (child instanceof Block) {
_ref2 = exps = child.expressions;
for (i = _i = 0, _len = _ref2.length; _i < _len; i = ++_i) {
node = _ref2[i];
if (node instanceof Value && node.isObject(true)) {
exps[i] = _this.addProperties(node, name, o);
}
}
return child.expressions = exps = flatten(exps);
}
});
};
Class.prototype.hoistDirectivePrologue = function() {
var expressions, index, node;
index = 0;
expressions = this.body.expressions;
while ((node = expressions[index]) && node instanceof Comment || node instanceof Value && node.isString()) {
++index;
}
return this.directives = expressions.splice(0, index);
};
Class.prototype.ensureConstructor = function(name) {
if (!this.ctor) {
this.ctor = new Code;
if (this.parent) {
this.ctor.body.push(new Literal("" + name + ".__super__.constructor.apply(this, arguments)"));
}
if (this.externalCtor) {
this.ctor.body.push(new Literal("" + this.externalCtor + ".apply(this, arguments)"));
}
this.ctor.body.makeReturn();
this.body.expressions.unshift(this.ctor);
}
this.ctor.ctor = this.ctor.name = name;
this.ctor.klass = null;
return this.ctor.noReturn = true;
};
Class.prototype.compileNode = function(o) {
var call, decl, klass, lname, name, params, _ref2;
decl = this.determineName();
name = decl || '_Class';
if (name.reserved) {
name = "_" + name;
}
lname = new Literal(name);
this.hoistDirectivePrologue();
this.setContext(name);
this.walkBody(name, o);
this.ensureConstructor(name);
this.body.spaced = true;
if (!(this.ctor instanceof Code)) {
this.body.expressions.unshift(this.ctor);
}
this.body.expressions.push(lname);
(_ref2 = this.body.expressions).unshift.apply(_ref2, this.directives);
this.addBoundFunctions(o);
call = Closure.wrap(this.body);
if (this.parent) {
this.superClass = new Literal(o.scope.freeVariable('super', false));
this.body.expressions.unshift(new Extends(lname, this.superClass));
call.args.push(this.parent);
params = call.variable.params || call.variable.base.params;
params.push(new Param(this.superClass));
}
klass = new Parens(call, true);
if (this.variable) {
klass = new Assign(this.variable, klass);
}
return klass.compile(o);
};
return Class;
})(Base);
exports.Assign = Assign = (function(_super) {
__extends(Assign, _super);
function Assign(variable, value, context, options) {
var forbidden, name, _ref2;
this.variable = variable;
this.value = value;
this.context = context;
this.param = options && options.param;
this.subpattern = options && options.subpattern;
forbidden = (_ref2 = (name = this.variable.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0);
if (forbidden && this.context !== 'object') {
throw SyntaxError("variable name may not be \"" + name + "\"");
}
}
Assign.prototype.children = ['variable', 'value'];
Assign.prototype.isStatement = function(o) {
return (o != null ? o.level : void 0) === LEVEL_TOP && (this.context != null) && __indexOf.call(this.context, "?") >= 0;
};
Assign.prototype.assigns = function(name) {
return this[this.context === 'object' ? 'value' : 'variable'].assigns(name);
};
Assign.prototype.unfoldSoak = function(o) {
return unfoldSoak(o, this, 'variable');
};
Assign.prototype.compileNode = function(o) {
var isValue, match, name, val, varBase, _ref2, _ref3, _ref4, _ref5;
if (isValue = this.variable instanceof Value) {
if (this.variable.isArray() || this.variable.isObject()) {
return this.compilePatternMatch(o);
}
if (this.variable.isSplice()) {
return this.compileSplice(o);
}
if ((_ref2 = this.context) === '||=' || _ref2 === '&&=' || _ref2 === '?=') {
return this.compileConditional(o);
}
}
name = this.variable.compile(o, LEVEL_LIST);
if (!this.context) {
if (!(varBase = this.variable.unwrapAll()).isAssignable()) {
throw SyntaxError("\"" + (this.variable.compile(o)) + "\" cannot be assigned.");
}
if (!(typeof varBase.hasProperties === "function" ? varBase.hasProperties() : void 0)) {
if (this.param) {
o.scope.add(name, 'var');
} else {
o.scope.find(name);
}
}
}
if (this.value instanceof Code && (match = METHOD_DEF.exec(name))) {
if (match[1]) {
this.value.klass = match[1];
}
this.value.name = (_ref3 = (_ref4 = (_ref5 = match[2]) != null ? _ref5 : match[3]) != null ? _ref4 : match[4]) != null ? _ref3 : match[5];
}
val = this.value.compile(o, LEVEL_LIST);
if (this.context === 'object') {
return "" + name + ": " + val;
}
val = name + (" " + (this.context || '=') + " ") + val;
if (o.level <= LEVEL_LIST) {
return val;
} else {
return "(" + val + ")";
}
};
Assign.prototype.compilePatternMatch = function(o) {
var acc, assigns, code, i, idx, isObject, ivar, name, obj, objects, olen, ref, rest, splat, top, val, value, vvar, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8;
top = o.level === LEVEL_TOP;
value = this.value;
objects = this.variable.base.objects;
if (!(olen = objects.length)) {
code = value.compile(o);
if (o.level >= LEVEL_OP) {
return "(" + code + ")";
} else {
return code;
}
}
isObject = this.variable.isObject();
if (top && olen === 1 && !((obj = objects[0]) instanceof Splat)) {
if (obj instanceof Assign) {
_ref2 = obj, (_ref3 = _ref2.variable, idx = _ref3.base), obj = _ref2.value;
} else {
if (obj.base instanceof Parens) {
_ref4 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref4[0], idx = _ref4[1];
} else {
idx = isObject ? obj["this"] ? obj.properties[0].name : obj : new Literal(0);
}
}
acc = IDENTIFIER.test(idx.unwrap().value || 0);
value = new Value(value);
value.properties.push(new (acc ? Access : Index)(idx));
if (_ref5 = obj.unwrap().value, __indexOf.call(RESERVED, _ref5) >= 0) {
throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (value.compile(o)));
}
return new Assign(obj, value, null, {
param: this.param
}).compile(o, LEVEL_TOP);
}
vvar = value.compile(o, LEVEL_LIST);
assigns = [];
splat = false;
if (!IDENTIFIER.test(vvar) || this.variable.assigns(vvar)) {
assigns.push("" + (ref = o.scope.freeVariable('ref')) + " = " + vvar);
vvar = ref;
}
for (i = _i = 0, _len = objects.length; _i < _len; i = ++_i) {
obj = objects[i];
idx = i;
if (isObject) {
if (obj instanceof Assign) {
_ref6 = obj, (_ref7 = _ref6.variable, idx = _ref7.base), obj = _ref6.value;
} else {
if (obj.base instanceof Parens) {
_ref8 = new Value(obj.unwrapAll()).cacheReference(o), obj = _ref8[0], idx = _ref8[1];
} else {
idx = obj["this"] ? obj.properties[0].name : obj;
}
}
}
if (!splat && obj instanceof Splat) {
name = obj.name.unwrap().value;
obj = obj.unwrap();
val = "" + olen + " <= " + vvar + ".length ? " + (utility('slice')) + ".call(" + vvar + ", " + i;
if (rest = olen - i - 1) {
ivar = o.scope.freeVariable('i');
val += ", " + ivar + " = " + vvar + ".length - " + rest + ") : (" + ivar + " = " + i + ", [])";
} else {
val += ") : []";
}
val = new Literal(val);
splat = "" + ivar + "++";
} else {
name = obj.unwrap().value;
if (obj instanceof Splat) {
obj = obj.name.compile(o);
throw new SyntaxError("multiple splats are disallowed in an assignment: " + obj + "...");
}
if (typeof idx === 'number') {
idx = new Literal(splat || idx);
acc = false;
} else {
acc = isObject && IDENTIFIER.test(idx.unwrap().value || 0);
}
val = new Value(new Literal(vvar), [new (acc ? Access : Index)(idx)]);
}
if ((name != null) && __indexOf.call(RESERVED, name) >= 0) {
throw new SyntaxError("assignment to a reserved word: " + (obj.compile(o)) + " = " + (val.compile(o)));
}
assigns.push(new Assign(obj, val, null, {
param: this.param,
subpattern: true
}).compile(o, LEVEL_LIST));
}
if (!(top || this.subpattern)) {
assigns.push(vvar);
}
code = assigns.join(', ');
if (o.level < LEVEL_LIST) {
return code;
} else {
return "(" + code + ")";
}
};
Assign.prototype.compileConditional = function(o) {
var left, right, _ref2;
_ref2 = this.variable.cacheReference(o), left = _ref2[0], right = _ref2[1];
if (!left.properties.length && left.base instanceof Literal && left.base.value !== "this" && !o.scope.check(left.base.value)) {
throw new Error("the variable \"" + left.base.value + "\" can't be assigned with " + this.context + " because it has not been defined.");
}
if (__indexOf.call(this.context, "?") >= 0) {
o.isExistentialEquals = true;
}
return new Op(this.context.slice(0, -1), left, new Assign(right, this.value, '=')).compile(o);
};
Assign.prototype.compileSplice = function(o) {
var code, exclusive, from, fromDecl, fromRef, name, to, valDef, valRef, _ref2, _ref3, _ref4;
_ref2 = this.variable.properties.pop().range, from = _ref2.from, to = _ref2.to, exclusive = _ref2.exclusive;
name = this.variable.compile(o);
_ref3 = (from != null ? from.cache(o, LEVEL_OP) : void 0) || ['0', '0'], fromDecl = _ref3[0], fromRef = _ref3[1];
if (to) {
if ((from != null ? from.isSimpleNumber() : void 0) && to.isSimpleNumber()) {
to = +to.compile(o) - +fromRef;
if (!exclusive) {
to += 1;
}
} else {
to = to.compile(o, LEVEL_ACCESS) + ' - ' + fromRef;
if (!exclusive) {
to += ' + 1';
}
}
} else {
to = "9e9";
}
_ref4 = this.value.cache(o, LEVEL_LIST), valDef = _ref4[0], valRef = _ref4[1];
code = "[].splice.apply(" + name + ", [" + fromDecl + ", " + to + "].concat(" + valDef + ")), " + valRef;
if (o.level > LEVEL_TOP) {
return "(" + code + ")";
} else {
return code;
}
};
return Assign;
})(Base);
exports.Code = Code = (function(_super) {
__extends(Code, _super);
function Code(params, body, tag) {
this.params = params || [];
this.body = body || new Block;
this.bound = tag === 'boundfunc';
if (this.bound) {
this.context = '_this';
}
}
Code.prototype.children = ['params', 'body'];
Code.prototype.isStatement = function() {
return !!this.ctor;
};
Code.prototype.jumps = NO;
Code.prototype.compileNode = function(o) {
var code, exprs, i, idt, lit, name, p, param, params, ref, splats, uniqs, val, wasEmpty, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _len5, _m, _n, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7, _ref8;
o.scope = new Scope(o.scope, this.body, this);
o.scope.shared = del(o, 'sharedScope');
o.indent += TAB;
delete o.bare;
delete o.isExistentialEquals;
params = [];
exprs = [];
_ref2 = this.paramNames();
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
name = _ref2[_i];
if (!o.scope.check(name)) {
o.scope.parameter(name);
}
}
_ref3 = this.params;
for (_j = 0, _len1 = _ref3.length; _j < _len1; _j++) {
param = _ref3[_j];
if (!param.splat) {
continue;
}
_ref4 = this.params;
for (_k = 0, _len2 = _ref4.length; _k < _len2; _k++) {
p = _ref4[_k].name;
if (p["this"]) {
p = p.properties[0].name;
}
if (p.value) {
o.scope.add(p.value, 'var', true);
}
}
splats = new Assign(new Value(new Arr((function() {
var _l, _len3, _ref5, _results;
_ref5 = this.params;
_results = [];
for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) {
p = _ref5[_l];
_results.push(p.asReference(o));
}
return _results;
}).call(this))), new Value(new Literal('arguments')));
break;
}
_ref5 = this.params;
for (_l = 0, _len3 = _ref5.length; _l < _len3; _l++) {
param = _ref5[_l];
if (param.isComplex()) {
val = ref = param.asReference(o);
if (param.value) {
val = new Op('?', ref, param.value);
}
exprs.push(new Assign(new Value(param.name), val, '=', {
param: true
}));
} else {
ref = param;
if (param.value) {
lit = new Literal(ref.name.value + ' == null');
val = new Assign(new Value(param.name), param.value, '=');
exprs.push(new If(lit, val));
}
}
if (!splats) {
params.push(ref);
}
}
wasEmpty = this.body.isEmpty();
if (splats) {
exprs.unshift(splats);
}
if (exprs.length) {
(_ref6 = this.body.expressions).unshift.apply(_ref6, exprs);
}
for (i = _m = 0, _len4 = params.length; _m < _len4; i = ++_m) {
p = params[i];
o.scope.parameter(params[i] = p.compile(o));
}
uniqs = [];
_ref7 = this.paramNames();
for (_n = 0, _len5 = _ref7.length; _n < _len5; _n++) {
name = _ref7[_n];
if (__indexOf.call(uniqs, name) >= 0) {
throw SyntaxError("multiple parameters named '" + name + "'");
}
uniqs.push(name);
}
if (!(wasEmpty || this.noReturn)) {
this.body.makeReturn();
}
if (this.bound) {
if ((_ref8 = o.scope.parent.method) != null ? _ref8.bound : void 0) {
this.bound = this.context = o.scope.parent.method.context;
} else if (!this["static"]) {
o.scope.parent.assign('_this', 'this');
}
}
idt = o.indent;
code = 'function';
if (this.ctor) {
code += ' ' + this.name;
}
code += '(' + params.join(', ') + ') {';
if (!this.body.isEmpty()) {
code += "\n" + (this.body.compileWithDeclarations(o)) + "\n" + this.tab;
}
code += '}';
if (this.ctor) {
return this.tab + code;
}
if (this.front || (o.level >= LEVEL_ACCESS)) {
return "(" + code + ")";
} else {
return code;
}
};
Code.prototype.paramNames = function() {
var names, param, _i, _len, _ref2;
names = [];
_ref2 = this.params;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
param = _ref2[_i];
names.push.apply(names, param.names());
}
return names;
};
Code.prototype.traverseChildren = function(crossScope, func) {
if (crossScope) {
return Code.__super__.traverseChildren.call(this, crossScope, func);
}
};
return Code;
})(Base);
exports.Param = Param = (function(_super) {
__extends(Param, _super);
function Param(name, value, splat) {
var _ref2;
this.name = name;
this.value = value;
this.splat = splat;
if (_ref2 = (name = this.name.unwrapAll().value), __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) {
throw SyntaxError("parameter name \"" + name + "\" is not allowed");
}
}
Param.prototype.children = ['name', 'value'];
Param.prototype.compile = function(o) {
return this.name.compile(o, LEVEL_LIST);
};
Param.prototype.asReference = function(o) {
var node;
if (this.reference) {
return this.reference;
}
node = this.name;
if (node["this"]) {
node = node.properties[0].name;
if (node.value.reserved) {
node = new Literal(o.scope.freeVariable(node.value));
}
} else if (node.isComplex()) {
node = new Literal(o.scope.freeVariable('arg'));
}
node = new Value(node);
if (this.splat) {
node = new Splat(node);
}
return this.reference = node;
};
Param.prototype.isComplex = function() {
return this.name.isComplex();
};
Param.prototype.names = function(name) {
var atParam, names, obj, _i, _len, _ref2;
if (name == null) {
name = this.name;
}
atParam = function(obj) {
var value;
value = obj.properties[0].name.value;
if (value.reserved) {
return [];
} else {
return [value];
}
};
if (name instanceof Literal) {
return [name.value];
}
if (name instanceof Value) {
return atParam(name);
}
names = [];
_ref2 = name.objects;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
obj = _ref2[_i];
if (obj instanceof Assign) {
names.push(obj.value.unwrap().value);
} else if (obj instanceof Splat) {
names.push(obj.name.unwrap().value);
} else if (obj instanceof Value) {
if (obj.isArray() || obj.isObject()) {
names.push.apply(names, this.names(obj.base));
} else if (obj["this"]) {
names.push.apply(names, atParam(obj));
} else {
names.push(obj.base.value);
}
} else {
throw SyntaxError("illegal parameter " + (obj.compile()));
}
}
return names;
};
return Param;
})(Base);
exports.Splat = Splat = (function(_super) {
__extends(Splat, _super);
Splat.prototype.children = ['name'];
Splat.prototype.isAssignable = YES;
function Splat(name) {
this.name = name.compile ? name : new Literal(name);
}
Splat.prototype.assigns = function(name) {
return this.name.assigns(name);
};
Splat.prototype.compile = function(o) {
if (this.index != null) {
return this.compileParam(o);
} else {
return this.name.compile(o);
}
};
Splat.prototype.unwrap = function() {
return this.name;
};
Splat.compileSplattedArray = function(o, list, apply) {
var args, base, code, i, index, node, _i, _len;
index = -1;
while ((node = list[++index]) && !(node instanceof Splat)) {
continue;
}
if (index >= list.length) {
return '';
}
if (list.length === 1) {
code = list[0].compile(o, LEVEL_LIST);
if (apply) {
return code;
}
return "" + (utility('slice')) + ".call(" + code + ")";
}
args = list.slice(index);
for (i = _i = 0, _len = args.length; _i < _len; i = ++_i) {
node = args[i];
code = node.compile(o, LEVEL_LIST);
args[i] = node instanceof Splat ? "" + (utility('slice')) + ".call(" + code + ")" : "[" + code + "]";
}
if (index === 0) {
return args[0] + (".concat(" + (args.slice(1).join(', ')) + ")");
}
base = (function() {
var _j, _len1, _ref2, _results;
_ref2 = list.slice(0, index);
_results = [];
for (_j = 0, _len1 = _ref2.length; _j < _len1; _j++) {
node = _ref2[_j];
_results.push(node.compile(o, LEVEL_LIST));
}
return _results;
})();
return "[" + (base.join(', ')) + "].concat(" + (args.join(', ')) + ")";
};
return Splat;
})(Base);
exports.While = While = (function(_super) {
__extends(While, _super);
function While(condition, options) {
this.condition = (options != null ? options.invert : void 0) ? condition.invert() : condition;
this.guard = options != null ? options.guard : void 0;
}
While.prototype.children = ['condition', 'guard', 'body'];
While.prototype.isStatement = YES;
While.prototype.makeReturn = function(res) {
if (res) {
return While.__super__.makeReturn.apply(this, arguments);
} else {
this.returns = !this.jumps({
loop: true
});
return this;
}
};
While.prototype.addBody = function(body) {
this.body = body;
return this;
};
While.prototype.jumps = function() {
var expressions, node, _i, _len;
expressions = this.body.expressions;
if (!expressions.length) {
return false;
}
for (_i = 0, _len = expressions.length; _i < _len; _i++) {
node = expressions[_i];
if (node.jumps({
loop: true
})) {
return node;
}
}
return false;
};
While.prototype.compileNode = function(o) {
var body, code, rvar, set;
o.indent += TAB;
set = '';
body = this.body;
if (body.isEmpty()) {
body = '';
} else {
if (this.returns) {
body.makeReturn(rvar = o.scope.freeVariable('results'));
set = "" + this.tab + rvar + " = [];\n";
}
if (this.guard) {
if (body.expressions.length > 1) {
body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue")));
} else {
if (this.guard) {
body = Block.wrap([new If(this.guard, body)]);
}
}
}
body = "\n" + (body.compile(o, LEVEL_TOP)) + "\n" + this.tab;
}
code = set + this.tab + ("while (" + (this.condition.compile(o, LEVEL_PAREN)) + ") {" + body + "}");
if (this.returns) {
code += "\n" + this.tab + "return " + rvar + ";";
}
return code;
};
return While;
})(Base);
exports.Op = Op = (function(_super) {
var CONVERSIONS, INVERSIONS;
__extends(Op, _super);
function Op(op, first, second, flip) {
if (op === 'in') {
return new In(first, second);
}
if (op === 'do') {
return this.generateDo(first);
}
if (op === 'new') {
if (first instanceof Call && !first["do"] && !first.isNew) {
return first.newInstance();
}
if (first instanceof Code && first.bound || first["do"]) {
first = new Parens(first);
}
}
this.operator = CONVERSIONS[op] || op;
this.first = first;
this.second = second;
this.flip = !!flip;
return this;
}
CONVERSIONS = {
'==': '===',
'!=': '!==',
'of': 'in'
};
INVERSIONS = {
'!==': '===',
'===': '!=='
};
Op.prototype.children = ['first', 'second'];
Op.prototype.isSimpleNumber = NO;
Op.prototype.isUnary = function() {
return !this.second;
};
Op.prototype.isComplex = function() {
var _ref2;
return !(this.isUnary() && ((_ref2 = this.operator) === '+' || _ref2 === '-')) || this.first.isComplex();
};
Op.prototype.isChainable = function() {
var _ref2;
return (_ref2 = this.operator) === '<' || _ref2 === '>' || _ref2 === '>=' || _ref2 === '<=' || _ref2 === '===' || _ref2 === '!==';
};
Op.prototype.invert = function() {
var allInvertable, curr, fst, op, _ref2;
if (this.isChainable() && this.first.isChainable()) {
allInvertable = true;
curr = this;
while (curr && curr.operator) {
allInvertable && (allInvertable = curr.operator in INVERSIONS);
curr = curr.first;
}
if (!allInvertable) {
return new Parens(this).invert();
}
curr = this;
while (curr && curr.operator) {
curr.invert = !curr.invert;
curr.operator = INVERSIONS[curr.operator];
curr = curr.first;
}
return this;
} else if (op = INVERSIONS[this.operator]) {
this.operator = op;
if (this.first.unwrap() instanceof Op) {
this.first.invert();
}
return this;
} else if (this.second) {
return new Parens(this).invert();
} else if (this.operator === '!' && (fst = this.first.unwrap()) instanceof Op && ((_ref2 = fst.operator) === '!' || _ref2 === 'in' || _ref2 === 'instanceof')) {
return fst;
} else {
return new Op('!', this);
}
};
Op.prototype.unfoldSoak = function(o) {
var _ref2;
return ((_ref2 = this.operator) === '++' || _ref2 === '--' || _ref2 === 'delete') && unfoldSoak(o, this, 'first');
};
Op.prototype.generateDo = function(exp) {
var call, func, param, passedParams, ref, _i, _len, _ref2;
passedParams = [];
func = exp instanceof Assign && (ref = exp.value.unwrap()) instanceof Code ? ref : exp;
_ref2 = func.params || [];
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
param = _ref2[_i];
if (param.value) {
passedParams.push(param.value);
delete param.value;
} else {
passedParams.push(param);
}
}
call = new Call(exp, passedParams);
call["do"] = true;
return call;
};
Op.prototype.compileNode = function(o) {
var code, isChain, _ref2, _ref3;
isChain = this.isChainable() && this.first.isChainable();
if (!isChain) {
this.first.front = this.front;
}
if (this.operator === 'delete' && o.scope.check(this.first.unwrapAll().value)) {
throw SyntaxError('delete operand may not be argument or var');
}
if (((_ref2 = this.operator) === '--' || _ref2 === '++') && (_ref3 = this.first.unwrapAll().value, __indexOf.call(STRICT_PROSCRIBED, _ref3) >= 0)) {
throw SyntaxError('prefix increment/decrement may not have eval or arguments operand');
}
if (this.isUnary()) {
return this.compileUnary(o);
}
if (isChain) {
return this.compileChain(o);
}
if (this.operator === '?') {
return this.compileExistence(o);
}
code = this.first.compile(o, LEVEL_OP) + ' ' + this.operator + ' ' + this.second.compile(o, LEVEL_OP);
if (o.level <= LEVEL_OP) {
return code;
} else {
return "(" + code + ")";
}
};
Op.prototype.compileChain = function(o) {
var code, fst, shared, _ref2;
_ref2 = this.first.second.cache(o), this.first.second = _ref2[0], shared = _ref2[1];
fst = this.first.compile(o, LEVEL_OP);
code = "" + fst + " " + (this.invert ? '&&' : '||') + " " + (shared.compile(o)) + " " + this.operator + " " + (this.second.compile(o, LEVEL_OP));
return "(" + code + ")";
};
Op.prototype.compileExistence = function(o) {
var fst, ref;
if (this.first.isComplex()) {
ref = new Literal(o.scope.freeVariable('ref'));
fst = new Parens(new Assign(ref, this.first));
} else {
fst = this.first;
ref = fst;
}
return new If(new Existence(fst), ref, {
type: 'if'
}).addElse(this.second).compile(o);
};
Op.prototype.compileUnary = function(o) {
var op, parts, plusMinus;
if (o.level >= LEVEL_ACCESS) {
return (new Parens(this)).compile(o);
}
parts = [op = this.operator];
plusMinus = op === '+' || op === '-';
if ((op === 'new' || op === 'typeof' || op === 'delete') || plusMinus && this.first instanceof Op && this.first.operator === op) {
parts.push(' ');
}
if ((plusMinus && this.first instanceof Op) || (op === 'new' && this.first.isStatement(o))) {
this.first = new Parens(this.first);
}
parts.push(this.first.compile(o, LEVEL_OP));
if (this.flip) {
parts.reverse();
}
return parts.join('');
};
Op.prototype.toString = function(idt) {
return Op.__super__.toString.call(this, idt, this.constructor.name + ' ' + this.operator);
};
return Op;
})(Base);
exports.In = In = (function(_super) {
__extends(In, _super);
function In(object, array) {
this.object = object;
this.array = array;
}
In.prototype.children = ['object', 'array'];
In.prototype.invert = NEGATE;
In.prototype.compileNode = function(o) {
var hasSplat, obj, _i, _len, _ref2;
if (this.array instanceof Value && this.array.isArray()) {
_ref2 = this.array.base.objects;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
obj = _ref2[_i];
if (!(obj instanceof Splat)) {
continue;
}
hasSplat = true;
break;
}
if (!hasSplat) {
return this.compileOrTest(o);
}
}
return this.compileLoopTest(o);
};
In.prototype.compileOrTest = function(o) {
var cmp, cnj, i, item, ref, sub, tests, _ref2, _ref3;
if (this.array.base.objects.length === 0) {
return "" + (!!this.negated);
}
_ref2 = this.object.cache(o, LEVEL_OP), sub = _ref2[0], ref = _ref2[1];
_ref3 = this.negated ? [' !== ', ' && '] : [' === ', ' || '], cmp = _ref3[0], cnj = _ref3[1];
tests = (function() {
var _i, _len, _ref4, _results;
_ref4 = this.array.base.objects;
_results = [];
for (i = _i = 0, _len = _ref4.length; _i < _len; i = ++_i) {
item = _ref4[i];
_results.push((i ? ref : sub) + cmp + item.compile(o, LEVEL_ACCESS));
}
return _results;
}).call(this);
tests = tests.join(cnj);
if (o.level < LEVEL_OP) {
return tests;
} else {
return "(" + tests + ")";
}
};
In.prototype.compileLoopTest = function(o) {
var code, ref, sub, _ref2;
_ref2 = this.object.cache(o, LEVEL_LIST), sub = _ref2[0], ref = _ref2[1];
code = utility('indexOf') + (".call(" + (this.array.compile(o, LEVEL_LIST)) + ", " + ref + ") ") + (this.negated ? '< 0' : '>= 0');
if (sub === ref) {
return code;
}
code = sub + ', ' + code;
if (o.level < LEVEL_LIST) {
return code;
} else {
return "(" + code + ")";
}
};
In.prototype.toString = function(idt) {
return In.__super__.toString.call(this, idt, this.constructor.name + (this.negated ? '!' : ''));
};
return In;
})(Base);
exports.Try = Try = (function(_super) {
__extends(Try, _super);
function Try(attempt, error, recovery, ensure) {
this.attempt = attempt;
this.error = error;
this.recovery = recovery;
this.ensure = ensure;
}
Try.prototype.children = ['attempt', 'recovery', 'ensure'];
Try.prototype.isStatement = YES;
Try.prototype.jumps = function(o) {
var _ref2;
return this.attempt.jumps(o) || ((_ref2 = this.recovery) != null ? _ref2.jumps(o) : void 0);
};
Try.prototype.makeReturn = function(res) {
if (this.attempt) {
this.attempt = this.attempt.makeReturn(res);
}
if (this.recovery) {
this.recovery = this.recovery.makeReturn(res);
}
return this;
};
Try.prototype.compileNode = function(o) {
var catchPart, ensurePart, errorPart, tryPart;
o.indent += TAB;
errorPart = this.error ? " (" + (this.error.compile(o)) + ") " : ' ';
tryPart = this.attempt.compile(o, LEVEL_TOP);
catchPart = (function() {
var _ref2;
if (this.recovery) {
if (_ref2 = this.error.value, __indexOf.call(STRICT_PROSCRIBED, _ref2) >= 0) {
throw SyntaxError("catch variable may not be \"" + this.error.value + "\"");
}
if (!o.scope.check(this.error.value)) {
o.scope.add(this.error.value, 'param');
}
return " catch" + errorPart + "{\n" + (this.recovery.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}";
} else if (!(this.ensure || this.recovery)) {
return ' catch (_error) {}';
}
}).call(this);
ensurePart = this.ensure ? " finally {\n" + (this.ensure.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}" : '';
return "" + this.tab + "try {\n" + tryPart + "\n" + this.tab + "}" + (catchPart || '') + ensurePart;
};
return Try;
})(Base);
exports.Throw = Throw = (function(_super) {
__extends(Throw, _super);
function Throw(expression) {
this.expression = expression;
}
Throw.prototype.children = ['expression'];
Throw.prototype.isStatement = YES;
Throw.prototype.jumps = NO;
Throw.prototype.makeReturn = THIS;
Throw.prototype.compileNode = function(o) {
return this.tab + ("throw " + (this.expression.compile(o)) + ";");
};
return Throw;
})(Base);
exports.Existence = Existence = (function(_super) {
__extends(Existence, _super);
function Existence(expression) {
this.expression = expression;
}
Existence.prototype.children = ['expression'];
Existence.prototype.invert = NEGATE;
Existence.prototype.compileNode = function(o) {
var cmp, cnj, code, _ref2;
this.expression.front = this.front;
code = this.expression.compile(o, LEVEL_OP);
if (IDENTIFIER.test(code) && !o.scope.check(code)) {
_ref2 = this.negated ? ['===', '||'] : ['!==', '&&'], cmp = _ref2[0], cnj = _ref2[1];
code = "typeof " + code + " " + cmp + " \"undefined\" " + cnj + " " + code + " " + cmp + " null";
} else {
code = "" + code + " " + (this.negated ? '==' : '!=') + " null";
}
if (o.level <= LEVEL_COND) {
return code;
} else {
return "(" + code + ")";
}
};
return Existence;
})(Base);
exports.Parens = Parens = (function(_super) {
__extends(Parens, _super);
function Parens(body) {
this.body = body;
}
Parens.prototype.children = ['body'];
Parens.prototype.unwrap = function() {
return this.body;
};
Parens.prototype.isComplex = function() {
return this.body.isComplex();
};
Parens.prototype.compileNode = function(o) {
var bare, code, expr;
expr = this.body.unwrap();
if (expr instanceof Value && expr.isAtomic()) {
expr.front = this.front;
return expr.compile(o);
}
code = expr.compile(o, LEVEL_PAREN);
bare = o.level < LEVEL_OP && (expr instanceof Op || expr instanceof Call || (expr instanceof For && expr.returns));
if (bare) {
return code;
} else {
return "(" + code + ")";
}
};
return Parens;
})(Base);
exports.For = For = (function(_super) {
__extends(For, _super);
function For(body, source) {
var _ref2;
this.source = source.source, this.guard = source.guard, this.step = source.step, this.name = source.name, this.index = source.index;
this.body = Block.wrap([body]);
this.own = !!source.own;
this.object = !!source.object;
if (this.object) {
_ref2 = [this.index, this.name], this.name = _ref2[0], this.index = _ref2[1];
}
if (this.index instanceof Value) {
throw SyntaxError('index cannot be a pattern matching expression');
}
this.range = this.source instanceof Value && this.source.base instanceof Range && !this.source.properties.length;
this.pattern = this.name instanceof Value;
if (this.range && this.index) {
throw SyntaxError('indexes do not apply to range loops');
}
if (this.range && this.pattern) {
throw SyntaxError('cannot pattern match over range loops');
}
this.returns = false;
}
For.prototype.children = ['body', 'source', 'guard', 'step'];
For.prototype.compileNode = function(o) {
var body, defPart, forPart, forVarPart, guardPart, idt1, index, ivar, kvar, kvarAssign, lastJumps, lvar, name, namePart, ref, resultPart, returnResult, rvar, scope, source, stepPart, stepvar, svar, varPart, _ref2;
body = Block.wrap([this.body]);
lastJumps = (_ref2 = last(body.expressions)) != null ? _ref2.jumps() : void 0;
if (lastJumps && lastJumps instanceof Return) {
this.returns = false;
}
source = this.range ? this.source.base : this.source;
scope = o.scope;
name = this.name && this.name.compile(o, LEVEL_LIST);
index = this.index && this.index.compile(o, LEVEL_LIST);
if (name && !this.pattern) {
scope.find(name);
}
if (index) {
scope.find(index);
}
if (this.returns) {
rvar = scope.freeVariable('results');
}
ivar = (this.object && index) || scope.freeVariable('i');
kvar = (this.range && name) || index || ivar;
kvarAssign = kvar !== ivar ? "" + kvar + " = " : "";
if (this.step && !this.range) {
stepvar = scope.freeVariable("step");
}
if (this.pattern) {
name = ivar;
}
varPart = '';
guardPart = '';
defPart = '';
idt1 = this.tab + TAB;
if (this.range) {
forPart = source.compile(merge(o, {
index: ivar,
name: name,
step: this.step
}));
} else {
svar = this.source.compile(o, LEVEL_LIST);
if ((name || this.own) && !IDENTIFIER.test(svar)) {
defPart = "" + this.tab + (ref = scope.freeVariable('ref')) + " = " + svar + ";\n";
svar = ref;
}
if (name && !this.pattern) {
namePart = "" + name + " = " + svar + "[" + kvar + "]";
}
if (!this.object) {
lvar = scope.freeVariable('len');
forVarPart = "" + kvarAssign + ivar + " = 0, " + lvar + " = " + svar + ".length";
if (this.step) {
forVarPart += ", " + stepvar + " = " + (this.step.compile(o, LEVEL_OP));
}
stepPart = "" + kvarAssign + (this.step ? "" + ivar + " += " + stepvar : (kvar !== ivar ? "++" + ivar : "" + ivar + "++"));
forPart = "" + forVarPart + "; " + ivar + " < " + lvar + "; " + stepPart;
}
}
if (this.returns) {
resultPart = "" + this.tab + rvar + " = [];\n";
returnResult = "\n" + this.tab + "return " + rvar + ";";
body.makeReturn(rvar);
}
if (this.guard) {
if (body.expressions.length > 1) {
body.expressions.unshift(new If((new Parens(this.guard)).invert(), new Literal("continue")));
} else {
if (this.guard) {
body = Block.wrap([new If(this.guard, body)]);
}
}
}
if (this.pattern) {
body.expressions.unshift(new Assign(this.name, new Literal("" + svar + "[" + kvar + "]")));
}
defPart += this.pluckDirectCall(o, body);
if (namePart) {
varPart = "\n" + idt1 + namePart + ";";
}
if (this.object) {
forPart = "" + kvar + " in " + svar;
if (this.own) {
guardPart = "\n" + idt1 + "if (!" + (utility('hasProp')) + ".call(" + svar + ", " + kvar + ")) continue;";
}
}
body = body.compile(merge(o, {
indent: idt1
}), LEVEL_TOP);
if (body) {
body = '\n' + body + '\n';
}
return "" + defPart + (resultPart || '') + this.tab + "for (" + forPart + ") {" + guardPart + varPart + body + this.tab + "}" + (returnResult || '');
};
For.prototype.pluckDirectCall = function(o, body) {
var base, defs, expr, fn, idx, ref, val, _i, _len, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
defs = '';
_ref2 = body.expressions;
for (idx = _i = 0, _len = _ref2.length; _i < _len; idx = ++_i) {
expr = _ref2[idx];
expr = expr.unwrapAll();
if (!(expr instanceof Call)) {
continue;
}
val = expr.variable.unwrapAll();
if (!((val instanceof Code) || (val instanceof Value && ((_ref3 = val.base) != null ? _ref3.unwrapAll() : void 0) instanceof Code && val.properties.length === 1 && ((_ref4 = (_ref5 = val.properties[0].name) != null ? _ref5.value : void 0) === 'call' || _ref4 === 'apply')))) {
continue;
}
fn = ((_ref6 = val.base) != null ? _ref6.unwrapAll() : void 0) || val;
ref = new Literal(o.scope.freeVariable('fn'));
base = new Value(ref);
if (val.base) {
_ref7 = [base, val], val.base = _ref7[0], base = _ref7[1];
}
body.expressions[idx] = new Call(base, expr.args);
defs += this.tab + new Assign(ref, fn).compile(o, LEVEL_TOP) + ';\n';
}
return defs;
};
return For;
})(While);
exports.Switch = Switch = (function(_super) {
__extends(Switch, _super);
function Switch(subject, cases, otherwise) {
this.subject = subject;
this.cases = cases;
this.otherwise = otherwise;
}
Switch.prototype.children = ['subject', 'cases', 'otherwise'];
Switch.prototype.isStatement = YES;
Switch.prototype.jumps = function(o) {
var block, conds, _i, _len, _ref2, _ref3, _ref4;
if (o == null) {
o = {
block: true
};
}
_ref2 = this.cases;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
_ref3 = _ref2[_i], conds = _ref3[0], block = _ref3[1];
if (block.jumps(o)) {
return block;
}
}
return (_ref4 = this.otherwise) != null ? _ref4.jumps(o) : void 0;
};
Switch.prototype.makeReturn = function(res) {
var pair, _i, _len, _ref2, _ref3;
_ref2 = this.cases;
for (_i = 0, _len = _ref2.length; _i < _len; _i++) {
pair = _ref2[_i];
pair[1].makeReturn(res);
}
if (res) {
this.otherwise || (this.otherwise = new Block([new Literal('void 0')]));
}
if ((_ref3 = this.otherwise) != null) {
_ref3.makeReturn(res);
}
return this;
};
Switch.prototype.compileNode = function(o) {
var block, body, code, cond, conditions, expr, i, idt1, idt2, _i, _j, _len, _len1, _ref2, _ref3, _ref4, _ref5;
idt1 = o.indent + TAB;
idt2 = o.indent = idt1 + TAB;
code = this.tab + ("switch (" + (((_ref2 = this.subject) != null ? _ref2.compile(o, LEVEL_PAREN) : void 0) || false) + ") {\n");
_ref3 = this.cases;
for (i = _i = 0, _len = _ref3.length; _i < _len; i = ++_i) {
_ref4 = _ref3[i], conditions = _ref4[0], block = _ref4[1];
_ref5 = flatten([conditions]);
for (_j = 0, _len1 = _ref5.length; _j < _len1; _j++) {
cond = _ref5[_j];
if (!this.subject) {
cond = cond.invert();
}
code += idt1 + ("case " + (cond.compile(o, LEVEL_PAREN)) + ":\n");
}
if (body = block.compile(o, LEVEL_TOP)) {
code += body + '\n';
}
if (i === this.cases.length - 1 && !this.otherwise) {
break;
}
expr = this.lastNonComment(block.expressions);
if (expr instanceof Return || (expr instanceof Literal && expr.jumps() && expr.value !== 'debugger')) {
continue;
}
code += idt2 + 'break;\n';
}
if (this.otherwise && this.otherwise.expressions.length) {
code += idt1 + ("default:\n" + (this.otherwise.compile(o, LEVEL_TOP)) + "\n");
}
return code + this.tab + '}';
};
return Switch;
})(Base);
exports.If = If = (function(_super) {
__extends(If, _super);
function If(condition, body, options) {
this.body = body;
if (options == null) {
options = {};
}
this.condition = options.type === 'unless' ? condition.invert() : condition;
this.elseBody = null;
this.isChain = false;
this.soak = options.soak;
}
If.prototype.children = ['condition', 'body', 'elseBody'];
If.prototype.bodyNode = function() {
var _ref2;
return (_ref2 = this.body) != null ? _ref2.unwrap() : void 0;
};
If.prototype.elseBodyNode = function() {
var _ref2;
return (_ref2 = this.elseBody) != null ? _ref2.unwrap() : void 0;
};
If.prototype.addElse = function(elseBody) {
if (this.isChain) {
this.elseBodyNode().addElse(elseBody);
} else {
this.isChain = elseBody instanceof If;
this.elseBody = this.ensureBlock(elseBody);
}
return this;
};
If.prototype.isStatement = function(o) {
var _ref2;
return (o != null ? o.level : void 0) === LEVEL_TOP || this.bodyNode().isStatement(o) || ((_ref2 = this.elseBodyNode()) != null ? _ref2.isStatement(o) : void 0);
};
If.prototype.jumps = function(o) {
var _ref2;
return this.body.jumps(o) || ((_ref2 = this.elseBody) != null ? _ref2.jumps(o) : void 0);
};
If.prototype.compileNode = function(o) {
if (this.isStatement(o)) {
return this.compileStatement(o);
} else {
return this.compileExpression(o);
}
};
If.prototype.makeReturn = function(res) {
if (res) {
this.elseBody || (this.elseBody = new Block([new Literal('void 0')]));
}
this.body && (this.body = new Block([this.body.makeReturn(res)]));
this.elseBody && (this.elseBody = new Block([this.elseBody.makeReturn(res)]));
return this;
};
If.prototype.ensureBlock = function(node) {
if (node instanceof Block) {
return node;
} else {
return new Block([node]);
}
};
If.prototype.compileStatement = function(o) {
var body, child, cond, exeq, ifPart;
child = del(o, 'chainChild');
exeq = del(o, 'isExistentialEquals');
if (exeq) {
return new If(this.condition.invert(), this.elseBodyNode(), {
type: 'if'
}).compile(o);
}
cond = this.condition.compile(o, LEVEL_PAREN);
o.indent += TAB;
body = this.ensureBlock(this.body);
ifPart = "if (" + cond + ") {\n" + (body.compile(o)) + "\n" + this.tab + "}";
if (!child) {
ifPart = this.tab + ifPart;
}
if (!this.elseBody) {
return ifPart;
}
return ifPart + ' else ' + (this.isChain ? (o.indent = this.tab, o.chainChild = true, this.elseBody.unwrap().compile(o, LEVEL_TOP)) : "{\n" + (this.elseBody.compile(o, LEVEL_TOP)) + "\n" + this.tab + "}");
};
If.prototype.compileExpression = function(o) {
var alt, body, code, cond;
cond = this.condition.compile(o, LEVEL_COND);
body = this.bodyNode().compile(o, LEVEL_LIST);
alt = this.elseBodyNode() ? this.elseBodyNode().compile(o, LEVEL_LIST) : 'void 0';
code = "" + cond + " ? " + body + " : " + alt;
if (o.level >= LEVEL_COND) {
return "(" + code + ")";
} else {
return code;
}
};
If.prototype.unfoldSoak = function() {
return this.soak && this;
};
return If;
})(Base);
Closure = {
wrap: function(expressions, statement, noReturn) {
var args, call, func, mentionsArgs, meth;
if (expressions.jumps()) {
return expressions;
}
func = new Code([], Block.wrap([expressions]));
args = [];
if ((mentionsArgs = expressions.contains(this.literalArgs)) || expressions.contains(this.literalThis)) {
meth = new Literal(mentionsArgs ? 'apply' : 'call');
args = [new Literal('this')];
if (mentionsArgs) {
args.push(new Literal('arguments'));
}
func = new Value(func, [new Access(meth)]);
}
func.noReturn = noReturn;
call = new Call(func, args);
if (statement) {
return Block.wrap([call]);
} else {
return call;
}
},
literalArgs: function(node) {
return node instanceof Literal && node.value === 'arguments' && !node.asKey;
},
literalThis: function(node) {
return (node instanceof Literal && node.value === 'this' && !node.asKey) || (node instanceof Code && node.bound) || (node instanceof Call && node.isSuper);
}
};
unfoldSoak = function(o, parent, name) {
var ifn;
if (!(ifn = parent[name].unfoldSoak(o))) {
return;
}
parent[name] = ifn.body;
ifn.body = new Value(parent);
return ifn;
};
UTILITIES = {
"extends": function() {
return "function(child, parent) { for (var key in parent) { if (" + (utility('hasProp')) + ".call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }";
},
bind: function() {
return 'function(fn, me){ return function(){ return fn.apply(me, arguments); }; }';
},
indexOf: function() {
return "[].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; }";
},
hasProp: function() {
return '{}.hasOwnProperty';
},
slice: function() {
return '[].slice';
}
};
LEVEL_TOP = 1;
LEVEL_PAREN = 2;
LEVEL_LIST = 3;
LEVEL_COND = 4;
LEVEL_OP = 5;
LEVEL_ACCESS = 6;
TAB = ' ';
IDENTIFIER_STR = "[$A-Za-z_\\x7f-\\uffff][$\\w\\x7f-\\uffff]*";
IDENTIFIER = RegExp("^" + IDENTIFIER_STR + "$");
SIMPLENUM = /^[+-]?\d+$/;
METHOD_DEF = RegExp("^(?:(" + IDENTIFIER_STR + ")\\.prototype(?:\\.(" + IDENTIFIER_STR + ")|\\[(\"(?:[^\\\\\"\\r\\n]|\\\\.)*\"|'(?:[^\\\\'\\r\\n]|\\\\.)*')\\]|\\[(0x[\\da-fA-F]+|\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\]))|(" + IDENTIFIER_STR + ")$");
IS_STRING = /^['"]/;
utility = function(name) {
var ref;
ref = "__" + name;
Scope.root.assign(ref, UTILITIES[name]());
return ref;
};
multident = function(code, tab) {
code = code.replace(/\n/g, '$&' + tab);
return code.replace(/\s+$/, '');
};
}).call(this);
| DnD-Dev-FE/mainsite-mobile | minisub/node_modules/grunt/node_modules/coffee-script/lib/coffee-script/nodes.js | JavaScript | mit | 92,328 |
.mediaplayer[data-state=waiting]>div.jme-media-overlay,.mediaplayer .fullscreen,.mediaplayer .fullscreen.state-exitfullscreen,.mediaplayer .mediaconfigmenu,.mediaplayer.initial-state>.jme-media-overlay,.mediaplayer button.play-pause,.mediaplayer button.play-pause.state-playing,.mediaplayer .mute-unmute,.mediaplayer[data-volume=medium] .mute-unmute,.mediaplayer[data-volume=low] .mute-unmute,.mediaplayer[data-volume=no] .mute-unmute,.mediaplayer .state-unmute.mute-unmute,.mediaplayer .captions,.mediaplayer .subtitle-menu button[aria-checked=true],.mediaplayer .subtitle-menu button,.mediaplayer .playlist-next,.mediaplayer .playlist-prev,.mediaplayer .chapters,.mediaplayer.ended-state>.jme-media-overlay{font-family:jme;speak:none;font-style:normal;font-weight:400;font-variant:normal;text-transform:none;line-height:1;zoom:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.mediaplayer[data-state=waiting]>div.jme-media-overlay:before{content:"\e612"}.mediaplayer .fullscreen:before{content:"\e604"}.mediaplayer .fullscreen.state-exitfullscreen:before{content:"\e605"}.mediaplayer .mediaconfigmenu:before{content:"\e606"}.mediaplayer.initial-state>.jme-media-overlay:before{content:"\e608"}.mediaplayer button.play-pause:before{content:"\e60a"}.mediaplayer button.play-pause.state-playing:before{content:"\e60b"}.mediaplayer .mute-unmute:before{content:"\e60c"}.mediaplayer[data-volume=medium] .mute-unmute:before{content:"\e60d"}.mediaplayer[data-volume=low] .mute-unmute:before{content:"\e60e"}.mediaplayer[data-volume=no] .mute-unmute:before{content:"\e60f"}.mediaplayer .state-unmute.mute-unmute:before{content:"\e610"}.mediaplayer .captions:before{content:"\e600"}.mediaplayer .subtitle-menu button[aria-checked=true]:before{content:"\e616"}.mediaplayer .subtitle-menu button:before{content:"\e617"}.mediaplayer .playlist-next:before{content:"\e602"}.mediaplayer .playlist-prev:before{content:"\e603"}.mediaplayer .chapters:before{content:"\e615"}.mediaplayer.ended-state>.jme-media-overlay:before{content:"\e601"}@font-face{font-family:jme;src:url(jme.eot)}@font-face{font-family:jme;src:url(data:application/font-woff;charset=utf-8;base64,d09GRk9UVE8AAA5sAAoAAAAADiQAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAABDRkYgAAAA9AAACq0AAAqt29xKpU9TLzIAAAukAAAAYAAAAGAIIvzPY21hcAAADAQAAABMAAAATBpVzHBnYXNwAAAMUAAAAAgAAAAIAAAAEGhlYWQAAAxYAAAANgAAADb/1ko1aGhlYQAADJAAAAAkAAAAJAQCAh9obXR4AAAMtAAAAHgAAAB4NSAB521heHAAAA0sAAAABgAAAAYAHlAAbmFtZQAADTQAAAEVAAABFQcRlmFwb3N0AAAOTAAAACAAAAAgAAMAAAEABAQAAQEBBGptZQABAgABADr4HAL4GwP4GAQeCgAZU/+Lix4KABlT/4uLDAeLa/i0+HQFHQAAAQAPHQAAAQURHQAAAAkdAAAKpBIAHwEBBAcJCw4TGB0iJywxNjtARUpPVFleY2htcnd8gYaLkGptZWptZXUwdTF1MjB1RTYwMHVFNjAxdUU2MDJ1RTYwM3VFNjA0dUU2MDV1RTYwNnVFNjA3dUU2MDh1RTYwOXVFNjBBdUU2MEJ1RTYwQ3VFNjBEdUU2MEV1RTYwRnVFNjEwdUU2MTF1RTYxMnVFNjEzdUU2MTR1RTYxNXVFNjE2dUU2MTd1RTYxOHVFNjE5AAACAYkAHAAeAgABAAQABwAKAA0BJAGCAZ8BuwHiAgoCngLwA1EDvgPMA+oEsAU6BZEFuQYFBoAHcwe1B/sIaQikCMgJJQlf/JQO/JQO/JQO+5QO+IL4ABX7f7sFiYuJi4mLCPt/WwWDioWEi4MIi/uyBYuDkYWTiQj3f1wFjYqNi42MCPd/ugWTjZGRi5MIi/eyBYuThZKDjAj7o/twFXtncnlpi1KLZbqLz4vQsbnEi6yLpXqbaYyIi4iKiIqIiYiIighvfwWFiISOiJGHlIOVfot2i3xyi2eLZ5pyoIuai5KajZGNj42NjoyOjY+LjokIp38FjoqNiYyIjYeLiImICPd/ixV6Z3J5aYtTi2W6i8+L0LG5w4uti6R6m2mNiIuIioiJiImIiIoIcH8FhIiEjoiRh5SDlX6Ldot9cotni2eZcqCLmouSmo6RjI+NjY+Mjo2Oi4+JCKZ/BY6KjomMiIyHi4iKiAgO+En4KRVduUuoRIv7AosuRmYqCMd0BabU0r/di8CLu3auaAhDQ/dUi4v3VEBABftJ/AkVVotboGiuCNPT+1SLi/tU1tYFuV3LbtKL9wKL6NCw7AhPogVwQkRXOYsIDvgU+DQVi/wUS4uL90T7NPs0i/f09zT7NIv3RAUO9xSrFYv4FMuLi/tE9zT3NIv79Ps09zSL+0QFDvh1+FUVi/tLRdI2NmG14OBE0QVF+7sVNzbRRftLi4v3S9FF4N8FDvd491gVi/tLRdE2N2G13+BF0QX4SPdnFTc20UX7S4uL90vRReDfBQ74lPdEFYvrQpcFiJSHlIeUCLbHR89PYAWCj4KPgo4If9Qri39CBYKIgoeChwhPtkdHtk8Fh4KHgoiCCEJ/iyvVfwWOgo6Cj4MIYE7PR8i2BZOHlIiUiAiXQeuLl9UFlI6UjpOPCMhgz89gyAWPk46UjpQI1ZcF+5R7FWiLbqiLrouuqKiui66LqG6LaItobm5oiwgOi/h0FfcUi4v7FPsUiwX3VOsV99SLi0v71IsF+1QrFfcUi4v7FPsUiwX3VOsV99SLi0v71IsF+1QrFfcUi4v7FPsUiwX3VOsV99SLi0v71IsFDveU+HQV+yGL+wf7B4v7IYv7IfcH+wf3IYv3IYv3B/cHi/chi/ch+wf3B/shiwiL/GQV+weLLuiL9weL9wfo6PcHi/cHi+gui/sHi/sHLi77B4sIS/fUFfdU+wT7VPsEBQ73lPh0Ffshi/sH+weL+yGL+yH3B/sH9yGL9yGL9wf3B4v3IYv3IfsH9wf7IYsIi/xkFfsHiy7oi/cHi/cH6Oj3B4v3B4voLov7B4v7By4u+weLCCv3xBXLi4v7VEuLBfcU91QVy4uL+1RLiwUOyfhdFfgY+338GPt9BQ6i+F0V91aLi/xm+1aLBfek+GYV91aLi/xm+1aLBQ6r+FGeFYWLhY2GkIKUi5uUlLe3o8WLyYvJc8Vft4KUi5uUlJSUm4uUgsBWqEWLQItAbkVWVgiGhoWJhYsINrgVhYuEjoePgZWLmpWUzM2L9UrNgZSLmpWVlJSai5WCtGKhVYtRi1F1VWJihoeFiIWLCDa4FYSLhY6HkIGUi5qVlLO0i81jtIGUi5qVlJSVmouUgcdQiytPUIeGhYiFiwhB9+AVmJiVhot5CIv8MgWLeYGHfpcI+w33DTuLi/dU24v3DfcNBQ73/MsVhYuEjoePgZWLmpWUzM2L9UrNgZSLmpWVlJSai5WCtGKhVYtRi1F1VWJihoeFiIWLCDa4FYSLhY6HkIGUi5qVlLO0i81jtIGUi5qVlJSVmouUgcdQiytPUIeGhYiFiwhB9+AVmJiVhot5CIv8MgWLeYGHfpcI+w33DTuLi/dU24v3DfcNBQ73p/cBFYSLhY6HkIGUi5qVlLO0i81jtIGUi5qVlJSVmouUgcdQiytPUIeGhYiFiwhB9+AVmJiVhot5CIv8MgWLeYGHfpcI+w33DTuLi/dU24v3DfcNBQ73XfhNFZiYlYaLeQiL/DIFi3mBh36XCPsN9w07i4v3VNuL9w33DQUO9134TRWYmJWGi3kIi/wyBYt5gYd+lwj7DfcNO4uL91Tbi/cN9w0F96v7oxWLYWGLVcFVVWGLi7XBwVXBi7W1i8FVwcG1i4thVVUFDvhE9xQVdIt3gnx8CPtr9gWMj4uQi4+Lj4uQio8I92v2BZp8n4Kii7eLr6+Lt4u3Z69fi1+LZ2eLX4uHi4aMhwj7ayAFfJp3lHSLX4tnZ4tfi1+vZ7eLoouflJqaCPdrIAWKh4uGi4eLX69nt4u3i6+vi7eLt2evX4sIDviU93QViqyErX6pfap4pnOic6JvnW2XbJdqkWuKa4pqhG5+bX5xeXR0dXN6cH9ugG2Fa4xsCIxskWuYb5hunXGhdqF2pnqngKiAqoWpjKmMqZGnl6eYpJyfoaCgm6WWppGckJ2NnAiMi4uLjIudi5mai5yLjIuMi4wIi4sFWDYVf3B6c3d3dnhye3CBcYBuhm+Mb4xvkXGWcZd0m3ifeJ98o4GlgaSGp4ymjKaRppakCJajmqKfnZ6eopmklaOUppCliqWKpYajgKKAoXydeZx4mXWUc5R0kHGKcgiLiwWLiouKi4qLe5d9nIqHeYZ6hHsIDvhU+HQV/FSLi/yU+JSLi/hUS8sF+1RLFcuLi/sUS4uL9xQF91T8FBX8FIuL+BSri4v7NPe0i4v3NLCLpnCL+/kFDvh/+CQVQ5U7kTiLOIs7hUOBflWDUItMi0yTUJhV04Hbhd6L3ovbkdOVmMGTxovKi8qDxn7BCPu/+6QVi/dU9zQr+zQrBQ73VMsV99SLi0v71IsFi/eUFffUi4tL+9SLBYv3lBX31IuLS/vUiwUr6xWL+xRri4vra4uLqwWr+5sVi3LLi4trK4uL1Mupi6RLi4ur64uLQgWL+wsVi/s0K4uLq8uLi6tLi4ury4uLq0uLi6sFDov4dBWL/JT4lIuL+JT8lIsF+HT8dBX8VIuL+FT4VIuL/FQFK/gEFfs0+zQr60tL9zT7NPd093RLywUOi/h0FYv8lPiUi4v4lPyUiwX4dPx0FfxUi4v4VPhUi4v8VAUO9930FSL1i/chy4uL+wfiNQX7C/fdFfshi/sH+weL+yGL+yH3B/sH9yGL9yGL9wf3B4v3IYv3IfsH9wf7IYsIi/xUFSGLNeGL9Yv14eH1i/WL4TWLIYshNTUhiwgOy/d0FfcU9xRLi/sU+xT3FPsUy4sF91T3lBVLi/cU+xT7FPsUy4v3FPcUBfuE91QVO/wUu4vb+BQFDviUFPiUFYsMCgAAAAADAgABkAAFAAABTAFmAAAARwFMAWYAAAD1ABkAhAAAAAAAAAAAAAAAAAAAAAEQAAAAAAAAAAAAAAAAAAAAAEAAAOYZAeD/4P/gAeAAIAAAAAEAAAAAAAAAAAAAACAAAAAAAAIAAAADAAAAFAADAAEAAAAUAAQAOAAAAAoACAACAAIAAQAg5hn//f//AAAAAAAg5gD//f//AAH/4xoEAAMAAQAAAAAAAAAAAAAAAQAB//8ADwABAAAAAQAAAnhtIV8PPPUACwIAAAAAAM9LhLwAAAAAz0uEvAAA/+ACIAHgAAAACAACAAAAAAAAAAEAAAHg/+AAAAIgAAAAAAIgAAEAAAAAAAAAAAAAAAAAAAAeAAAAAAAAAAAAAAAAAQAAAAIAAAQCAAAAAgAAoAIAAIACAAAfAgAAHwIAAAACAAAAAgAAAAIAAAACAAA+AgAAFwIgAAACAAAAAgAAAAIAAAACAAAAAgAAAAIAABACAAAAAgAAAAIAACACAAAAAgAAAAIAAAACAAAAAABQAAAeAAAAAAAOAK4AAQAAAAAAAQAGAAAAAQAAAAAAAgAOACsAAQAAAAAAAwAGABwAAQAAAAAABAAGADkAAQAAAAAABQAWAAYAAQAAAAAABgADACIAAQAAAAAACgAoAD8AAwABBAkAAQAGAAAAAwABBAkAAgAOACsAAwABBAkAAwAGABwAAwABBAkABAAGADkAAwABBAkABQAWAAYAAwABBAkABgAGACUAAwABBAkACgAoAD8AagBtAGUAVgBlAHIAcwBpAG8AbgAgADEALgAwAGoAbQBlam1lAGoAbQBlAFIAZQBnAHUAbABhAHIAagBtAGUARwBlAG4AZQByAGEAdABlAGQAIABiAHkAIABJAGMAbwBNAG8AbwBuAAAAAAMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=) format("woff"),url(jme.ttf) format("truetype");font-weight:400;font-style:normal}@-webkit-keyframes jmespin{0%{-webkit-transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg)}}@keyframes jmespin{0%{-webkit-transform:rotate(0deg);transform:rotate(0deg)}100%{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}.jme-controlbar{display:table;width:100%}.jme-cb-box{display:table-row}.jme-cb-box>div{display:table-cell;padding:.21875em;vertical-align:middle}.jme-cb-box .progress-container{width:100%}.jme-cb-box .mute-container{padding-right:.0625em}.jme-cb-box .volume-container{padding-left:.0625em}[data-playersizes~=xs]>.jme-controlbar{padding-top:.25em}[data-playersizes~=xs]>.jme-controlbar .time-slider{position:absolute;top:-.125em;left:0;right:0}[data-playersizes~=xs]>.jme-controlbar .progress-container{width:auto}[data-playersizes~=xs]>.jme-controlbar .progress-container:before{content:"/"}[data-playersizes~=xs]>.jme-controlbar .duration-container{width:100%}[data-playersize=xx-small]>.jme-controlbar .progress-container:before{content:""}[data-playersize=xx-small]>.jme-controlbar .duration-display,[data-playersize=xx-small]>.jme-controlbar .volume-container{display:none}.mediaplayer{position:relative;display:block;width:512px;font-size:16px}.mediaplayer video{display:block;width:100%;height:auto}.audioplayer .media-controls .fullscreen-container{display:none}.mediaplayer{}.mediaplayer button{overflow:visible;-webkit-appearance:none;background:0;padding:0;border:0;font-size:inherit;outline:0}.mediaplayer button::-moz-focus-inner{padding:0;border:0}.mediaplayer>.jme-media-overlay{position:absolute;top:0;left:0;right:0;bottom:0;font-size:400%;color:#f6f6f6;text-align:center;background:url(../styles/transparent.png) \9}.mediaplayer>.jme-media-overlay:before{content:'\0020';position:absolute;display:block;width:1em;height:1em;top:50%;left:50%;margin:-.5em 0 0 -.5em;background:url(../styles/transparent.png) \9;text-shadow:0 0 .5em rgba(0,0,0,.5)}.mediaplayer[data-playersize=x-large]>.jme-media-overlay{font-size:550%}.mediaplayer[data-playersize=large]>.jme-media-overlay{font-size:450%}.mediaplayer[data-playersize=small]>.jme-media-overlay{font-size:350%}.mediaplayer[data-playersize=x-small]>.jme-media-overlay{font-size:300%}.mediaplayer[data-playersize=xx-small]>.jme-media-overlay{font-size:240%}.mediaplayer[data-state=idle]{cursor:pointer}.mediaplayer.initial-state>.jme-media-overlay{background-position:1px 1px}.mediaplayer.initial-state.has-ytposter.no-backgroundsize>.jme-media-overlay:before{content:"";background-position:2px 2px}.mediaplayer.ended-state{cursor:pointer}.mediaplayer.ended-state>.jme-media-overlay{background-position:3px 3px}.mediaplayer.yt-video.has-yt-bug.initial-state>.jme-media-overlay,.mediaplayer.yt-video.has-yt-bug.initial-state>.ws-poster,.mediaplayer.yt-video.has-yt-bug.initial-state>.jme-controlbar{pointer-events:none}.mediaplayer.yt-video.has-yt-bug.initial-state .fullscreen-container,.mediaplayer.yt-video.has-yt-bug.initial-state .playlist-container,.mediaplayer.yt-video.has-yt-bug.initial-state .subtitle-container,.mediaplayer.yt-video.has-yt-bug.initial-state .mediaconfig-container{pointer-events:auto}.mediaplayer[data-state=waiting]{cursor:default}.mediaplayer[data-state=waiting]>div.jme-media-overlay{background-position:4px 4px}.mediaplayer[data-state=waiting]>div.jme-media-overlay:before{-webkit-animation-name:jmespin;-webkit-animation-iteration-count:infinite;-webkit-animation-duration:1100ms;-webkit-animation-timing-function:linear;animation-name:jmespin;animation-iteration-count:infinite;animation-duration:1100ms;animation-timing-function:linear;background-position:5px 5px}.mediaplayer[data-state=playing][data-useractivity=false] .jme-controlbar{opacity:0;visibility:hidden}.mediaplayer .cue-display span.cue-wrapper{transition:bottom 300ms;bottom:0}.mediaplayer[data-state=playing][data-useractivity=false] .cue-display span.cue-wrapper{bottom:-35px}.mediaplayer .ws-poster{display:none;position:absolute;top:0;left:0;right:0;bottom:0;background:#000 no-repeat center;background-size:contain}.mediaplayer.initial-state .ws-poster,.mediaplayer.ended-state .ws-poster{display:block}.mediaplayer.no-poster .ws-poster,.mediaplayer.no-backgroundsize div.ws-poster{display:none}.mediaplayer>.jme-controlbar{position:absolute;left:0;right:0;bottom:0;width:auto;cursor:default;outline:0;background:#333;background:rgba(0,0,0,.6);color:#e1e1e1;transition:all 300ms}.mediaplayer>.jme-controlbar button{display:inline-block;color:inherit;width:1.5em;height:1.5em;cursor:pointer;text-align:center;transition:color 400ms}.mediaplayer>.jme-controlbar button:hover,.mediaplayer>.jme-controlbar button:focus{color:#fefefe}.mediaplayer>.jme-controlbar button:active{color:#fff}.mediaplayer>.jme-controlbar button[disabled]{color:#ccc;cursor:default;cursor:not-allowed}.mediaplayer .currenttime-display,.mediaplayer .duration-display,.mediaplayer .time-select{font-size:81.3%;font-family:sans-serif;margin-top:.03em}.mediaplayer .playlist-container{display:none}.mediaplayer .playlist-box,.mediaplayer .playlist-button-container,.mediaplayer.has-playlist .playlist-container{display:table-cell}.mediaplayer .no-volume-api .volume-container,.mediaplayer .no-volume-api .mute-container{padding:0}.mediaplayer .no-volume-api .mute-unmute,.mediaplayer .no-volume-api .volume-slider{display:none}.mediaplayer .chapters-container{display:none}.mediaplayer.has-chapter-tracks .chapters-container{display:table-cell}.mediaplayer .captions[role=checkbox]{color:#999}.mediaplayer .captions[role=checkbox][aria-checked=true]{color:inherit}.mediaplayer[data-tracks="0"] .subtitle-container{display:none}.mediaplayer[data-tracks="1"] .captions[aria-haspopup],.mediaplayer[data-tracks="1"] .subtitle-menu{display:none}.mediaplayer[data-tracks=many] .captions[role=checkbox]{display:none}.mediaplayer .mediamenu-wrapper{position:relative;zoom:1}.mediaplayer .mediamenu{position:absolute;bottom:1.75em;margin-bottom:3px;width:400px;right:-.625em;visibility:hidden}.mediaplayer .mediamenu h5{font-size:100%;margin:.3125em 0;padding:0}.mediaplayer .mediamenu ul,.mediaplayer .mediamenu li{margin:0;padding:0;list-style:none}.mediaplayer .mediamenu li>ul{margin-left:10px}.mediaplayer .mediamenu button{position:relative;display:block;zoom:1;width:100%;text-align:left;height:auto;padding:2px;font-size:81.3%}.mediaplayer .mediamenu>div{position:relative;zoom:1;visibility:hidden;float:right;padding:.3125em;background:#333;background:rgba(0,0,0,.6);opacity:0;transform:translateY(-3%);transition:all 200ms}.mediaplayer .mediamenu>div>.media-submenu{margin:.3125em 0;padding:.3125em 0;border-top:.0625em solid #eee;border-top:.0625em solid rgba(255,255,255,.4)}.mediaplayer .mediamenu>div>.media-submenu:first-child{margin-top:0;border-top:0}.mediaplayer .mediamenu>div iframe{visibility:inherit!important}.mediaplayer .mediamenu.visible-menu>div{visibility:visible;opacity:1;transform:translateY(0)}.mediaplayer .subtitle-menu button:before{display:inline-block;vertical-align:middle;padding:0 5px 0 0}.mediaplayer .mediaconfig-container{display:none}.mediaplayer.has-config-menu .mediaconfig-container{display:table-cell}.mediaplayer .buffer-progress{position:absolute;top:0;left:0;right:0;bottom:0;overflow:hidden}.mediaplayer .buffer-progress-indicator{cursor:pointer;height:100%;background:#bbb;background:rgba(255,255,255,.2)}.mediaplayer .media-range{position:relative;zoom:1;height:.4375em;border:1px solid #999;border-color:rgba(255,255,255,.4);outline:0}.mediaplayer .ws-range-progress,.mediaplayer .ws-range-track,.mediaplayer .ws-range-thumb,.mediaplayer .time-select{position:absolute;display:block}.mediaplayer .time-select{display:inline-block;overflow:hidden;text-align:center;visibility:hidden;opacity:0;transition:400ms opacity,400ms visibility;background:#333;background:rgba(0,0,0,.6);color:#eee;bottom:1.25em;margin:0 0 4px;padding:.25em .125em .125em;min-width:2.8em}.mediaplayer .time-select.show-time-select{opacity:1;visibility:visible}.mediaplayer .ws-range-track{top:0;left:0;bottom:0}.mediaplayer .ws-range-progress{-moz-box-sizing:content-box;box-sizing:content-box;cursor:pointer;background:#e1e1e1;background:rgba(255,255,255,.3);left:0;height:100%}.mediaplayer .ws-range-thumb{cursor:pointer;width:.5625em;height:.5625em;background:#f1f1f1;background:rgba(255,255,255,.9)}.mediaplayer [aria-disabled=true] .ws-range-thumb{cursor:default}.mediaplayer .ws-focus .ws-range-thumb{background:#fff}.mediaplayer .time-slider .ws-range-thumb{width:.75em}.mediaplayer .volume-slider{width:60px}.mediaplayer[data-playersize=medium] .volume-slider{width:80px}.mediaplayer[data-playersize=large] .volume-slider{width:110px}.mediaplayer[data-playersize=x-large] .volume-slider{width:130px}.mediaplayer.state-muted .volume-slider .ws-range-progress{width:0!important}.mediaplayer.state-muted .volume-slider .ws-range-thumb{left:0!important}.mediaplayer .ws-a11y-focus{outline:1px dotted #eee;outline:1px dotted rgba(255,255,255,.8)}.mediaplayer .ws-a11y-focus:hover{outline:0}.has-media-fullscreen{overflow:hidden}.player-fullscreen{position:fixed!important;z-index:999999;background:#000}.mediaplayer[data-useractivity=false][data-state=playing].player-fullscreen,.mediaplayer[data-useractivity=false][data-state=playing].player-fullscreen .jme-media-overlay,.mediaplayer[data-useractivity=false][data-state=playing].player-fullscreen .cue-display{cursor:none!important}.media-fullscreen,.player-fullscreen .polyfill-mediaelement,.player-fullscreen{top:0!important;left:0!important;right:0!important;bottom:0!important;width:100%!important;height:100%!important;max-width:none!important;padding:0!important;margin:0!important}.media-fullscreen{position:relative} | DaAwesomeP/cdnjs | ajax/libs/webshim/1.15.4/minified/shims/jme/controls.css | CSS | mit | 16,853 |
!function(a,b){"use strict";if(!("Ink"in a&&"function"==typeof Ink.requireModules)){var c={},d={},e=[],f={},g=[],h={},i=Function.prototype.apply,j=function(a){if("object"!=typeof a)return!1;for(var b in a)if(a.hasOwnProperty(b))return!1;return!0};a.Ink={VERSION:"3.1.10",_checkPendingRequireModules:function(){var a,b,c,e,f,h,i=[],j=[];for(a=0,b=g.length;b>a;++a)if(c=g[a]){for(e in c.left)c.left.hasOwnProperty(e)&&(f=d[e],f&&(c.args[c.left[e]]=f,delete c.left[e],--c.remaining));if(c.remaining>0)i.push(c);else{if(h=c.cb,!h)continue;delete c.cb,j.push([h,c.args])}}g=i;for(var k=0;k<j.length;k++)j[k][0].apply(!1,j[k][1]);g.length>0&&setTimeout(function(){Ink._checkPendingRequireModules()},0)},getPath:function(a,b){var d=a.split(/[._]/g),e,f,g,h;for(f=d.length;f>=0;f-=1)if(e=d.slice(0,f+1).join("."),c[e]){g=e;break}return g in c?(h=c[g],/\/$/.test(h)||(h+="/"),f<d.length&&(h+=d.slice(f+1).join("/")+"/"),b||(h+="lib.js"),h):null},setPath:function(a,b){c[a.replace(/_/,".")]=b},loadScript:function(a,c){if(-1===a.indexOf("/")){var d=a;if(a=this.getPath(a),null===a)throw new Error('Could not load script "'+d+'". Path not found in the registry. Did you misspell the name, or forgot to call setPath()?')}var e=b.createElement("script");e.setAttribute("type",c||"text/javascript"),e.setAttribute("src",a),"onerror"in e&&(e.onerror=function(){Ink.error(["Failed to load script from ",a,"."].join(""))});var f=b.head||b.getElementsByTagName("head")[0];return f?f.appendChild(e):void 0},_loadLater:function(a){setTimeout(function(){d[a]||f[a]||h[a]||(f[a]=!0,Ink.loadScript(a))},0)},namespace:function(b,c){if(!b||!b.length)return null;for(var d=b.split("."),e=a,f,g=0,h=d.length;h>g;++g)e[d[g]]=e[d[g]]||{},f=e,e=e[d[g]];return c?[f,d[g-1]]:e},getModule:function(a,b){var c=b?[a,"_",b].join(""):a;return d[c]},createModule:function(b,c,g,i){if("string"!=typeof b)throw new Error("module name must be a string!");if(!("number"==typeof c||"string"==typeof c&&c.length>0))throw new Error("version number missing!");var k=[b,"_",c].join("");h[k]=!0;var l=function(){if(!d[k]){delete f[k],delete f[b];var g=Array.prototype.slice.call(arguments),l=i.apply(a,g);e.push(k),"object"==typeof l?l._version=c:"function"==typeof l&&(l.prototype._version=c,l._version=c);var m=0===b.indexOf("Ink."),n;m&&(n=Ink.namespace(b,!0)),d[k]=l,delete h[k],m&&(n[0][n[1]+"_"+c]=l),d[b]=l,m&&j(n[0][n[1]])&&(n[0][n[1]]=l),this&&Ink._checkPendingRequireModules()}};this.requireModules(g,l)},requireModules:function(a,b){var c,e,h,i,j;if(e=a&&a.length,h={args:new Array(e),left:{},remaining:e,cb:b},"object"!=typeof a||void 0===a.length)throw new Error("Dependency list should be an array!");if("function"!=typeof b)throw new Error("Callback should be a function!");for(c=0;e>c;++c)Ink._moduleRenames[a[c]]?(Ink.warn(a[c]+" was renamed to "+Ink._moduleRenames[a[c]]),i=Ink._moduleRenames[a[c]]):i=a[c],i?(j=d[i],j?(h.args[c]=j,--h.remaining):(f[i]||Ink._loadLater(i),h.left[i]=c)):--h.remaining;h.remaining>0?g.push(h):b.apply(!0,h.args)},_moduleRenames:{"Ink.UI.Aux_1":"Ink.UI.Common_1"},getModulesLoadOrder:function(){return e.slice()},getModuleScripts:function(){var a=this.getModulesLoadOrder();return a.unshift("Ink_1"),a=a.map(function(a){return["<scr",'ipt type="text/javascript" src="',Ink.getModuleURL(a),'"></scr',"ipt>"].join("")}),a.join("\n")},createExt:function(a,b,c,d){return Ink.createModule("Ink.Ext."+a,b,c,d)},bind:function(a,b){var c=Array.prototype.slice.call(arguments,2);return function(){var d=Array.prototype.slice.call(arguments),e=c.concat(d);return a.apply(b===!1?this:b,e)}},bindMethod:function(a,b){return Ink.bind.apply(Ink,[a[b],a].concat([].slice.call(arguments,2)))},bindEvent:function(b,c){var d=Array.prototype.slice.call(arguments,2);return function(e){var f=d.slice();return f.unshift(e||a.event),b.apply(c===!1?this:c,f)}},i:function(a){return"string"==typeof a?b.getElementById(a)||null:a},ss:function(a,c){if("undefined"==typeof Ink.Dom||"undefined"==typeof Ink.Dom.Selector)throw new Error("This method requires Ink.Dom.Selector");return Ink.Dom.Selector.select(a,c||b)},s:function(a,c){if("undefined"==typeof Ink.Dom||"undefined"==typeof Ink.Dom.Selector)throw new Error("This method requires Ink.Dom.Selector");return Ink.Dom.Selector.select(a,c||b)[0]||null},extendObj:function(a){for(var b=[].slice.call(arguments,1),c=0,d=b.length;d>c;c++)if(b[c])for(var e in b[c])Object.prototype.hasOwnProperty.call(b[c],e)&&(a[e]=b[c][e]);return a},log:function(){var b=a.console;b&&b.log&&i.call(b.log,b,arguments)},warn:function(){var b=a.console;b&&b.warn&&i.call(b.warn,b,arguments)},error:function(){var b=a.console;b&&b.error&&i.call(b.error,b,arguments)}}}}(window,document),Ink.createModule("Ink.Net.Ajax","1",[],function(){"use strict";var Ajax=function(a,b){this.init(a,b)};Ajax.globalOptions={parameters:{},requestHeaders:{}};var xMLHttpRequestWithCredentials="XMLHttpRequest"in window&&"withCredentials"in new XMLHttpRequest;return Ajax.prototype={init:function(a,b){if(!a)throw new Error("new Ink.Net.Ajax: Pass a url as the first argument!");var c=Ink.extendObj({asynchronous:!0,contentType:"application/x-www-form-urlencoded",cors:!1,validateCors:!1,debug:!1,delay:0,evalJS:!0,method:"POST",parameters:null,postBody:"",requestHeaders:null,sanitizeJSON:!1,signRequest:!1,timeout:0,useCredentials:!1,xhrProxy:"",onComplete:null,onCreate:null,onException:null,onFailure:null,onHeaders:null,onInit:null,onSuccess:null,onTimeout:null},Ajax.globalOptions);if(b&&"object"==typeof b){if(c=Ink.extendObj(c,b),"object"==typeof b.parameters)c.parameters=Ink.extendObj(Ink.extendObj({},Ajax.globalOptions.parameters),b.parameters);else if(null!==b.parameters){var d=this.paramsObjToStr(Ajax.globalOptions.parameters);d&&(c.parameters=b.parameters+"&"+d)}c.requestHeaders=Ink.extendObj({},Ajax.globalOptions.requestHeaders),c.requestHeaders=Ink.extendObj(c.requestHeaders,b.requestHeaders)}this.options=c,this.safeCall("onInit"),this.url=a;var e=this._locationFromURL(a);this.isHTTP=this._locationIsHTTP(e),this.isCrossDomain=this._locationIsCrossDomain(e,location),this.requestHasBody=c.method.search(/^get|head$/i)<0,this.options.validateCors===!0&&(this.options.cors=this.isCrossDomain),this.options.cors&&(this.isCrossDomain=!1),this.transport=this.getTransport(),this.request()},_locationFromURL:function(a){var b=document.createElementNS?document.createElementNS("http://www.w3.org/1999/xhtml","a"):document.createElement("a");return b.setAttribute("href",a),b},_locationIsHTTP:function(a){return a.href.match(/^https?:/i)?!0:!1},_locationIsCrossDomain:function(a,b){if(b=b||window.location,Ajax.prototype._locationIsHTTP(a)&&"widget:"!==b.protocol&&"object"!=typeof window.widget){var c=a.href.split("//"),d=b.href.split("//");if(1===c.length||1===d.length)return!1;var e=c[0],f=d[0],g=/:|\//,h=c[1].split(g)[0],i=d[1].split(g)[0];return e!==f||h!==i}return!1},getTransport:function(){if(!xMLHttpRequestWithCredentials&&this.options.cors&&"XDomainRequest"in window)return this.usingXDomainReq=!0,new XDomainRequest;if("undefined"!=typeof XMLHttpRequest)return new XMLHttpRequest;if("undefined"==typeof ActiveXObject)return null;try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(a){return new ActiveXObject("Microsoft.XMLHTTP")}},setHeaders:function(){if(this.transport)try{var a={Accept:"text/javascript,text/xml,application/xml,application/xhtml+xml,text/html,application/json;q=0.9,text/plain;q=0.8,video/x-mng,image/png,image/jpeg,image/gif;q=0.2,*/*;q=0.1","Accept-Language":navigator.language,"X-Requested-With":"XMLHttpRequest","X-Ink-Version":"3"};if(this.options.cors&&(this.options.signRequest||delete a["X-Requested-With"],delete a["X-Ink-Version"]),this.options.requestHeaders&&"object"==typeof this.options.requestHeaders)for(var b in this.options.requestHeaders)this.options.requestHeaders.hasOwnProperty(b)&&(a[b]=this.options.requestHeaders[b]);this.transport.overrideMimeType&&(navigator.userAgent.match(/Gecko\/(\d{4})/)||[0,2005])[1]<2005&&(a.Connection="close");for(var c in a)a.hasOwnProperty(c)&&this.transport.setRequestHeader(c,a[c])}catch(d){}},paramsObjToStr:function(a){var b,c,d,e,f=[];if("object"!=typeof a)return a;for(d in a)if(a.hasOwnProperty(d))if(e=a[d],"[object Array]"!==Object.prototype.toString.call(e)||isNaN(e.length))f=f.concat([encodeURIComponent(d),"=",encodeURIComponent(e),"&"]);else for(b=0,c=e.length;c>b;b++)f=f.concat([encodeURIComponent(d),"[]","=",encodeURIComponent(e[b]),"&"]);return f.length>0&&f.pop(),f.join("")},setParams:function(){var a=null,b=this.options.parameters;a="object"==typeof b?this.paramsObjToStr(b):""+b,a&&(this.url.indexOf("?")>-1?this.url=this.url.split("#")[0]+"&"+a:this.url=this.url.split("#")[0]+"?"+a)},getHeader:function(a){if(this.usingXDomainReq&&"Content-Type"===a)return this.transport.contentType;try{return this.transport.getResponseHeader(a)}catch(b){return null}},getAllHeaders:function(){try{return this.transport.getAllResponseHeaders()}catch(a){return null}},getResponse:function(){var a=this.transport,b={headerJSON:null,responseJSON:null,getHeader:this.getHeader,getAllHeaders:this.getAllHeaders,request:this,transport:a,timeTaken:new Date-this.startTime,requestedUrl:this.url};b.readyState=a.readyState;try{b.responseText=a.responseText}catch(c){}try{b.responseXML=a.responseXML}catch(c){}try{b.status=a.status}catch(c){b.status=0}try{b.statusText=a.statusText}catch(c){b.statusText=""}return b},abort:function(){if(this.transport){clearTimeout(this.delayTimeout),clearTimeout(this.stoTimeout),this._aborted=!0;try{this.transport.abort()}catch(a){}this.finish()}},runStateChange:function(){if(!this._aborted){var a=this.transport.readyState;if(3===a)this.isHTTP&&this.safeCall("onHeaders");else if(4===a||this.usingXDomainReq){if(this.options.asynchronous&&this.options.delay&&this.startTime+this.options.delay>(new Date).getTime())return void(this.delayTimeout=setTimeout(Ink.bind(this.runStateChange,this),this.options.delay+this.startTime-(new Date).getTime()));var b,c=this.transport.responseText,d=this.getResponse(),e=this.transport.status;this.isHTTP&&!this.options.asynchronous&&this.safeCall("onHeaders"),clearTimeout(this.stoTimeout),0===e?this.isHTTP?this.safeCall("onException",new Error("Ink.Net.Ajax: network error! (HTTP status 0)")):e=c?200:404:304===e&&(e=200);var f=this.usingXDomainReq||e>=200&&300>e,g=this.getHeader("Content-Type")||"";if(this.options.evalJS&&(g.indexOf("application/json")>=0||"force"===this.options.evalJS))try{b=this.evalJSON(c,this.sanitizeJSON),b&&(c=d.responseJSON=b)}catch(h){f&&this.safeCall("onException",h)}if(this.usingXDomainReq&&-1!==g.indexOf("xml")&&"DOMParser"in window){var i;switch(g){case"application/xml":case"application/xhtml+xml":case"image/svg+xml":i=g;break;default:i="text/xml"}var j=(new DOMParser).parseFromString(this.transport.responseText,i);this.transport.responseXML=j,d.responseXML=j}null!=this.transport.responseXML&&null==d.responseJSON&&""!==this.transport.responseXML.xml&&(c=this.transport.responseXML),(e||this.usingXDomainReq)&&(f?this.safeCall("onSuccess",d,c):this.safeCall("onFailure",d,c),this.safeCall("on"+e,d,c)),this.finish(d,c)}}},finish:function(a,b){if(a&&this.safeCall("onComplete",a,b),clearTimeout(this.stoTimeout),this.transport){try{this.transport.onreadystatechange=null}catch(c){}"function"==typeof this.transport.destroy&&this.transport.destroy(),this.transport=null}},safeCall:function(a){var b=arguments[1]instanceof Error?arguments[1]:null;if("function"==typeof this.options[a])try{this.options[a].apply(this,[].slice.call(arguments,1))}catch(c){Ink.error("Ink.Net.Ajax: an error was raised while executing "+a+".",c)}else b&&Ink.error("Ink.Net.Ajax: "+b)},setRequestHeader:function(a,b){this.options.requestHeaders||(this.options.requestHeaders={}),this.options.requestHeaders[a]=b},request:function(){if(this.transport){var a=null;this.requestHasBody?(null!==this.options.postBody&&""!==this.options.postBody?(a=this.options.postBody,this.setParams()):null!==this.options.parameters&&""!==this.options.parameters&&(a=this.options.parameters),"object"!=typeof a||a.nodeType?"object"!=typeof a&&null!==a&&(a=""+a):a=this.paramsObjToStr(a),this.options.contentType&&this.setRequestHeader("Content-Type",this.options.contentType)):this.setParams();var b=this.url,c=this.options.method,d=this.isCrossDomain;d&&this.options.xhrProxy&&(this.setRequestHeader("X-Url",b),b=this.options.xhrProxy+encodeURIComponent(b),d=!1);try{this.transport.open(c,b,this.options.asynchronous)}catch(e){return this.safeCall("onException",e),this.finish(this.getResponse(),null)}this.setHeaders(),this.safeCall("onCreate"),this.options.timeout&&!isNaN(this.options.timeout)&&(this.stoTimeout=setTimeout(Ink.bind(function(){this.options.onTimeout&&(this.safeCall("onTimeout"),this.abort())},this),1e3*this.options.timeout)),this.options.useCredentials&&!this.usingXDomainReq&&(this.transport.withCredentials=!0),this.options.asynchronous&&!this.usingXDomainReq?this.transport.onreadystatechange=Ink.bind(this.runStateChange,this):this.usingXDomainReq&&(this.transport.onload=Ink.bind(this.runStateChange,this));try{if(d)return void Ink.error("Ink.Net.Ajax: You are attempting to request a URL which is cross-domain from this one. To do this, you *must* enable the `cors` option!");this.startTime=(new Date).getTime(),this.transport.send(a)}catch(e){return this.safeCall("onException",e),this.finish(this.getResponse(),null)}this.options.asynchronous||this.runStateChange()}},isJSON:function(a){return"string"==typeof a&&a?(a=a.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"/g,""),/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/.test(a)):!1},evalJSON:function(strJSON,sanitize){if(strJSON&&(!sanitize||this.isJSON(strJSON)))try{return"undefined"!=typeof JSON&&"undefined"!=typeof JSON.parse?JSON.parse(strJSON):eval("("+strJSON+")")}catch(e){throw new Error("Ink.Net.Ajax: Bad JSON string. "+e)}return null}},Ajax.load=function(a,b){var c=Ajax.prototype._locationIsCrossDomain(window.location,Ajax.prototype._locationFromURL(a));return new Ajax(a,{method:"GET",cors:c,onSuccess:function(a){b(a.responseJSON||a.responseText,a)}})},Ajax.ping=function(a,b){var c=Ajax.prototype._locationIsCrossDomain(window.location,Ajax.prototype._locationFromURL(a));return new Ajax(a,{method:"HEAD",cors:c,onSuccess:function(a){"function"==typeof b&&b(a)}})},Ajax}),Ink.createModule("Ink.Net.JsonP","1",[],function(){"use strict";var a=function(a,b){this.init(a,b)};return a.prototype={init:function(a,b){if(this.options=Ink.extendObj({onSuccess:void 0,onFailure:void 0,failureObj:{},timeout:10,params:{},callbackParam:"jsoncallback",internalCallback:"_cb",randVar:!1},b||{}),this.options.randVar!==!1?this.randVar=this.options.randVar:this.randVar=parseInt(1e5*Math.random(),10),this.options.internalCallback+=this.randVar,this.uri=a,"function"==typeof this.options.onComplete&&(this.options.onSuccess=this.options.onComplete),"string"!=typeof this.uri)throw new Error("Ink.Net.JsonP: Please define an URI");if("function"!=typeof this.options.onSuccess)throw new Error("Ink.Net.JsonP: please define a callback function on option onSuccess!");Ink.Net.JsonP[this.options.internalCallback]=Ink.bind(function(){this.options.onSuccess(arguments[0]),this._cleanUp()},this),this.timeout=setTimeout(Ink.bind(function(){this.abort(),"function"==typeof this.options.onFailure&&this.options.onFailure(this.options.failureObj)},this),1e3*this.options.timeout),this._addScriptTag()},abort:function(){Ink.Net.JsonP[this.options.internalCallback]=Ink.bindMethod(this,"_cleanUp")},_addParamsToGet:function(a,b){var c=-1!==a.indexOf("?"),d,e,f,g=[a];for(e in b)b.hasOwnProperty(e)&&(c?d="&":(d="?",c=!0),f=b[e],"number"==typeof f||f||(f=""),g=g.concat([d,e,"=",encodeURIComponent(f)]));return g.join("")},_getScriptContainer:function(){return document.body||document.getElementsByTagName("body")[0]||document.getElementsByTagName("head")[0]||document.documentElement},_addScriptTag:function(){this.options.params[this.options.callbackParam]="Ink.Net.JsonP."+this.options.internalCallback,this.options.params.rnd_seed=this.randVar,this.uri=this._addParamsToGet(this.uri,this.options.params),this._scriptEl=document.createElement("script"),this._scriptEl.type="text/javascript",this._scriptEl.src=this.uri;var a=this._getScriptContainer();a.appendChild(this._scriptEl)},_cleanUp:function(){this.timeout&&window.clearTimeout(this.timeout),delete this.options.onSuccess,delete this.options.onFailure,delete Ink.Net.JsonP[this.options.internalCallback],this._removeScriptTag()},_removeScriptTag:function(){this._scriptEl&&(this._scriptEl.parentNode.removeChild(this._scriptEl),delete this._scriptEl)}},a}),Ink.createModule("Ink.Dom.Browser","1",[],function(){"use strict";var a={IE:!1,GECKO:!1,OPERA:!1,SAFARI:!1,KONQUEROR:!1,CHROME:!1,model:!1,version:!1,userAgent:!1,cssPrefix:!1,domPrefix:!1,init:function(){this.detectBrowser(),this.setDimensions(),this.setReferrer()},setDimensions:function(){var a=0,b=0;"number"==typeof window.innerWidth?(a=window.innerWidth,b=window.innerHeight):document.documentElement&&(document.documentElement.clientWidth||document.documentElement.clientHeight)?(a=document.documentElement.clientWidth,b=document.documentElement.clientHeight):document.body&&(document.body.clientWidth||document.body.clientHeight)&&(a=document.body.clientWidth,b=document.body.clientHeight),this.windowWidth=a,this.windowHeight=b},setReferrer:function(){document.referrer&&document.referrer.length?this.referrer=window.escape(document.referrer):this.referrer=!1},detectBrowser:function(){this._sniffUserAgent(navigator.userAgent)},_sniffUserAgent:function(a){if(this.userAgent=a,a=a.toLowerCase(),/applewebkit\//.test(a)&&!/iemobile/.test(a))if(this.cssPrefix="-webkit-",this.domPrefix="Webkit",/(chrome|crios)\//.test(a))this.CHROME=!0,this.model="chrome",this.version=a.replace(/(.*)chrome\/([^\s]+)(.*)/,"$2");else{this.SAFARI=!0,this.model="safari";var b=/version\/([^) ]+)/;b.test(a)?this.version=a.match(b)[1]:this.version=a.replace(/(.*)applewebkit\/([^\s]+)(.*)/,"$2")}else if(/opera/.test(a))this.OPERA=!0,this.model="opera",this.version=a.replace(/(.*)opera.([^\s$]+)(.*)/,"$2"),this.cssPrefix="-o-",this.domPrefix="O";else if(/konqueror/.test(a))this.KONQUEROR=!0,this.model="konqueror",this.version=a.replace(/(.*)konqueror\/([^;]+);(.*)/,"$2"),this.cssPrefix="-khtml-",this.domPrefix="Khtml";else if(/(msie|trident)/i.test(a))this.IE=!0,this.model="ie",/rv:((?:\d|\.)+)/.test(a)?this.version=a.match(/rv:((?:\d|\.)+)/)[1]:this.version=a.replace(/(.*)\smsie\s([^;]+);(.*)/,"$2"),this.cssPrefix="-ms-",this.domPrefix="ms";else if(/gecko/.test(a)){this.cssPrefix="-moz-",this.domPrefix="Moz",this.GECKO=!0;var c=/(camino|chimera|epiphany|minefield|firefox|firebird|phoenix|galeon|iceweasel|k\-meleon|seamonkey|netscape|songbird|sylera)/;if(c.test(a))this.model=a.match(c)[1],this.version=a.replace(new RegExp("(.*)"+this.model+"/([^;\\s$]+)(.*)"),"$2");else{this.model="mozilla";var d=/(.*)rv:([^)]+)(.*)/;d.test(a)&&(this.version=a.replace(d,"$2"))}}},debug:function(){var a="known browsers: (ie, gecko, opera, safari, konqueror) \n";a+=[this.IE,this.GECKO,this.OPERA,this.SAFARI,this.KONQUEROR]+"\n",a+="cssPrefix -> "+this.cssPrefix+"\n",a+="domPrefix -> "+this.domPrefix+"\n",a+="model -> "+this.model+"\n",a+="version -> "+this.version+"\n",a+="\n",a+="original UA -> "+this.userAgent,alert(a)}};return a.init(),a}),Ink.createModule("Ink.Dom.Css",1,[],function(){"use strict";var a="defaultView"in document&&"getComputedStyle"in document.defaultView?document.defaultView.getComputedStyle:window.getComputedStyle,b={addRemoveClassName:function(a,b,c){return c?this.addClassName(a,b):void this.removeClassName(a,b)},addClassName:function(a,c){if(a=Ink.i(a),!a||!c)return null;c=(""+c).split(/[, ]+/);for(var d=0,e=c.length;e>d;d++)c[d].replace(/^\s+|\s+$/g,"")&&("undefined"!=typeof a.classList?a.classList.add(c[d]):b.hasClassName(a,c[d])||(a.className+=(a.className?" ":"")+c[d]))},removeClassName:function(a,b){if(a=Ink.i(a),!a||!b)return null;b=(""+b).split(/[, ]+/);var c=0,d=b.length;if("undefined"!=typeof a.classList)for(;d>c;c++)a.classList.remove(b[c]);else{for(var e=a.className||"",f;d>c;c++)f=new RegExp("(^|\\s+)"+b[c]+"(\\s+|$)"),e=e.replace(f," ");a.className=e.replace(/^\s+/,"").replace(/\s+$/,"")}},setClassName:function(a,b,c){this.addRemoveClassName(a,b,c||!1)},hasClassName:function(a,b,c){if(a=Ink.i(a),!a||!b)return!1;b=(""+b).split(/[, ]+/);for(var d=0,e=b.length,f,g;e>d;d++){if("undefined"!=typeof a.classList)f=a.classList.contains(b[d]);else{var h=a.className;h===b[d]?f=!0:(g=new RegExp("(^|\\s)"+b[d]+"(\\s|$)"),f=g.test(h))}if(f&&!c)return!0;if(!f&&c)return!1}return c?!0:!1},blinkClass:function(a,c,d,e){a=Ink.i(a),b.addRemoveClassName(a,c,!e),setTimeout(function(){b.addRemoveClassName(a,c,e)},Number(d)||100)},toggleClassName:function(a,c,d){return a&&c?"undefined"!=typeof d?b.addRemoveClassName(a,c,d):void("undefined"==typeof a.classList||/[, ]/.test(c)?b.hasClassName(a,c)?b.removeClassName(a,c):b.addClassName(a,c):(a=Ink.i(a),null!==a&&a.classList.toggle(c))):!1},setOpacity:function(a,b){if(a=Ink.i(a),null!==a){var c=1;isNaN(Number(b))||(c=0>=b?0:1>=b?b:100>=b?b/100:1),"undefined"!=typeof a.style.opacity?a.style.opacity=c:a.style.filter="alpha(opacity:"+(100*c|0)+")"}},_camelCase:function(a){return a?a.replace(/-(\w)/g,function(a,b){return b.toUpperCase()}):a},getStyle:function(b,c){if(b=Ink.i(b),null!==b&&b.style){c="float"===c?"cssFloat":this._camelCase(c);var d=b.style[c];if(!a||d&&"auto"!==d)!d&&b.currentStyle&&(d=b.currentStyle[c],"auto"!==d||"width"!==c&&"height"!==c||(d=b["offset"+c.charAt(0).toUpperCase()+c.slice(1)]+"px"));else{var e=a(b,null);d=e?e[c]:null}if("opacity"===c)return d?parseFloat(d,10):1;if("borderTopWidth"===c||"borderBottomWidth"===c||"borderRightWidth"===c||"borderLeftWidth"===c){if("thin"===d)return"1px";if("medium"===d)return"3px";if("thick"===d)return"5px"}return"auto"===d?null:d}},setStyle:function(a,b){if(a=Ink.i(a),null!==a)if("string"==typeof b)a.style.cssText+="; "+b,-1!==b.indexOf("opacity")&&this.setOpacity(a,b.match(/opacity:\s*(\d?\.?\d*)/)[1]);else for(var c in b)b.hasOwnProperty(c)&&("opacity"===c?this.setOpacity(a,b[c]):"float"===c||"cssFloat"===c?"undefined"==typeof a.style.styleFloat?a.style.cssFloat=b[c]:a.style.styleFloat=b[c]:a.style[c]=b[c])},show:function(a,b){a=Ink.i(a),null!==a&&(a.style.display=b||"")},hide:function(a){a=Ink.i(a),null!==a&&(a.style.display="none")},showHide:function(a,b){a=Ink.i(a),a&&(a.style.display=b?"":"none")},toggle:function(a,b){a=Ink.i(a),null!==a&&("undefined"!=typeof b?b===!0?this.show(a):this.hide(a):"none"===this.getStyle(a,"display").toLowerCase()?this.show(a):this.hide(a))},_getRefTag:function(a){if(a.firstElementChild)return a.firstElementChild;for(var b=a.firstChild;b;b=b.nextSibling)if(1===b.nodeType)return b;return null},appendStyleTag:function(a,b,c){c=Ink.extendObj({type:"text/css",force:!1},c||{});var d=document.getElementsByTagName("style"),e=!1,f=!0,g,h;for(g=0,h=d.length;h>g;g++)e=d[g].innerHTML,e.indexOf(a)>=0&&(f=!1);if(f){var i=document.createElement("style"),j=document.getElementsByTagName("head")[0],k=!1,l="";i.type=c.type,l+=a+" {",l+=b,l+="} ","undefined"!=typeof i.styleSheet?i.styleSheet.cssText=l:i.appendChild(document.createTextNode(l)),c.force?j.appendChild(i):(k=this._getRefTag(j),k&&j.insertBefore(i,k))}},appendStylesheet:function(a,b){b=Ink.extendObj({media:"screen",type:"text/css",force:!1},b||{});var c,d=document.createElement("link"),e=document.getElementsByTagName("head")[0];d.media=b.media,d.type=b.type,d.href=a,d.rel="Stylesheet",b.force?e.appendChild(d):(c=this._getRefTag(e),c&&e.insertBefore(d,c))},_loadingCSSFiles:{},_loadedCSSFiles:{},appendStylesheetCb:function(a,b){if(!a)return b(a);if(this._loadedCSSFiles[a])return b(a);var c=this._loadingCSSFiles[a];if(c)return c.push(b);this._loadingCSSFiles[a]=[b];var d=document.createElement("link");d.type="text/css",d.rel="stylesheet",d.href=a;var e=document.getElementsByTagName("head")[0];e.appendChild(d);var f=document.createElement("img");f.onerror=Ink.bindEvent(function(a,b){var c=b;this._loadedCSSFiles[c]=!0;for(var d=this._loadingCSSFiles[c],e=0,f=d.length;f>e;++e)d[e](c);delete this._loadingCSSFiles[c]},this,a),f.src=a},decToHex:function(a){var b=function(a){return 1===a.length&&(a="0"+a),a=a.toUpperCase()};if("object"==typeof a){var c=b(parseInt(a.r,10).toString(16)),d=b(parseInt(a.g,10).toString(16)),e=b(parseInt(a.b,10).toString(16));return c+d+e}a+="";var f=a.match(/\((\d+),\s?(\d+),\s?(\d+)\)/);return null!==f?b(parseInt(f[1],10).toString(16))+b(parseInt(f[2],10).toString(16))+b(parseInt(f[3],10).toString(16)):b(parseInt(a,10).toString(16))},hexToDec:function(a){return 0===a.indexOf("#")&&(a=a.substr(1)),6===a.length?{r:parseInt(a.substr(0,2),16),g:parseInt(a.substr(2,2),16),b:parseInt(a.substr(4,2),16)}:3===a.length?{r:parseInt(a.charAt(0)+a.charAt(0),16),g:parseInt(a.charAt(1)+a.charAt(1),16),b:parseInt(a.charAt(2)+a.charAt(2),16)}:a.length<=2?parseInt(a,16):void 0},getPropertyFromStylesheet:function(a,b){var c=this.getRuleFromStylesheet(a);return c?c.style[b]:null},getPropertyFromStylesheet2:function(a,b){for(var c=this.getRulesFromStylesheet(a),d,e=0,f=c.length;f>e;e++)if(d=c[e].style[b],null!==d&&void 0!==d)return d;return null},getRuleFromStylesheet:function(a){var b,c,d,e,f,g=document.styleSheets;if(!g)return null;for(var h=0,i=document.styleSheets.length;i>h;++h){if(b=document.styleSheets[h],c=b.rules?b.rules:b.cssRules,!c)return null;for(d=0,e=c.length;e>d;++d)if(f=c[d],f.selectorText&&f.selectorText===a)return f}return null},getRulesFromStylesheet:function(a){var b=[],c,d,e,f,g,h=document.styleSheets;if(!h)return b;for(var i=0,j=document.styleSheets.length;j>i;++i){if(c=document.styleSheets[i],d=c.rules?c.rules:c.cssRules,!d)return null;for(e=0,f=d.length;f>e;++e)g=d[e],g.selectorText&&g.selectorText===a&&b.push(g)}return b},getPropertiesFromRule:function(a){var b=this.getRuleFromStylesheet(a),c={},d,e,f;b=b.style.cssText;var g=b.split(";"),h,i,j,k;for(e=0,f=g.length;f>e;++e)" "===g[e].charAt(0)&&(g[e]=g[e].substring(1)),h=g[e].split(":"),d=this._camelCase(h[0].toLowerCase()),i=h[1],i&&(i=i.substring(1),"padding"===d||"margin"===d||"borderWidth"===d?("borderWidth"===d?(j="border",k="Width"):(j=d,k=""),-1!==i.indexOf(" ")?(i=i.split(" "),c[j+"Top"+k]=i[0],c[j+"Bottom"+k]=i[0],c[j+"Left"+k]=i[1],c[j+"Right"+k]=i[1]):(c[j+"Top"+k]=i,c[j+"Bottom"+k]=i,c[j+"Left"+k]=i,c[j+"Right"+k]=i)):"borderRadius"===d?-1!==i.indexOf(" ")?(i=i.split(" "),c.borderTopLeftRadius=i[0],c.borderBottomRightRadius=i[0],c.borderTopRightRadius=i[1],c.borderBottomLeftRadius=i[1]):(c.borderTopLeftRadius=i,c.borderTopRightRadius=i,c.borderBottomLeftRadius=i,c.borderBottomRightRadius=i):c[d]=i);return c},changeFontSize:function(a,b,c,d,e){var f=this;Ink.requireModules(["Ink.Dom.Selector_1"],function(g){var h;if("string"!=typeof a?h="1st argument must be a CSS selector rule.":"number"!=typeof b?h="2nd argument must be a number.":void 0!==c&&"+"!==c&&"*"!==c?h='3rd argument must be one of "+", "*".':void 0!==d&&("number"!=typeof d||0>=d)?h="4th argument must be a positive number.":void 0!==e&&("number"!=typeof e||e>e)&&(h="5th argument must be a positive number greater than minValue."),h)throw new TypeError(h);var i,j,k=g.select(a);void 0===d&&(d=1),c="*"===c?function(a,b){return a*b}:function(a,b){return a+b};for(var l=0,m=k.length;m>l;++l)j=k[l],i=parseFloat(f.getStyle(j,"fontSize")),i=c(i,b),d>i||"number"==typeof e&&i>e||(j.style.fontSize=i+"px")})}};return b}),Ink.createModule("Ink.Dom.Element",1,[],function(){"use strict";function a(a){var b={};try{b=a.getBoundingClientRect()}catch(c){b={top:a.offsetTop,left:a.offsetLeft}}return b}var b="function"==typeof document.createRange&&"function"==typeof window.Range.prototype.createContextualFragment,c="Ink.Dom.Element tbody: "+Math.random(),d=function(){var a=document.createElement("div");return a.innerHTML="<table>",0!==a.getElementsByTagName("tbody").length}(),e={isDOMElement:function(a){return null!==a&&"object"==typeof a&&"nodeType"in a&&1===a.nodeType},get:function(a){return"undefined"!=typeof a?"string"==typeof a?document.getElementById(a):a:null},create:function(a,b){var c=document.createElement(a);if(b)for(var d in b)b.hasOwnProperty(d)&&(d in e?e[d](c,b[d]):"className"===d||"class"===d?c.className=b.className||b["class"]:c.setAttribute(d,b[d]));return c},remove:function(a){a=Ink.i(a);var b;a&&(b=a.parentNode)&&b.removeChild(a)},scrollTo:function(a){if(a=e.get(a)){if(a.scrollIntoView)return a.scrollIntoView();var b={},c=0,d=0;do c+=a.offsetTop||0,d+=a.offsetLeft||0,a=a.offsetParent;while(a);b={x:d,y:c},window.scrollTo(b.x,b.y)}},offsetTop:function(a){return e.offset(a)[1]},offsetLeft:function(a){return e.offset(a)[0]},positionedOffset:function(a){var b=0,c=0;a=e.get(a);do if(b+=a.offsetTop||0,c+=a.offsetLeft||0,a=a.offsetParent){if("body"===a.tagName.toLowerCase())break;var d=a.style.position;if(!d&&a.currentStyle&&(d=a.currentStyle.position),(!d||"auto"===d)&&"undefined"!=typeof getComputedStyle){var f=getComputedStyle(a,null);d=f?f.position:null}if("relative"===d||"absolute"===d)break}while(a);return[c,b]},offset:function(b){b=Ink.i(b);var c=[0,0],d=b.ownerDocument,e=d.documentElement,f=a(b),g=d.body,h=e.clientTop||g.clientTop||0,i=e.clientLeft||g.clientLeft||0,j=d.pageYOffset||e.scrollTop||g.scrollTop,k=d.pageXOffset||e.scrollLeft||g.scrollLeft,l=f.top+j-h,m=f.left+k-i;return c=[m,l]},scroll:function(a){return a=a?Ink.i(a):document.body,[window.pageXOffset?window.pageXOffset:a.scrollLeft,window.pageYOffset?window.pageYOffset:a.scrollTop]},_getPropPx:function(a,b){var c,d,e=a.getPropertyValue?a.getPropertyValue(b):a[b];return e?(d=e.indexOf("px"),c=-1===d?0:parseFloat(e,10)):c=0,c},offset2:function(a){return e.offset(a)},hasAttribute:function(a,b){return a=Ink.i(a),a.hasAttribute?a.hasAttribute(b):!!a.getAttribute(b)},insertAfter:function(a,b){(b=e.get(b))&&(null!==b.nextSibling?b.parentNode.insertBefore(a,b.nextSibling):b.parentNode.appendChild(a))},insertBefore:function(a,b){(b=e.get(b))&&b.parentNode.insertBefore(a,b)},insertTop:function(a,b){(b=e.get(b))&&(b.firstChild?b.insertBefore(a,b.firstChild):b.appendChild(a))},insertBottom:function(a,b){b=Ink.i(b),b.appendChild(a)},textContent:function(a){a=Ink.i(a);var b,c,d,f;switch(a&&a.nodeType){case 9:return e.textContent(a.documentElement||a.body&&a.body.parentNode||a.body);case 1:if(b="textContent"in a?a.textContent:a.innerText,"undefined"!=typeof b)return b;case 11:if(b=a.textContent,"undefined"!=typeof b)return b;if(a.firstChild===a.lastChild)return e.textContent(a.firstChild);for(b=[],d=a.childNodes,c=0,f=d.length;f>c;++c)b.push(e.textContent(d[c]));return b.join("");case 3:case 4:return a.nodeValue}return""},setTextContent:function(a,b){switch(a=Ink.i(a),a&&a.nodeType){case 1:if("innerText"in a){a.innerText=b;break}case 11:if("textContent"in a){a.textContent=b;break}case 9:for(;a.firstChild;)a.removeChild(a.firstChild);if(""!==b){var c=a.ownerDocument||a;a.appendChild(c.createTextNode(b))}break;case 3:case 4:a.nodeValue=b}},isLink:function(a){var b=a&&1===a.nodeType&&(/^a|area$/i.test(a.tagName)||a.hasAttributeNS&&a.hasAttributeNS("http://www.w3.org/1999/xlink","href"));return!!b},isAncestorOf:function(a,b){if(!b||!a)return!1;if(b.compareDocumentPosition)return 0!==(16&a.compareDocumentPosition(b));for(;b=b.parentNode;)if(b===a)return!0;return!1},descendantOf:function(a,b){return a!==b&&e.isAncestorOf(a,b)},firstElementChild:function(a){if(!a)return null;if("firstElementChild"in a)return a.firstElementChild;for(var b=a.firstChild;b&&1!==b.nodeType;)b=b.nextSibling;return b},lastElementChild:function(a){if(!a)return null;if("lastElementChild"in a)return a.lastElementChild;for(var b=a.lastChild;b&&1!==b.nodeType;)b=b.previousSibling;return b},nextElementSibling:function(a){var b=null;if(!a)return b;if("nextElementSibling"in a)return a.nextElementSibling;for(b=a.nextSibling;b&&1!==b.nodeType;)b=b.nextSibling;return b},previousElementSibling:function(a){
var b=null;if(!a)return b;if("previousElementSibling"in a)return a.previousElementSibling;for(b=a.previousSibling;b&&1!==b.nodeType;)b=b.previousSibling;return b},elementWidth:function(a){return"string"==typeof a&&(a=document.getElementById(a)),a.offsetWidth},elementHeight:function(a){return"string"==typeof a&&(a=document.getElementById(a)),a.offsetHeight},elementLeft:function(a){return e.offsetLeft(a)},elementTop:function(a){return e.offsetTop(a)},elementDimensions:function(a){return a=Ink.i(a),[a.offsetWidth,a.offsetHeight]},outerDimensions:function(b){var c=a(b),d=Ink.getModule("Ink.Dom.Css_1"),e=Ink.bindMethod(d,"getStyle",b);return[c.right-c.left+parseFloat(e("marginLeft")||0)+parseFloat(e("marginRight")||0),c.bottom-c.top+parseFloat(e("marginTop")||0)+parseFloat(e("marginBottom")||0)]},inViewport:function(b,c){var d=a(Ink.i(b));return"boolean"==typeof c&&(c={partial:c,margin:0}),c=c||{},c.margin=c.margin||0,c.partial?d.bottom+c.margin>0&&d.left-c.margin<e.viewportWidth()&&d.top-c.margin<e.viewportHeight()&&d.right+c.margin>0:d.top+c.margin>0&&d.right-c.margin<e.viewportWidth()&&d.bottom-c.margin<e.viewportHeight()&&d.left+c.margin>0},isHidden:function(a){var b=a.offsetWidth,c=a.offsetHeight,d="tr"===a.tagName.toLowerCase(),e=Ink.getModule("Ink.Dom.Css_1");return 0!==b||0!==c||d?0===b||0===c||d?"none"===e.getStyle(a,"display").toLowerCase():!1:!0},isVisible:function(a){return!this.isHidden(a)},clonePosition:function(a,b){var c=e.offset(b);return a.style.left=c[0]+"px",a.style.top=c[1]+"px",a},ellipsizeText:function(a){(a=Ink.i(a))&&(a.style.overflow="hidden",a.style.whiteSpace="nowrap",a.style.textOverflow="ellipsis")},findUpwardsHaving:function(a,b){for(;a&&1===a.nodeType;){if(b(a))return a;a=a.parentNode}return!1},findUpwardsByClass:function(a,b){var c=new RegExp("(^|\\s)"+b+"(\\s|$)"),d=function(a){var b=a.className;return b&&c.test(b)};return e.findUpwardsHaving(a,d)},findUpwardsByTag:function(a,b){b=b.toUpperCase();var c=function(a){return a.nodeName&&a.nodeName.toUpperCase()===b};return e.findUpwardsHaving(a,c)},findUpwardsById:function(a,b){var c=function(a){return a.id===b};return e.findUpwardsHaving(a,c)},findUpwardsBySelector:function(a,b){var c=Ink.getModule("Ink.Dom.Selector","1");if(!c)throw new Error("This method requires Ink.Dom.Selector");var d=function(a){return c.matchesSelector(a,b)};return e.findUpwardsHaving(a,d)},getChildrenText:function(a,b){var c,d,f,g=a.childNodes,h=g.length,i="";if(!a)return i;for(d=0;h>d;++d)c=g[d],c&&3===c.nodeType&&(f=e._trimString(String(c.data)),f.length>0?(i+=f,b&&a.removeChild(c)):a.removeChild(c));return i},_trimString:function(a){return String.prototype.trim?a.trim():a.replace(/^\s*/,"").replace(/\s*$/,"")},getSelectValues:function(a){for(var b=Ink.i(a),c=[],d=0;d<b.options.length;++d)c.push(b.options[d].value);return c},_normalizeData:function(a){for(var b,c=[],d=0,e=a.length;e>d;++d)b=a[d],b instanceof Array?1===b.length&&b.push(b[0]):b=[b,b],c.push(b);return c},fillSelect:function(a,b,c,d){var f=Ink.i(a);if(f){f.innerHTML="";var g,h;c||(h=document.createElement("option"),h.setAttribute("value",""),f.appendChild(h)),b=e._normalizeData(b);for(var i=0,j=b.length;j>i;++i)g=b[i],h=document.createElement("option"),h.setAttribute("value",g[0]),g.length>2&&h.setAttribute("extra",g[2]),h.appendChild(document.createTextNode(g[1])),g[0]===d&&h.setAttribute("selected","selected"),f.appendChild(h)}},fillRadios:function(a,b,c,d,f,g){a=Ink.i(a);var h=document.createElement("span");e.insertAfter(h,a),c=e._normalizeData(c);var i,j;d||(j=document.createElement("input"),j.setAttribute("type","radio"),j.setAttribute("name",b),j.setAttribute("value",""),h.appendChild(j),g&&h.appendChild(document.createElement(g)));for(var k=0;k<c.length;++k)i=c[k],j=document.createElement("input"),j.setAttribute("type","radio"),j.setAttribute("name",b),j.setAttribute("value",i[0]),h.appendChild(j),h.appendChild(document.createTextNode(i[1])),g&&h.appendChild(document.createElement(g)),i[0]===f&&(j.checked=!0);return h},fillChecks:function(a,b,c,d,f){a=Ink.i(a);var g=document.createElement("span");e.insertAfter(g,a),c=e._normalizeData(c),"]"!==b.substring(b.length-1)&&(b+="[]");for(var h,i,j=0;j<c.length;++j)h=c[j],i=document.createElement("input"),i.setAttribute("type","checkbox"),i.setAttribute("name",b),i.setAttribute("value",h[0]),g.appendChild(i),g.appendChild(document.createTextNode(h[1])),f&&g.appendChild(document.createElement(f)),h[0]===d&&(i.checked=!0);return g},parentIndexOf:function(a,b){if(b||(b=a,a=a.parentNode),!a)return!1;for(var c=0,d=a.children.length;d>c;++c)if(a.children[c]===b)return c;return!1},nextSiblings:function(a){if(a=Ink.i(a),"object"==typeof a&&null!==a&&a.nodeType&&1===a.nodeType){for(var b=[],c=a.parentNode.children,d=e.parentIndexOf(a.parentNode,a),f=++d,g=c.length;g>f;f++)b.push(c[f]);return b}return[]},previousSiblings:function(a){if(a=Ink.i(a),"object"==typeof a&&null!==a&&a.nodeType&&1===a.nodeType){for(var b=[],c=a.parentNode.children,d=e.parentIndexOf(a.parentNode,a),f=0,g=d;g>f;f++)b.push(c[f]);return b}return[]},siblings:function(a){if(a=Ink.i(a),"object"==typeof a&&null!==a&&a.nodeType&&1===a.nodeType){for(var b=[],c=a.parentNode.children,d=0,e=c.length;e>d;d++)a!==c[d]&&b.push(c[d]);return b}return[]},childElementCount:function(a){return a=Ink.i(a),"childElementCount"in a?a.childElementCount:a?e.siblings(a).length+1:0},_wrapElements:{TABLE:function(a,b){return d?a.innerHTML="<table>"+b+"<tbody><tr><td>"+c+"</tr></td></tbody></table>":a.innerHTML="<table>"+b+"</table>",a.firstChild},TBODY:function(a,b){return a.innerHTML="<table><tbody>"+b+"</tbody></table>",a.firstChild.getElementsByTagName("tbody")[0]},THEAD:function(a,b){return a.innerHTML="<table><thead>"+b+"</thead><tbody></tbody></table>",a.firstChild.getElementsByTagName("thead")[0]},TFOOT:function(a,b){return a.innerHTML="<table><tfoot>"+b+"</tfoot><tbody></tbody></table>",a.firstChild.getElementsByTagName("tfoot")[0]},TR:function(a,b){return a.innerHTML="<table><tbody><tr>"+b+"</tr></tbody></table>",a.firstChild.firstChild.firstChild}},_getWrapper:function(a,b){var f=a.nodeName&&a.nodeName.toUpperCase(),g=document.createElement("div"),h=e._wrapElements[f];if(!h)return g.innerHTML=b,g;if(g=h(g,b),d&&"TABLE"===f)for(var i=g.getElementsByTagName("td"),j=0,k=i.length;k>j;j++)if(i[j].innerHTML===c){var l=i[j].parentNode.parentNode;l.parentNode.removeChild(l)}return g},appendHTML:function(a,b){if(a=Ink.i(a),null!==a)for(var c=e._getWrapper(a,b);c.firstChild;)a.appendChild(c.firstChild)},prependHTML:function(a,b){if(a=Ink.i(a),null!==a)for(var c=e._getWrapper(a,b);c.lastChild;)a.insertBefore(c.lastChild,a.firstChild)},setHTML:function(a,b){if(a=Ink.i(a),null!==a)try{a.innerHTML=b}catch(c){e.clear(a),e.appendHTML(a,b)}},wrap:function(a,b){a=Ink.i(a),b=Ink.i(b);var c=a.nextSibling,d=a.parentNode;return b.appendChild(a),null!==c?d.insertBefore(b,c):d.appendChild(b),b},unwrap:function(a,b){a=Ink.i(a);var c;c="string"==typeof b?e.findUpwardsBySelector(a,b):"object"==typeof b&&b.tagName?e.findUpwardsHaving(a,function(a){return a===b}):a.parentNode,c&&c.parentNode&&e.insertBefore(a,c)},replace:function(a,b){a=Ink.i(a),null!==a&&a.parentNode.replaceChild(b,a)},removeTextNodeChildren:function(a){if(a=Ink.i(a),null!==a){var b,c,d=a;for(a=a.firstChild;a;)c=3===a.nodeType,b=a,a=a.nextSibling,c&&d.removeChild(b)}},htmlToFragment:b?function(a){var b;return"string"!=typeof a?document.createDocumentFragment():(b=document.createRange(),b.selectNode(document.body),b.createContextualFragment(a))}:function(a){var b=document.createDocumentFragment(),c,d;if("string"!=typeof a)return b;for(c=document.createElement("div"),c.innerHTML=a;d=c.firstChild;)b.appendChild(d);return b},_camelCase:function(a){return a?a.replace(/-(\w)/g,function(a,b){return b.toUpperCase()}):a},data:function(a){var b;if("object"!=typeof a&&"string"!=typeof a)throw"[Ink.Dom.Element.data] :: Invalid selector defined";if("object"==typeof a)b=a;else{var c=Ink.getModule("Ink.Dom.Selector",1);if(!c)throw"[Ink.Dom.Element.data] :: this method requires Ink.Dom.Selector - v1";if(b=c.select(a),b.length<=0)throw"[Ink.Dom.Element.data] :: Can't find any element with the specified selector";b=b[0]}var d={},f=b.attributes||[],g,h,i;if(f)for(var j=0,k=f.length;k>j;++j)g=f[j],h=g.name,i=g.value,h&&0===h.indexOf("data-")&&(d[e._camelCase(h.replace("data-",""))]=i);return d},clear:function(a,b){for(;b=a.lastChild;)a.removeChild(b)},moveCursorTo:function(a,b){if(a=Ink.i(a),null!==a)if(a.setSelectionRange)a.setSelectionRange(b,b);else{var c=a.createTextRange();c.collapse(!0),c.moveEnd("character",b),c.moveStart("character",b),c.select()}},pageWidth:function(){var a;a=window.innerWidth&&window.scrollMaxX?window.innerWidth+window.scrollMaxX:document.body.scrollWidth>document.body.offsetWidth?document.body.scrollWidth:document.body.offsetWidth;var b;return window.self.innerWidth?b=document.documentElement.clientWidth?document.documentElement.clientWidth:window.self.innerWidth:document.documentElement&&document.documentElement.clientWidth?b=document.documentElement.clientWidth:document.body&&(b=document.body.clientWidth),b>a?a:b},pageHeight:function(){var a;a=window.innerHeight&&window.scrollMaxY?window.innerHeight+window.scrollMaxY:document.body.scrollHeight>document.body.offsetHeight?document.body.scrollHeight:document.body.offsetHeight;var b;return window.self.innerHeight?b=window.self.innerHeight:document.documentElement&&document.documentElement.clientHeight?b=document.documentElement.clientHeight:document.body&&(b=document.body.clientHeight),b>a?b:a},viewportWidth:function(){return"undefined"!=typeof window.innerWidth?window.innerWidth:document.documentElement&&"undefined"!=typeof document.documentElement.offsetWidth?document.documentElement.offsetWidth:void 0},viewportHeight:function(){return"undefined"!=typeof window.innerHeight?window.innerHeight:document.documentElement&&"undefined"!=typeof document.documentElement.offsetHeight?document.documentElement.offsetHeight:void 0},scrollWidth:function(){return"undefined"!=typeof window.self.pageXOffset?window.self.pageXOffset:"undefined"!=typeof document.documentElement&&"undefined"!=typeof document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft},scrollHeight:function(){return"undefined"!=typeof window.self.pageYOffset?window.self.pageYOffset:"undefined"!=typeof document.body&&"undefined"!=typeof document.body.scrollTop&&"undefined"!=typeof document.documentElement&&"undefined"!=typeof document.documentElement.scrollTop?document.body.scrollTop||document.documentElement.scrollTop:"undefined"!=typeof document.documentElement&&"undefined"!=typeof document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop}};return e}),Ink.createModule("Ink.Dom.Event",1,[],function(){var a=function(a,b,c){return c()}("bean",this,function(a,b){a=a||"bean",b=b||this;var c=window,d=b[a],e=/[^\.]*(?=\..*)\.|.*/,f=/\..*/,g="addEventListener",h="removeEventListener",i=document||{},j=i.documentElement||{},k=j[g],l=k?g:"attachEvent",m={},n=Array.prototype.slice,o=function(a,b){return a.split(b||" ")},p=function(a){return"string"==typeof a},q=function(a){return"function"==typeof a},r="click dblclick mouseup mousedown contextmenu mousewheel mousemultiwheel DOMMouseScroll mouseover mouseout mousemove selectstart selectend keydown keypress keyup orientationchange focus blur change reset select submit load unload beforeunload resize move DOMContentLoaded readystatechange message error abort scroll ",s="show input invalid touchstart touchmove touchend touchcancel gesturestart gesturechange gestureend textinputreadystatechange pageshow pagehide popstate hashchange offline online afterprint beforeprint dragstart dragenter dragover dragleave drag drop dragend loadstart progress suspend emptied stalled loadmetadata loadeddata canplay canplaythrough playing waiting seeking seeked ended durationchange timeupdate play pause ratechange volumechange cuechange checking noupdate downloading cached updateready obsolete ",t=function(a,b,c){for(c=0;c<b.length;c++)b[c]&&(a[b[c]]=1);return a}({},o(r+(k?s:""))),u=function(){var a="compareDocumentPosition"in j?function(a,b){return b.compareDocumentPosition&&16===(16&b.compareDocumentPosition(a))}:"contains"in j?function(a,b){return b=9===b.nodeType||b===window?j:b,b!==a&&b.contains(a)}:function(a,b){for(;a=a.parentNode;)if(a===b)return 1;return 0},b=function(b){var c=b.relatedTarget;return c?c!==this&&"xul"!==c.prefix&&!/document/.test(this.toString())&&!a(c,this):null==c};return{mouseenter:{base:"mouseover",condition:b},mouseleave:{base:"mouseout",condition:b},mousewheel:{base:/Firefox/.test(navigator.userAgent)?"DOMMouseScroll":"mousewheel"}}}(),v=function(){var a=o("altKey attrChange attrName bubbles cancelable ctrlKey currentTarget detail eventPhase getModifierState isTrusted metaKey relatedNode relatedTarget shiftKey srcElement target timeStamp type view which propertyName path"),b=a.concat(o("button buttons clientX clientY dataTransfer fromElement offsetX offsetY pageX pageY screenX screenY toElement movementX movementY region")),d=b.concat(o("wheelDelta wheelDeltaX wheelDeltaY wheelDeltaZ axis")),e=a.concat(o("char charCode key keyCode keyIdentifier keyLocation location isComposing code")),f=a.concat(o("data")),g=a.concat(o("touches targetTouches changedTouches scale rotation")),h=a.concat(o("data origin source")),k=a.concat(o("state")),l=/over|out/,m=[{reg:/key/i,fix:function(a,b){return b.keyCode=a.keyCode||a.which,e}},{reg:/click|mouse(?!(.*wheel|scroll))|menu|drag|drop/i,fix:function(a,c,d){return c.rightClick=3===a.which||2===a.button,c.pos={x:0,y:0},a.pageX||a.pageY?(c.clientX=a.pageX,c.clientY=a.pageY):(a.clientX||a.clientY)&&(c.clientX=a.clientX+i.body.scrollLeft+j.scrollLeft,c.clientY=a.clientY+i.body.scrollTop+j.scrollTop),l.test(d)&&(c.relatedTarget=a.relatedTarget||a[("mouseover"==d?"from":"to")+"Element"]),b}},{reg:/mouse.*(wheel|scroll)/i,fix:function(){return d}},{reg:/^text/i,fix:function(){return f}},{reg:/^touch|^gesture/i,fix:function(){return g}},{reg:/^message$/i,fix:function(){return h}},{reg:/^popstate$/i,fix:function(){return k}},{reg:/.*/,fix:function(){return a}}],n={},p=function(a,b,d){if(arguments.length&&(a=a||((b.ownerDocument||b.document||b).parentWindow||c).event,this.originalEvent=a,this.isNative=d,this.isBean=!0,a)){var e=a.type,f=a.target||a.srcElement,g,h,i,j,k;if(this.target=f&&3===f.nodeType?f.parentNode:f,d){if(k=n[e],!k)for(g=0,h=m.length;h>g;g++)if(m[g].reg.test(e)){n[e]=k=m[g].fix;break}for(j=k(a,this,e),g=j.length;g--;)!((i=j[g])in this)&&i in a&&(this[i]=a[i])}}};return p.prototype.preventDefault=function(){if(this.originalEvent.preventDefault)this.originalEvent.preventDefault();else try{this.originalEvent.returnValue=!1}catch(a){}},p.prototype.stopPropagation=function(){this.originalEvent.stopPropagation?this.originalEvent.stopPropagation():this.originalEvent.cancelBubble=!0},p.prototype.stop=function(){this.preventDefault(),this.stopPropagation(),this.stopped=!0},p.prototype.stopImmediatePropagation=function(){this.originalEvent.stopImmediatePropagation&&this.originalEvent.stopImmediatePropagation(),this.isImmediatePropagationStopped=function(){return!0}},p.prototype.isImmediatePropagationStopped=function(){return this.originalEvent.isImmediatePropagationStopped&&this.originalEvent.isImmediatePropagationStopped()},p.prototype.clone=function(a){var b=new p(this,this.element,this.isNative);return b.currentTarget=a,b},p}(),w=function(a,b){return k||b||a!==i&&a!==c?a:j},x=function(){var a=function(a,b,c,d){var e=function(c,e){return b.apply(a,d?n.call(e,c?0:1).concat(d):e)},f=function(c,d){return b.__beanDel?b.__beanDel.ft(c.target,a):d},g=c?function(a){var b=f(a,this);return c.apply(b,arguments)?(a&&(a.currentTarget=b),e(a,arguments)):void 0}:function(a){return b.__beanDel&&(a=a.clone(f(a))),e(a,arguments)};return g.__beanDel=b.__beanDel,g},b=function(b,c,d,e,f,g,h){var i=u[c],j;"unload"==c&&(d=D(E,b,c,d,e)),i&&(i.condition&&(d=a(b,d,i.condition,g)),c=i.base||c),this.isNative=j=t[c]&&!!b[l],this.customType=!k&&!j&&c,this.element=b,this.type=c,this.original=e,this.namespaces=f,this.eventType=k||j?c:"propertychange",this.target=w(b,j),this[l]=!!this.target[l],this.root=h,this.handler=a(b,d,null,g)};return b.prototype.inNamespaces=function(a){var b,c,d=0;if(!a)return!0;if(!this.namespaces)return!1;for(b=a.length;b--;)for(c=this.namespaces.length;c--;)a[b]==this.namespaces[c]&&d++;return a.length===d},b.prototype.matches=function(a,b,c){return!(this.element!==a||b&&this.original!==b||c&&this.handler!==c)},b}(),y=function(){var a={},b=function(c,d,e,f,g,h){var i=g?"r":"$";if(d&&"*"!=d){var j=0,k,l=a[i+d],m="*"==c;if(!l)return;for(k=l.length;k>j;j++)if((m||l[j].matches(c,e,f))&&!h(l[j],l,j,d))return}else for(var n in a)n.charAt(0)==i&&b(c,n.substr(1),e,f,g,h)},c=function(b,c,d,e){var f,g=a[(e?"r":"$")+c];if(g)for(f=g.length;f--;)if(!g[f].root&&g[f].matches(b,d,null))return!0;return!1},d=function(a,c,d,e){var f=[];return b(a,c,d,null,e,function(a){return f.push(a)}),f},e=function(b){var c=!b.root&&!this.has(b.element,b.type,null,!1),d=(b.root?"r":"$")+b.type;return(a[d]||(a[d]=[])).push(b),c},f=function(c){b(c.element,c.type,null,c.handler,c.root,function(b,c,d){return c.splice(d,1),b.removed=!0,0===c.length&&delete a[(b.root?"r":"$")+b.type],!1})},g=function(){var b,c=[];for(b in a)"$"==b.charAt(0)&&(c=c.concat(a[b]));return c};return{has:c,get:d,put:e,del:f,entries:g}}(),z,A=function(a){z=arguments.length?a:i.querySelectorAll?function(a,b){return b.querySelectorAll(a)}:function(){throw new Error("Bean: No selector engine installed")}},B=function(a,b){if(k||!b||!a||a.propertyName=="_on"+b){var c=y.get(this,b||a.type,null,!1),d=c.length,e=0;for(a=new v(a,this,!0),b&&(a.type=b);d>e&&!a.isImmediatePropagationStopped();e++)c[e].removed||c[e].handler.call(this,a)}},C=k?function(a,b,c){a[c?g:h](b,B,!1)}:function(a,b,c,d){var e;c?(y.put(e=new x(a,d||b,function(b){B.call(a,b,d)},B,null,null,!0)),d&&null==a["_on"+d]&&(a["_on"+d]=0),e.target.attachEvent("on"+e.eventType,e.handler)):(e=y.get(a,d||b,B,!0)[0],e&&(e.target.detachEvent("on"+e.eventType,e.handler),y.del(e)))},D=function(a,b,c,d,e){return function(){d.apply(this,arguments),a(b,c,e)}},E=function(a,b,c,d){var e=b&&b.replace(f,""),g=y.get(a,e,null,!1),h={},i,j;for(i=0,j=g.length;j>i;i++)c&&g[i].original!==c||!g[i].inNamespaces(d)||(y.del(g[i]),!h[g[i].eventType]&&g[i][l]&&(h[g[i].eventType]={t:g[i].eventType,c:g[i].type}));for(i in h)h.hasOwnProperty(i)&&(y.has(a,h[i].t,null,!1)||C(a,h[i].t,!1,h[i].c))},F=function(a,b){var c=function(b,c){for(var d,e=p(a)?z(a,c):a;b&&b!==c;b=b.parentNode)for(d=e.length;d--;)if(e[d]===b)return b},d=function(a){var d=c(a.target,this);d&&b.apply(d,arguments)};return d.__beanDel={ft:c,selector:a},d},G=k?function(a,b,d){var e=i.createEvent(a?"HTMLEvents":"UIEvents");e[a?"initEvent":"initUIEvent"](b,!0,!0,c,1),d.dispatchEvent(e)}:function(a,b,c){c=w(c,a),a?c.fireEvent("on"+b,i.createEventObject()):c["_on"+b]++},H=function(a,b,c){var d=p(b),g,h,i,j;if(d&&b.indexOf(" ")>0){for(b=o(b),j=b.length;j--;)H(a,b[j],c);return a}if(h=d&&b.replace(f,""),h&&u[h]&&(h=u[h].base),!b||d)(i=d&&b.replace(e,""))&&(i=o(i,".")),E(a,h,c,i);else if(q(b))E(a,null,b);else for(g in b)b.hasOwnProperty(g)&&H(a,g,b[g]);return a},I=function(a,b,c,d){var g,h,i,j,k,p,r;{if(void 0!==c||"object"!=typeof b){for(q(c)?(k=n.call(arguments,3),d=g=c):(g=d,k=n.call(arguments,4),d=F(c,g,z)),i=o(b),this===m&&(d=D(H,a,b,d,g)),j=i.length;j--;)r=y.put(p=new x(a,i[j].replace(f,""),d,g,o(i[j].replace(e,""),"."),k,!1)),p[l]&&r&&C(a,p.eventType,!0,p.customType);return a}for(h in b)b.hasOwnProperty(h)&&I.call(this,a,h,b[h])}},J=function(a,b,c,d){return I.apply(null,p(c)?[a,c,b,d].concat(arguments.length>3?n.call(arguments,5):[]):n.call(arguments))},K=function(){return I.apply(m,arguments)},L=function(a,b,c){var d=o(b),g,h,i,j,k;for(g=d.length;g--;)if(b=d[g].replace(f,""),(j=d[g].replace(e,""))&&(j=o(j,".")),j||c||!a[l])for(k=y.get(a,b,null,!1),c=[!1].concat(c),h=0,i=k.length;i>h;h++)k[h].inNamespaces(j)&&k[h].handler.apply(a,c);else G(t[b],b,a);return a},M=function(a,b,c){for(var d=y.get(b,c,null,!1),e=d.length,f=0,g,h;e>f;f++)d[f].original&&(g=[a,d[f].type],(h=d[f].handler.__beanDel)&&g.push(h.selector),g.push(d[f].original),I.apply(null,g));return a},N={on:I,add:J,one:K,off:H,remove:H,clone:M,fire:L,Event:v,setSelectorEngine:A,noConflict:function(){return b[a]=d,this}};if(c.attachEvent){var O=function(){var a,b=y.entries();for(a in b)b[a].type&&"unload"!==b[a].type&&H(b[a].element,b[a].type);c.detachEvent("onunload",O),c.CollectGarbage&&c.CollectGarbage()};c.attachEvent("onunload",O)}return A(Ink.ss),N}),b={KEY_BACKSPACE:8,KEY_TAB:9,KEY_RETURN:13,KEY_ESC:27,KEY_SPACE:32,KEY_LEFT:37,KEY_UP:38,KEY_RIGHT:39,KEY_DOWN:40,KEY_DELETE:46,KEY_HOME:36,KEY_END:35,KEY_PAGEUP:33,KEY_PAGEDOWN:34,KEY_INSERT:45,throttle:function(a,b,c){function d(g){var h=+new Date,i=h-e;if(c.preventDefault&&g&&"function"==typeof g.preventDefault&&g.preventDefault(),i>=b)return e=h,a.apply("bind"in c?c.bind:this,[].slice.call(arguments));var j=this,k=[].slice.call(arguments);f&&clearTimeout(f),f=setTimeout(function(){return f=null,d.apply(j,k)},b-i)}b=b||0,c=c||{};var e=0,f;return d},element:function(a){var b=a.delegationTarget||a.target||"mouseout"===a.type&&a.fromElement||"mouseleave"===a.type&&a.fromElement||"mouseover"===a.type&&a.toElement||"mouseenter"===a.type&&a.toElement||a.srcElement||null;return!b||3!==b.nodeType&&4!==b.nodeType?b:b.parentNode},relatedTarget:function(a){var b=a.relatedTarget||"mouseout"===a.type&&a.toElement||"mouseleave"===a.type&&a.toElement||"mouseover"===a.type&&a.fromElement||"mouseenter"===a.type&&a.fromElement||null;return!b||3!==b.nodeType&&4!==b.nodeType?b:b.parentNode},findElement:function(a,b,c){for(var d=this.element(a);;){if(d.nodeName.toLowerCase()===b.toLowerCase())return d;if(d=d.parentNode,!d)return c?!1:document;if(!d.parentNode)return c?!1:document}},observe:function(a,b,c,d){return a=Ink.i(a),a?(a.addEventListener?a.addEventListener(b,c,!!d):a.attachEvent("on"+b,c=Ink.bind(c,a)),c):void 0},observeOnce:function(a,c,d,e){var f=function(){return b.stopObserving(a,c,g),d.apply(this,arguments)},g=b.observe(a,c,f,e);return g},observeMulti:function(a,b,c,d){if("string"==typeof a?a=Ink.ss(a):a&&1===a.nodeType&&(a=[a]),!a[0])return!1;for(var e=0,f=a.length;f>e;e++)this.observe(a[e],b,c,d);return c},observeDelegated:function(a,c,d,e){return b.observe(a,c,function(c){var f=b.element(c);if(f&&f!==a)for(var g=f;g!==a&&g!==document&&g;){if(Ink.Dom.Selector_1.matchesSelector(g,d))return c.delegationTarget=g,e(c);g=g.parentNode}})},stopObserving:function(a,b,c,d){a=Ink.i(a),a&&(a.removeEventListener?a.removeEventListener(b,c,!!d):a.detachEvent("on"+b,c))},stop:function(a){null!==a.cancelBubble&&(a.cancelBubble=!0),a.stopPropagation&&a.stopPropagation(),a.preventDefault&&a.preventDefault(),window.attachEvent&&(a.returnValue=!1),null!==a.cancel&&(a.cancel=!0)},stopPropagation:function(a){null!==a.cancelBubble&&(a.cancelBubble=!0),a.stopPropagation&&a.stopPropagation()},stopDefault:function(a){a.preventDefault&&a.preventDefault(),window.attachEvent&&(a.returnValue=!1),null!==a.cancel&&(a.cancel=!0)},pointer:function(a){return{x:this.pointerX(a),y:this.pointerY(a)}},pointerX:function(a){return a.touches&&a.touches[0]&&a.touches[0].pageX||a.pageX||a.clientX},pointerY:function(a){return a.touches&&a.touches[0]&&a.touches[0].pageY||a.pageY||a.clientY},isLeftClick:function(a){if(window.addEventListener){if(0===a.button)return!0;if("touchend"===a.type&&null===a.button)return!0}else if(1===a.button)return!0;return!1},isRightClick:function(a){return 2===a.button},isMiddleClick:function(a){return window.addEventListener?1===a.button:4===a.button;return!1},getCharFromKeyboardEvent:function(a,b){var c=a.keyCode,d=String.fromCharCode(c),e=a.shiftKey;if(c>=65&&90>=c)return"boolean"==typeof b&&(e=b),e?d:d.toLowerCase();if(c>=96&&105>=c)return String.fromCharCode(48+(c-96));switch(c){case 109:case 189:return"-";case 107:case 187:return"+"}return d},debug:function(){}};return Ink.extendObj(b,a)}),Ink.createModule("Ink.Dom.FormSerialize",1,["Ink.Util.Array_1","Ink.Dom.Element_1","Ink.Dom.Selector_1"],function(a,b,c){"use strict";function d(c){return null!=c&&!b.isDOMElement(c)&&(a.isArray(c)||"string"!=typeof c&&"number"==typeof c.length)}function e(a){return d(a)?a:[a]}var f={serialize:function(b,c){c=c||{};var d={},e={},g=this.asPairs(b,{elements:!0,emptyArray:e,outputUnchecked:c.outputUnchecked});return null==g?g:(a.forEach(g,function(a){var b=/\[\]$/.test(a[0]),c=a[0].replace(/\[\]$/,""),g=a[1],h=a[2];g===e?d[c]=[]:f._resultsInArray(h)||b?c in d?(d[c]instanceof Array||(d[c]=[d[c]]),d[c].push(g)):b?d[c]=[g]:d[c]=g:d[c]=g}),d)},asPairs:function(b,d){function e(a,b,c){d.elements?h.push([a,b,c]):h.push([a,b])}function g(b){var f=b.nodeName.toLowerCase(),g=(b.type+"").toLowerCase();if("select"===f&&b.multiple){var h=!1;a.forEach(c.select("option:checked",b),function(a){e(b.name,a.value,b),h=!0}),!h&&"emptyArray"in d&&e(b.name,d.emptyArray,b)}else"input"!==f||"checkbox"!==g&&"radio"!==g||!d.outputUnchecked?e(b.name,b.value,b):e(b.name,null,b)}var h=[];if(d=d||{},b=Ink.i(b)){for(var i=a.filter(b.elements,function(a){return f._isSerialized(a,d)}),j=0,k=i.length;k>j;j++)g(i[j]);return h}return null},fillIn:function(a,b){if(!(a=Ink.i(a)))return null;var c;if("object"!=typeof b||d(b)){if(!d(b))return null;c=b}else c=f._objToPairs(b);return f._fillInPairs(a,c)},_objToPairs:function(a){var b=[],c;for(var d in a)if(a.hasOwnProperty(d)){c=e(a[d]);for(var f=0,g=c.length;g>f;f++)b.push([d,c[f]]);0===g&&b.push([d,[]])}return b},_fillInPairs:function(b,c){c=a.groupBy(c,{key:function(a){return a[0].replace(/\[\]$/,"")},adjacentGroups:!0}),c=a.map(c,function(b){var c=a.reduce(b,function(a,b){return[null,a[1].concat([b[1]])]},[null,[]])[1];return[b[0][0],c]});for(var d,g,h,i=0,j=c.length;j>i;i++){if(d=c[i][0],d in b)g=b[d];else{if(!(d+"[]"in b))continue;g=b[d+"[]"],d+="[]"}g=e(g),h=c[i][1],f._fillInOne(d,g,h)}},_fillInOne:function(a,c,d){var e=c[0],g=e.nodeName.toLowerCase(),h=e.getAttribute("type");h=h&&h.toLowerCase();var i="select"===g&&b.hasAttribute(e,"multiple");if("checkbox"===h||"radio"===h)f._fillInBoolean(c,d,"checked");else if(i)f._fillInBoolean(c[0].options,d,"selected");else{c.length!==d.length&&Ink.warn("Form had "+c.length+' inputs named "'+a+'", but received '+d.length+" values.");for(var j=0,k=Math.min(c.length,d.length);k>j;j+=1)c[j].value=d[j]}},_fillInBoolean:function(b,c,d){a.forEach(b,function(b){var e=a.inArray(b.value,c);b[d]=e})},_resultsInArray:function(a){var c=a.getAttribute("type"),d=a.nodeName.toLowerCase();return"checkbox"===c||"select"===d&&b.hasAttribute(a,"multiple")},_isSerialized:function(a,c){if(c=c||{},!b.isDOMElement(a))return!1;if(!b.hasAttribute(a,"name"))return!1;var d=a.nodeName.toLowerCase();return d&&"fieldset"!==d?"checkbox"===a.type||"radio"===a.type?c.outputUnchecked?!0:!!a.checked:!0:!1}};return f}),Ink.createModule("Ink.Dom.Loaded",1,[],function(){"use strict";var a={_contexts:[],run:function(a,b){b||(b=a,a=window);for(var c,d=0,e=this._contexts.length;e>d;d++)if(this._contexts[d][0]===a){c=this._contexts[d][1];break}c||(c={cbQueue:[],win:a,doc:a.document,root:a.document.documentElement,done:!1,top:!0},c.handlers={checkState:Ink.bindEvent(this._checkState,this,c),poll:Ink.bind(this._poll,this,c)},this._contexts.push([a,c]));var f=c.doc.addEventListener;c.add=f?"addEventListener":"attachEvent",c.rem=f?"removeEventListener":"detachEvent",c.pre=f?"":"on",c.det=f?"DOMContentLoaded":"onreadystatechange",c.wet=c.pre+"load";var g=c.handlers.checkState,h=/complete|loaded/.test(c.doc.readyState)&&"about:blank"!==c.win.location.toString();if(h)setTimeout(Ink.bind(function(){b.call(c.win,"lazy")},this),0);else{c.cbQueue.push(b),c.doc[c.add](c.det,g),c.win[c.add](c.wet,g);var i=1;try{i=c.win.frameElement}catch(j){}if(!f&&c.root&&c.root.doScroll){try{c.top=!i}catch(j){}c.top&&this._poll(c)}}},_checkState:function(a,b){if(a&&("readystatechange"!==a.type||/complete|loaded/.test(b.doc.readyState))){var c="load"===a.type?b.win:b.doc;c[b.rem](b.pre+a.type,b.handlers.checkState,!1),this._ready(b)}},_poll:function(a){try{a.root.doScroll("left")}catch(b){return setTimeout(a.handlers.poll,50)}this._ready(a)},_ready:function(a){if(!a.done){a.done=!0;for(var b=0;b<a.cbQueue.length;++b)a.cbQueue[b].call(a.win);a.cbQueue=[]}}};return a}),Ink.createModule("Ink.Dom.Selector",1,[],function(){"use strict";function a(a){return oa.test(a+"")}function b(){var a,b=[];return a=function(c,d){return b.push(c+=" ")>w.cacheLength&&delete a[b.shift()],a[c]=d}}function c(a){return a[L]=!0,a}function d(a){var b=E.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b=null}}function e(a,b,c,d){var e,f,g,h,i,l,m,n,o,p;if((b?b.ownerDocument||b:M)!==E&&D(b),b=b||E,c=c||[],!a||"string"!=typeof a)return c;if(1!==(h=b.nodeType)&&9!==h)return[];if(G&&!d){if(e=pa.exec(a))if(g=e[1]){if(9===h){if(f=b.getElementById(g),!f||!f.parentNode)return c;if(f.id===g)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(g))&&K(b,f)&&f.id===g)return c.push(f),c}else{if(e[2])return $.apply(c,b.getElementsByTagName(a)),c;if((g=e[3])&&N.getElementsByClassName&&b.getElementsByClassName)return $.apply(c,b.getElementsByClassName(g)),c}if(N.qsa&&!H.test(a)){if(m=!0,n=L,o=b,p=9===h&&a,1===h&&"object"!==b.nodeName.toLowerCase()){for(l=j(a),(m=b.getAttribute("id"))?n=m.replace(sa,"\\$&"):b.setAttribute("id",n),n="[id='"+n+"'] ",i=l.length;i--;)l[i]=n+k(l[i]);o=na.test(a)&&b.parentNode||b,p=l.join(",")}if(p)try{return $.apply(c,o.querySelectorAll(p)),c}catch(q){}finally{m||b.removeAttribute("id")}}}return s(a.replace(ha,"$1"),b,c,d)}function f(a,b){var c=b&&a,d=c&&(~b.sourceIndex||W)-(~a.sourceIndex||W);if(d)return d;if(c)for(;c=c.nextSibling;)if(c===b)return-1;return a?1:-1}function g(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function h(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function i(a){return c(function(b){return b=+b,c(function(c,d){for(var e,f=a([],c.length,b),g=f.length;g--;)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function j(a,b){var c,d,f,g,h,i,j,k=R[a+" "];if(k)return b?0:k.slice(0);for(h=a,i=[],j=w.preFilter;h;){(!c||(d=ia.exec(h)))&&(d&&(h=h.slice(d[0].length)||h),i.push(f=[])),c=!1,(d=ja.exec(h))&&(c=d.shift(),f.push({value:c,type:d[0].replace(ha," ")}),h=h.slice(c.length));for(g in w.filter)!(d=ma[g].exec(h))||j[g]&&!(d=j[g](d))||(c=d.shift(),f.push({value:c,type:g,matches:d}),h=h.slice(c.length));if(!c)break}return b?h.length:h?e.error(a):R(a,i).slice(0)}function k(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function l(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=P++;return b.first?function(b,c,f){for(;b=b[d];)if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j,k=O+" "+f;if(g){for(;b=b[d];)if((1===b.nodeType||e)&&a(b,c,g))return!0}else for(;b=b[d];)if(1===b.nodeType||e)if(j=b[L]||(b[L]={}),(i=j[d])&&i[0]===k){if((h=i[1])===!0||h===v)return h===!0}else if(i=j[d]=[k],i[1]=a(b,c,g)||v,i[1]===!0)return!0}}function m(a){return a.length>1?function(b,c,d){for(var e=a.length;e--;)if(!a[e](b,c,d))return!1;return!0}:a[0]}function n(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function o(a,b,d,e,f,g){return e&&!e[L]&&(e=o(e)),f&&!f[L]&&(f=o(f,g)),c(function(c,g,h,i){var j,k,l,m=[],o=[],p=g.length,q=c||r(b||"*",h.nodeType?[h]:h,[]),s=!a||!c&&b?q:n(q,m,a,h,i),t=d?f||(c?a:p||e)?[]:g:s;if(d&&d(s,t,h,i),e)for(j=n(t,o),e(j,[],h,i),k=j.length;k--;)(l=j[k])&&(t[o[k]]=!(s[o[k]]=l));if(c){if(f||a){if(f){for(j=[],k=t.length;k--;)(l=t[k])&&j.push(s[k]=l);f(null,t=[],j,i)}for(k=t.length;k--;)(l=t[k])&&(j=f?aa.call(c,l):m[k])>-1&&(c[j]=!(g[j]=l))}}else t=n(t===g?t.splice(p,t.length):t),f?f(null,g,t,i):$.apply(g,t);
})}function p(a){for(var b,c,d,e=a.length,f=w.relative[a[0].type],g=f||w.relative[" "],h=f?1:0,i=l(function(a){return a===b},g,!0),j=l(function(a){return aa.call(b,a)>-1},g,!0),n=[function(a,c,d){return!f&&(d||c!==A)||((b=c).nodeType?i(a,c,d):j(a,c,d))}];e>h;h++)if(c=w.relative[a[h].type])n=[l(m(n),c)];else{if(c=w.filter[a[h].type].apply(null,a[h].matches),c[L]){for(d=++h;e>d&&!w.relative[a[d].type];d++);return o(h>1&&m(n),h>1&&k(a.slice(0,h-1)).replace(ha,"$1"),c,d>h&&p(a.slice(h,d)),e>d&&p(a=a.slice(d)),e>d&&k(a))}n.push(c)}return m(n)}function q(a,b){var d=0,f=b.length>0,g=a.length>0,h=function(c,h,i,j,k){var l,m,o,p=[],q=0,r="0",s=c&&[],t=null!=k,u=A,x=c||g&&w.find.TAG("*",k&&h.parentNode||h),y=O+=null==u?1:Math.random()||.1;for(t&&(A=h!==E&&h,v=d);null!=(l=x[r]);r++){if(g&&l){for(m=0;o=a[m++];)if(o(l,h,i)){j.push(l);break}t&&(O=y,v=++d)}f&&((l=!o&&l)&&q--,c&&s.push(l))}if(q+=r,f&&r!==q){for(m=0;o=b[m++];)o(s,p,h,i);if(c){if(q>0)for(;r--;)s[r]||p[r]||(p[r]=Y.call(j));p=n(p)}$.apply(j,p),t&&!c&&p.length>0&&q+b.length>1&&e.uniqueSort(j)}return t&&(O=y,A=u),s};return f?c(h):h}function r(a,b,c){for(var d=0,f=b.length;f>d;d++)e(a,b[d],c);return c}function s(a,b,c,d){var e,f,g,h,i,l=j(a);if(!d&&1===l.length){if(f=l[0]=l[0].slice(0),f.length>2&&"ID"===(g=f[0]).type&&9===b.nodeType&&G&&w.relative[f[1].type]){if(b=(w.find.ID(g.matches[0].replace(ua,va),b)||[])[0],!b)return c;a=a.slice(f.shift().value.length)}for(e=ma.needsContext.test(a)?0:f.length;e--&&(g=f[e],!w.relative[h=g.type]);)if((i=w.find[h])&&(d=i(g.matches[0].replace(ua,va),na.test(f[0].type)&&b.parentNode||b))){if(f.splice(e,1),a=d.length&&k(f),!a)return $.apply(c,d),c;break}}return z(a,l)(d,b,!G,c,na.test(a)),c}function t(){}var u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L="sizzle"+-new Date,M=window.document,N={},O=0,P=0,Q=b(),R=b(),S=b(),T=!1,U=function(){return 0},V="undefined",W=1<<31,X=[],Y=X.pop,Z=X.push,$=X.push,_=X.slice,aa=X.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},ba="[\\x20\\t\\r\\n\\f]",ca="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",da=ca.replace("w","w#"),ea="([*^$|!~]?=)",fa="\\["+ba+"*("+ca+")"+ba+"*(?:"+ea+ba+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+da+")|)|)"+ba+"*\\]",ga=":("+ca+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+fa.replace(3,8)+")*)|.*)\\)|)",ha=new RegExp("^"+ba+"+|((?:^|[^\\\\])(?:\\\\.)*)"+ba+"+$","g"),ia=new RegExp("^"+ba+"*,"+ba+"*"),ja=new RegExp("^"+ba+"*([\\x20\\t\\r\\n\\f>+~])"+ba+"*"),ka=new RegExp(ga),la=new RegExp("^"+da+"$"),ma={ID:new RegExp("^#("+ca+")"),CLASS:new RegExp("^\\.("+ca+")"),NAME:new RegExp("^\\[name=['\"]?("+ca+")['\"]?\\]"),TAG:new RegExp("^("+ca.replace("w","w*")+")"),ATTR:new RegExp("^"+fa),PSEUDO:new RegExp("^"+ga),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+ba+"*(even|odd|(([+-]|)(\\d*)n|)"+ba+"*(?:([+-]|)"+ba+"*(\\d+)|))"+ba+"*\\)|)","i"),needsContext:new RegExp("^"+ba+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+ba+"*((?:-\\d)?\\d*)"+ba+"*\\)|)(?=[^-]|$)","i")},na=/[\x20\t\r\n\f]*[+~]/,oa=/^[^{]+\{\s*\[native code/,pa=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,qa=/^(?:input|select|textarea|button)$/i,ra=/^h\d$/i,sa=/'|\\/g,ta=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,ua=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,va=function(a,b){var c="0x"+b-65536;return c!==c?b:0>c?String.fromCharCode(c+65536):String.fromCharCode(c>>10|55296,1023&c|56320)};try{$.apply(X=_.call(M.childNodes),M.childNodes),X[M.childNodes.length].nodeType}catch(wa){$={apply:X.length?function(a,b){Z.apply(a,_.call(b))}:function(a,b){for(var c=a.length,d=0;a[c++]=b[d++];);a.length=c-1}}}y=e.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},D=e.setDocument=function(b){var c=b?b.ownerDocument||b:M;return c!==E&&9===c.nodeType&&c.documentElement?(E=c,F=c.documentElement,G=!y(c),N.getElementsByTagName=d(function(a){return a.appendChild(c.createComment("")),!a.getElementsByTagName("*").length}),N.attributes=d(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return"boolean"!==b&&"string"!==b}),N.getElementsByClassName=d(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",a.getElementsByClassName&&a.getElementsByClassName("e").length?(a.lastChild.className="e",2===a.getElementsByClassName("e").length):!1}),N.getByName=d(function(a){a.id=L+0,a.appendChild(E.createElement("a")).setAttribute("name",L),a.appendChild(E.createElement("i")).setAttribute("name",L),F.appendChild(a);var b=c.getElementsByName&&c.getElementsByName(L).length===2+c.getElementsByName(L+0).length;return F.removeChild(a),b}),N.sortDetached=d(function(a){return a.compareDocumentPosition&&1&a.compareDocumentPosition(E.createElement("div"))}),w.attrHandle=d(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==V&&"#"===a.firstChild.getAttribute("href")})?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},N.getByName?(w.find.ID=function(a,b){if(typeof b.getElementById!==V&&G){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},w.filter.ID=function(a){var b=a.replace(ua,va);return function(a){return a.getAttribute("id")===b}}):(w.find.ID=function(a,b){if(typeof b.getElementById!==V&&G){var c=b.getElementById(a);return c?c.id===a||typeof c.getAttributeNode!==V&&c.getAttributeNode("id").value===a?[c]:void 0:[]}},w.filter.ID=function(a){var b=a.replace(ua,va);return function(a){var c=typeof a.getAttributeNode!==V&&a.getAttributeNode("id");return c&&c.value===b}}),w.find.TAG=N.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==V?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){for(;c=f[e++];)1===c.nodeType&&d.push(c);return d}return f},w.find.NAME=N.getByName&&function(a,b){return typeof b.getElementsByName!==V?b.getElementsByName(name):void 0},w.find.CLASS=N.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==V&&G?b.getElementsByClassName(a):void 0},I=[],H=[":focus"],(N.qsa=a(c.querySelectorAll))&&(d(function(a){a.innerHTML="<select><option selected=''></option></select>",a.querySelectorAll("[selected]").length||H.push("\\["+ba+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||H.push(":checked")}),d(function(a){a.innerHTML="<input type='hidden' i=''/>",a.querySelectorAll("[i^='']").length&&H.push("[*^$]="+ba+"*(?:\"\"|'')"),a.querySelectorAll(":enabled").length||H.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),H.push(",.*:")})),(N.matchesSelector=a(J=F.matchesSelector||F.mozMatchesSelector||F.webkitMatchesSelector||F.oMatchesSelector||F.msMatchesSelector))&&d(function(a){N.disconnectedMatch=J.call(a,"div"),J.call(a,"[s!='']:x"),I.push("!=",ga)}),H=new RegExp(H.join("|")),I=I.length&&new RegExp(I.join("|")),K=a(F.contains)||F.compareDocumentPosition?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)for(;b=b.parentNode;)if(b===a)return!0;return!1},U=F.compareDocumentPosition?function(a,b){if(a===b)return T=!0,0;var d=b.compareDocumentPosition&&a.compareDocumentPosition&&a.compareDocumentPosition(b);return d?1&d||B&&b.compareDocumentPosition(a)===d?a===c||K(M,a)?-1:b===c||K(M,b)?1:C?aa.call(C,a)-aa.call(C,b):0:4&d?-1:1:a.compareDocumentPosition?-1:1}:function(a,b){var d,e=0,g=a.parentNode,h=b.parentNode,i=[a],j=[b];if(a===b)return T=!0,0;if(!g||!h)return a===c?-1:b===c?1:g?-1:h?1:0;if(g===h)return f(a,b);for(d=a;d=d.parentNode;)i.unshift(d);for(d=b;d=d.parentNode;)j.unshift(d);for(;i[e]===j[e];)e++;return e?f(i[e],j[e]):i[e]===M?-1:j[e]===M?1:0},E):E},e.matches=function(a,b){return e(a,null,null,b)},e.matchesSelector=function(a,b){if((a.ownerDocument||a)!==E&&D(a),b=b.replace(ta,"='$1']"),N.matchesSelector&&G&&(!I||!I.test(b))&&!H.test(b))try{var c=J.call(a,b);if(c||N.disconnectedMatch||a.document&&11!==a.document.nodeType)return c}catch(d){}return e(b,E,null,[a]).length>0},e.contains=function(a,b){return(a.ownerDocument||a)!==E&&D(a),K(a,b)},e.attr=function(a,b){var c;return(a.ownerDocument||a)!==E&&D(a),G&&(b=b.toLowerCase()),(c=w.attrHandle[b])?c(a):!G||N.attributes?a.getAttribute(b):((c=a.getAttributeNode(b))||a.getAttribute(b))&&a[b]===!0?b:c&&c.specified?c.value:null},e.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},e.uniqueSort=function(a){var b,c=[],d=0,e=0;if(T=!N.detectDuplicates,B=!N.sortDetached,C=!N.sortStable&&a.slice(0),a.sort(U),T){for(;b=a[e++];)b===a[e]&&(d=c.push(e));for(;d--;)a.splice(c[d],1)}return a},x=e.getText=function(a){var b,c="",d=0,e=a.nodeType;if(e){if(1===e||9===e||11===e){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=x(a)}else if(3===e||4===e)return a.nodeValue}else for(;b=a[d];d++)c+=x(b);return c},w=e.selectors={cacheLength:50,createPseudo:c,match:ma,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ua,va),a[3]=(a[4]||a[5]||"").replace(ua,va),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||e.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&e.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return ma.CHILD.test(a[0])?null:(a[4]?a[2]=a[4]:c&&ka.test(c)&&(b=j(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){return"*"===a?function(){return!0}:(a=a.replace(ua,va).toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=Q[a+" "];return b||(b=new RegExp("(^|"+ba+")"+a+"("+ba+"|$)"))&&Q(a,function(a){return b.test(a.className||typeof a.getAttribute!==V&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var f=e.attr(d,a);return null==f?"!="===b:b?(f+="","="===b?f===c:"!="===b?f!==c:"^="===b?c&&0===f.indexOf(c):"*="===b?c&&f.indexOf(c)>-1:"$="===b?c&&f.slice(-c.length)===c:"~="===b?(" "+f+" ").indexOf(c)>-1:"|="===b?f===c||f.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){for(;p;){for(l=b;l=l[p];)if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){for(k=q[L]||(q[L]={}),j=k[a]||[],n=j[0]===O&&j[1],m=j[0]===O&&j[2],l=n&&q.childNodes[n];l=++n&&l&&l[p]||(m=n=0)||o.pop();)if(1===l.nodeType&&++m&&l===b){k[a]=[O,n,m];break}}else if(s&&(j=(b[L]||(b[L]={}))[a])&&j[0]===O)m=j[1];else for(;(l=++n&&l&&l[p]||(m=n=0)||o.pop())&&((h?l.nodeName.toLowerCase()!==r:1!==l.nodeType)||!++m||(s&&((l[L]||(l[L]={}))[a]=[O,m]),l!==b)););return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var d,f=w.pseudos[a]||w.setFilters[a.toLowerCase()]||e.error("unsupported pseudo: "+a);return f[L]?f(b):f.length>1?(d=[a,a,"",b],w.setFilters.hasOwnProperty(a.toLowerCase())?c(function(a,c){for(var d,e=f(a,b),g=e.length;g--;)d=aa.call(a,e[g]),a[d]=!(c[d]=e[g])}):function(a){return f(a,0,d)}):f}},pseudos:{not:c(function(a){var b=[],d=[],e=z(a.replace(ha,"$1"));return e[L]?c(function(a,b,c,d){for(var f,g=e(a,null,d,[]),h=a.length;h--;)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,c,f){return b[0]=a,e(b,null,f,d),!d.pop()}}),has:c(function(a){return function(b){return e(a,b).length>0}}),contains:c(function(a){return function(b){return(b.textContent||b.innerText||x(b)).indexOf(a)>-1}}),lang:c(function(a){return la.test(a||"")||e.error("unsupported lang: "+a),a=a.replace(ua,va).toLowerCase(),function(b){var c;do if(c=G?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(a){var b=window.location&&window.location.hash;return b&&b.slice(1)===a.id},root:function(a){return a===F},focus:function(a){return a===E.activeElement&&(!E.hasFocus||E.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeName>"@"||3===a.nodeType||4===a.nodeType)return!1;return!0},parent:function(a){return!w.pseudos.empty(a)},header:function(a){return ra.test(a.nodeName)},input:function(a){return qa.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||b.toLowerCase()===a.type)},first:i(function(){return[0]}),last:i(function(a,b){return[b-1]}),eq:i(function(a,b,c){return[0>c?c+b:c]}),even:i(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:i(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:i(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:i(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}};for(u in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})w.pseudos[u]=g(u);for(u in{submit:!0,reset:!0})w.pseudos[u]=h(u);return z=e.compile=function(a,b){var c,d=[],e=[],f=S[a+" "];if(!f){for(b||(b=j(a)),c=b.length;c--;)f=p(b[c]),f[L]?d.push(f):e.push(f);f=S(a,q(e,d))}return f},w.pseudos.nth=w.pseudos.eq,t.prototype=w.filters=w.pseudos,w.setFilters=new t,N.sortStable=L.split("").sort(U).join("")===L,D(),[0,0].sort(U),N.detectDuplicates=T,{select:e,matches:e.matches,matchesSelector:e.matchesSelector}}),Ink.createModule("Ink.Util.Array","1",[],function(){"use strict";var a=Array.prototype,b={isArray:Array.isArray||function(a){return"[object Array]"==={}.toString.call(a)},groupBy:function(a,c){function d(a){return"function"==typeof c.key?c.key(a):"string"==typeof c.key?a[c.key]:a}function e(a){var b=c.pairs?[a,[]]:[];return h.push(b),g.push(a),b}c=c||{};for(var f,g=[],h=[],i=0,j=a.length;j>i;i++){f=d(a[i]);var k;k=c.adjacentGroups?g[g.length-1]===f?h[h.length-1]:e(f):h[b.keyValue(f,g,!0)]||e(f),c.pairs?k[1].push(a[i]):k.push(a[i])}return h},reduce:function(b,c,d){if(a.reduce)return a.reduce.apply(b,a.slice.call(arguments,1));var e=Object(b),f=e.length>>>0,g=0,h;if(arguments.length>=3)h=d;else{for(;f>g&&!(g in e);)g++;if(g>=f)throw new TypeError("Reduce of empty array with no initial value");h=e[g++]}for(;f>g;g++)g in e&&(h=c(h,e[g],g,e));return h},inArray:function(a,b){if("object"==typeof b)for(var c=0,d=b.length;d>c;++c)if(b[c]===a)return!0;return!1},sortMulti:function(a,b){if("undefined"==typeof a||a.constructor!==Array)return!1;if("string"!=typeof b)return a.sort();if(a.length>0){if("undefined"==typeof a[0][b])return!1;a.sort(function(a,c){var d=a[b],e=c[b];return e>d?-1:d>e?1:0})}return a},keyValue:function(a,b,c){if("undefined"!=typeof a&&"object"==typeof b&&this.inArray(a,b)){for(var d=[],e=0,f=b.length;f>e;++e)if(b[e]===a){if("undefined"!=typeof c&&c===!0)return e;d.push(e)}return d}return!1},shuffle:function(a){if("undefined"!=typeof a&&a.constructor!==Array)return!1;for(var b=a.length,c=!1,d=!1;b--;)d=Math.floor(Math.random()*(b+1)),c=a[b],a[b]=a[d],a[d]=c;return a},forEach:function(b,c,d){if(a.forEach)return a.forEach.call(b,c,d);for(var e=0,f=b.length>>>0;f>e;e++)c.call(d,b[e],e,b)},forEachObj:function(a,c,d){b.forEach(b.keys(a),function(b){c.call(d||null,a[b],b,a)})},each:function(){b.forEach.apply(b,a.slice.call(arguments))},map:function(b,c,d){if(a.map)return a.map.call(b,c,d);for(var e=new Array(g),f=0,g=b.length>>>0;g>f;f++)e[f]=c.call(d,b[f],f,b);return e},filter:function(b,c,d){if(a.filter)return a.filter.call(b,c,d);for(var e=[],f=null,g=0,h=b.length;h>g;g++)f=b[g],c.call(d,f,g,b)&&e.push(f);return e},some:function(a,b,c){if(null===a)throw new TypeError("First argument is invalid.");var d=Object(a),e=d.length>>>0;if("function"!=typeof b)throw new TypeError("Second argument must be a function.");for(var f=0;e>f;f++)if(f in d&&b.call(c,d[f],f,d))return!0;return!1},intersect:function(a,b){if(!a||!b||a instanceof Array==!1||b instanceof Array==!1)return[];for(var c=[],d=0,e=a.length;e>d;++d)for(var f=0,g=b.length;g>f;++f)a[d]===b[f]&&c.push(a[d]);return c},convert:function(b){return a.slice.call(b||[],0)},unique:function(a){if(!Array.prototype.lastIndexOf){var c=[];return b.forEach(b.convert(a),function(a){b.inArray(a,c)||c.push(a)}),c}return b.filter(b.convert(a),function(a,b,c){return c.lastIndexOf(a)===b})},range:function c(a,b,d){1===arguments.length&&(b=a,a=0),d||(d=1);var e=[],f;if(d>0)for(f=a;b>f;f+=d)e.push(f);else for(f=a;f>b;f+=d)e.push(f);return e},insert:function(a,b,c){a.splice(b,0,c)},keys:function(a){if(Object.keys)return Object.keys(a);var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},remove:function(a,b,c){for(var d=[],e=0,f=a.length;f>e;e++)e>=b&&b+c>e||d.push(a[e]);return d}};return b}),Ink.createModule("Ink.Util.BinPack","1",[],function(){"use strict";var a=function(a,b){this.init(a,b)};a.prototype={init:function(a,b){this.root={x:0,y:0,w:a,h:b}},fit:function(a){var b,c,d;for(b=0;b<a.length;++b)d=a[b],(c=this.findNode(this.root,d.w,d.h))&&(d.fit=this.splitNode(c,d.w,d.h))},findNode:function(a,b,c){return a.used?this.findNode(a.right,b,c)||this.findNode(a.down,b,c):b<=a.w&&c<=a.h?a:null},splitNode:function(a,b,c){return a.used=!0,a.down={x:a.x,y:a.y+c,w:a.w,h:a.h-c},a.right={x:a.x+b,y:a.y,w:a.w-b,h:c},a}};var b=function(){};b.prototype={fit:function(a){var b,c,d,e=a.length,f=e>0?a[0].w:0,g=e>0?a[0].h:0;for(this.root={x:0,y:0,w:f,h:g},b=0;e>b;b++)d=a[b],(c=this.findNode(this.root,d.w,d.h))?d.fit=this.splitNode(c,d.w,d.h):d.fit=this.growNode(d.w,d.h)},findNode:function(a,b,c){return a.used?this.findNode(a.right,b,c)||this.findNode(a.down,b,c):b<=a.w&&c<=a.h?a:null},splitNode:function(a,b,c){return a.used=!0,a.down={x:a.x,y:a.y+c,w:a.w,h:a.h-c},a.right={x:a.x+b,y:a.y,w:a.w-b,h:c},a},growNode:function(a,b){var c=a<=this.root.w,d=b<=this.root.h,e=d&&this.root.h>=this.root.w+a,f=c&&this.root.w>=this.root.h+b;return e?this.growRight(a,b):f?this.growDown(a,b):d?this.growRight(a,b):c?this.growDown(a,b):null},growRight:function(a,b){this.root={used:!0,x:0,y:0,w:this.root.w+a,h:this.root.h,down:this.root,right:{x:this.root.w,y:0,w:a,h:this.root.h}};var c;return(c=this.findNode(this.root,a,b))?this.splitNode(c,a,b):null},growDown:function(a,b){this.root={used:!0,x:0,y:0,w:this.root.w,h:this.root.h+b,down:{x:0,y:this.root.h,w:this.root.w,h:b},right:this.root};var c;return(c=this.findNode(this.root,a,b))?this.splitNode(c,a,b):null}};var c={random:function(){return Math.random()-.5},w:function(a,b){return b.w-a.w},h:function(a,b){return b.h-a.h},a:function(a,b){return b.area-a.area},max:function(a,b){return Math.max(b.w,b.h)-Math.max(a.w,a.h)},min:function(a,b){return Math.min(b.w,b.h)-Math.min(a.w,a.h)},height:function(a,b){return c.msort(a,b,["h","w"])},width:function(a,b){return c.msort(a,b,["w","h"])},area:function(a,b){return c.msort(a,b,["a","h","w"])},maxside:function(a,b){return c.msort(a,b,["max","min","h","w"])},msort:function(a,b,d){var e,f;for(f=0;f<d.length;++f)if(e=c[d[f]](a,b),0!==e)return e;return 0}},d=function(){return[this.w," x ",this.h].join("")},e={binPack:function(e){var f,g,h;for(f=0,g=e.blocks.length;g>f;++f)h=e.blocks[f],"area"in h||(h.area=h.w*h.h);var i=e.dimensions?new a(e.dimensions[0],e.dimensions[1]):new b;e.sorter||(e.sorter="maxside"),e.blocks.sort(c[e.sorter]),i.fit(e.blocks);var j=[i.root.w,i.root.h],k=[],l=[];for(f=0,g=e.blocks.length;g>f;++f)h=e.blocks[f],h.fit?k.push(h):(h.toString=d,l.push(h));var m=j[0]*j[1],n=0;for(f=0,g=k.length;g>f;++f)h=k[f],n+=h.area;return{dimensions:j,filled:n/m,blocks:e.blocks,fitted:k,unfitted:l}}};return e}),Ink.createModule("Ink.Util.Cookie","1",[],function(){"use strict";var a={get:function(a){var b=document.cookie||!1,c={};if(b){b=b.replace(new RegExp("; ","g"),";");var d=b.split(";"),e=[];if(d.length>0)for(var f=0;f<d.length;f++)e=d[f].split("="),2===e.length&&(c[e[0]]=decodeURIComponent(e[1]));if(a)return"undefined"!=typeof c[a]?c[a]:null}return c},set:function(a,b,c,d,e,f){var g;if(!a||b===!1||"undefined"==typeof a||"undefined"==typeof b)return!1;g=a+"="+encodeURIComponent(b);var h=!1,i=!1,j=!1,k=!1;if(c&&"undefined"!=typeof c&&!isNaN(c)){var l=new Date,m=parseInt(Number(l.valueOf()),10)+1e3*Number(parseInt(c,10)),n=new Date(m),o=n.toGMTString(),p=new RegExp("([^\\s]+)(\\s\\d\\d)\\s(\\w\\w\\w)\\s(.*)");o=o.replace(p,"$1$2-$3-$4"),h="expires="+o}else h="undefined"==typeof c||isNaN(c)||0!==Number(parseInt(c,10))?"expires=Thu, 01-Jan-2037 00:00:01 GMT":"";i=d&&"undefined"!=typeof d?"path="+d:"path=/",e?j="domain="+e:/\./.test(window.location.hostname)&&(j="domain="+window.location.hostname),k=f&&"undefined"!=typeof f?f:!1,document.cookie=g+"; "+h+"; "+i+(j?"; "+j:"")+"; "+k},remove:function(a,b,c){var d=-1;this.set(a,"deleted",d,b,c)}};return a}),Ink.createModule("Ink.Util.Date","1",[],function(){"use strict";var a={_months:function(a){var b=["Janeiro","Fevereiro","Março","Abril","Maio","Junho","Julho","Agosto","Setembro","Outubro","Novembro","Dezembro"];return b[a]},_iMonth:function(a){return Number(a)?+a-1:{janeiro:0,jan:0,fevereiro:1,fev:1,"março":2,mar:2,abril:3,abr:3,maio:4,mai:4,junho:5,jun:5,julho:6,jul:6,agosto:7,ago:7,setembro:8,set:8,outubro:9,out:9,novembro:10,nov:10,dezembro:11,dez:11}[a.toLowerCase()]},_wDays:function(a){var b=["Domingo","Segunda","Terça","Quarta","Quinta","Sexta","Sábado"];return b[a]},_iWeek:function(a){return Number(a)?+a||7:{segunda:1,seg:1,"terça":2,ter:2,quarta:3,qua:3,quinta:4,qui:4,sexta:5,sex:5,"sábado":6,"sáb":6,domingo:7,dom:7}[a.toLowerCase()]},_daysInMonth:function(a,b){var c;return c=1===a||3===a||5===a||7===a||8===a||10===a||12===a?31:4===a||6===a||9===a||11===a?30:b%400===0||b%4===0&&b%100!==0?29:28},get:function(a,b){("undefined"==typeof a||""===a)&&(a="Y-m-d");var c=a.split(""),d=new Array(c.length),e="\\",f;f="undefined"==typeof b?new Date:"number"==typeof b?new Date(1e3*b):new Date(b);for(var g,h,i,j=0;j<c.length;j++)switch(c[j]){case e:d[j]=c[j+1],j++;break;case"d":var k=f.getDate();d[j]=String(k).length>1?k:"0"+k;break;case"D":d[j]=this._wDays(f.getDay()).substring(0,3);break;case"j":d[j]=f.getDate();break;case"l":d[j]=this._wDays(f.getDay());break;case"N":d[j]=f.getDay()||7;break;case"S":var l=f.getDate(),m=["st","nd","rd"],n="";l>=11&&13>=l?d[j]="th":d[j]=(n=m[String(l).substr(-1)-1])?n:"th";break;case"w":d[j]=f.getDay();break;case"z":g=Date.UTC(f.getFullYear(),0,0),h=Date.UTC(f.getFullYear(),f.getMonth(),f.getDate()),d[j]=Math.floor((h-g)/864e5);break;case"W":var o=new Date(f.getFullYear(),0,1);g=o.getDay()||7;var p=Math.floor((f-o)/864e5+1);d[j]=Math.ceil((p-(8-g))/7)+1;break;case"F":d[j]=this._months(f.getMonth());break;case"m":var q=String(f.getMonth()+1);d[j]=q.length>1?q:"0"+q;break;case"M":d[j]=this._months(f.getMonth()).substring(0,3);break;case"n":d[j]=f.getMonth()+1;break;case"t":d[j]=this._daysInMonth(f.getMonth()+1,f.getYear());break;case"L":var r=f.getFullYear();d[j]=r%4?!1:r%100?!0:r%400?!1:!0;break;case"o":throw'"o" not implemented!';case"Y":d[j]=f.getFullYear();break;case"y":d[j]=String(f.getFullYear()).substring(2);break;case"a":d[j]=f.getHours()<12?"am":"pm";break;case"A":d[j]=f.getHours<12?"AM":"PM";break;case"B":throw'"B" not implemented!';case"g":i=f.getHours(),d[j]=12>=i?i:i-12;break;case"G":d[j]=String(f.getHours());break;case"h":i=String(f.getHours()),i=12>=i?i:i-12,d[j]=i.length>1?i:"0"+i;break;case"H":i=String(f.getHours()),d[j]=i.length>1?i:"0"+i;break;case"i":var s=String(f.getMinutes());d[j]=s.length>1?s:"0"+s;break;case"s":var t=String(f.getSeconds());d[j]=t.length>1?t:"0"+t;break;case"u":throw'"u" not implemented!';case"e":throw'"e" not implemented!';case"I":g=new Date(f.getFullYear(),0,1),d[j]=f.getTimezoneOffset()!==g.getTimezoneOffset()?1:0;break;case"O":var u=f.getTimezoneOffset(),v=u%60;i=String((u-v)/60*-1),"-"!==i.charAt(0)&&(i="+"+i),i=3===i.length?i:i.replace(/([+\-])(\d)/,"$10$2"),d[j]=i+v+"0";break;case"P":throw'"P" not implemented!';case"T":throw'"T" not implemented!';case"Z":d[j]=60*f.getTimezoneOffset();break;case"c":throw'"c" not implemented!';case"r":var w=this._wDays(f.getDay()).substr(0,3),x=this._months(f.getMonth()).substr(0,3);d[j]=w+", "+f.getDate()+" "+x+this.get(" Y H:i:s O",f);break;case"U":d[j]=Math.floor(f.getTime()/1e3);break;default:d[j]=c[j]}return d.join("")},set:function(a,b){if("undefined"!=typeof b){("undefined"==typeof a||""===a)&&(a="Y-m-d");for(var c=a.split(""),d=new Array(c.length),e="\\",f,g={year:void 0,month:void 0,day:void 0,dayY:void 0,dayW:void 0,week:void 0,hour:void 0,hourD:void 0,min:void 0,sec:void 0,msec:void 0,ampm:void 0,diffM:void 0,diffH:void 0,date:void 0},h=0,i=0;i<c.length;i++)switch(c[i]){case e:d[i]=c[i+1],i++;break;case"d":d[i]="(\\d{2})",g.day={original:i,match:h++};break;case"j":d[i]="(\\d{1,2})",g.day={original:i,match:h++};break;case"D":d[i]="([\\wá]{3})",g.dayW={original:i,match:h++};break;case"l":d[i]="([\\wá]{5,7})",g.dayW={original:i,match:h++};break;case"N":d[i]="(\\d)",g.dayW={original:i,match:h++};break;case"w":d[i]="(\\d)",g.dayW={original:i,match:h++};break;case"S":d[i]="\\w{2}";break;case"z":d[i]="(\\d{1,3})",g.dayY={original:i,match:h++};break;case"W":d[i]="(\\d{1,2})",g.week={original:i,match:h++};break;case"F":d[i]="([\\wç]{4,9})",g.month={original:i,match:h++};break;case"M":d[i]="(\\w{3})",g.month={original:i,match:h++};break;case"m":d[i]="(\\d{2})",g.month={original:i,match:h++};break;case"n":d[i]="(\\d{1,2})",g.month={original:i,match:h++};break;case"t":d[i]="\\d{2}";break;case"L":d[i]="\\w{4,5}";break;case"o":throw'"o" not implemented!';case"Y":d[i]="(\\d{4})",g.year={original:i,match:h++};break;case"y":d[i]="(\\d{2})",("undefined"==typeof g.year||"Y"!==c[g.year.original])&&(g.year={original:i,match:h++});break;case"a":d[i]="(am|pm)",g.ampm={original:i,match:h++};break;case"A":d[i]="(AM|PM)",g.ampm={original:i,match:h++};break;case"B":throw'"B" not implemented!';case"g":d[i]="(\\d{1,2})",g.hourD={original:i,match:h++};break;case"G":d[i]="(\\d{1,2})",g.hour={original:i,match:h++};break;case"h":d[i]="(\\d{2})",g.hourD={original:i,match:h++};break;case"H":d[i]="(\\d{2})",g.hour={original:i,match:h++};break;case"i":d[i]="(\\d{2})",g.min={original:i,match:h++};break;case"s":d[i]="(\\d{2})",g.sec={original:i,match:h++};break;case"u":throw'"u" not implemented!';case"e":throw'"e" not implemented!';case"I":d[i]="\\d";break;case"O":d[i]="([-+]\\d{4})",g.diffH={original:i,match:h++};break;case"P":throw'"P" not implemented!';case"T":throw'"T" not implemented!';case"Z":d[i]="(\\-?\\d{1,5})",g.diffM={original:i,match:h++};break;case"c":throw'"c" not implemented!';case"r":d[i]="([\\wá]{3}, \\d{1,2} \\w{3} \\d{4} \\d{2}:\\d{2}:\\d{2} [+\\-]\\d{4})",g.date={original:i,match:h++};break;case"U":d[i]="(\\d{1,13})",g.date={original:i,match:h++};break;default:d[i]=c[i]}var j=new RegExp(d.join(""));try{if(f=b.match(j),!f)return}catch(k){return}var l="undefined"!=typeof g.date,m="undefined"!=typeof g.year,n="undefined"!=typeof g.dayY,o="undefined"!=typeof g.day,p="undefined"!=typeof g.month,q=p&&o,r=!p&&o,s="undefined"!=typeof g.dayW,t="undefined"!=typeof g.week,u=t&&s,v=!t&&s,w=n||q||!m&&r||u||!m&&v,x=!(m||n||o||p||s||t),y="undefined"!=typeof g.hourD&&"undefined"!=typeof g.ampm,z="undefined"!=typeof g.hour,A=y||z,B="undefined"!=typeof g.min,C="undefined"!=typeof g.sec,D="undefined"!=typeof g.msec,E=!x||A,F=E||B,G="undefined"!=typeof g.diffM,H="undefined"!=typeof g.diffH,I,J;if(l){if("U"===c[g.date.original])return new Date(1e3*+f[g.date.match+1]);var K=f[g.date.match+1].match(/\w{3}, (\d{1,2}) (\w{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) ([+\-]\d{4})/);return I=+K[4]+ +K[7].slice(0,3),J=+K[5]+(K[7].slice(0,1)+K[7].slice(3))/100*60,new Date(K[3],this._iMonth(K[2]),K[1],I,J,K[6])}var L=new Date,M,N,O,P,Q,R;if(w||x){if(w){if(m){var S=L.getFullYear()-50+"";M=f[g.year.match+1],"y"===c[g.year.original]&&(M=+S.slice(0,2)+(M>=S.slice(2)?0:1)+M)}else M=L.getFullYear();if(n)N=0,O=f[g.dayY.match+1];else if(o)N=p?this._iMonth(f[g.month.match+1]):L.getMonth(),O=f[g.day.match+1];else{N=0;var T;T=t?f[g.week.match+1]:this.get("W",L),O=7*(T-2)+(8-(new Date(M,0,1).getDay()||7))+this._iWeek(f[g.week.match+1])}if(0===N&&O>31){var U=new Date(M,N,O);N=U.getMonth(),O=U.getDate()}}else M=L.getFullYear(),N=L.getMonth(),O=L.getDate();return I=y?+f[g.hourD.match+1]+("pm"===f[g.ampm.match+1]?12:0):z?f[g.hour.match+1]:x?L.getHours():"00",J=B?f[g.min.match+1]:E?"00":L.getMinutes(),P=C?f[g.sec.match+1]:F?"00":L.getSeconds(),Q=D?f[g.msec.match+1]:"000",R=H?f[g.diffH.match+1]:G?String(-1*f[g.diffM.match+1]/60*100).replace(/^(\d)/,"+$1").replace(/(^[\-+])(\d{3}$)/,"$10$2"):"+0000",new Date(M,N,O,I,J,P)}}}};return a}),Ink.createModule("Ink.Util.Dumper","1",[],function(){"use strict";var a={_tab:" ",_formatParam:function(a){var b="";switch(typeof a){case"string":b="(string) "+a;break;case"number":b="(number) "+a;break;case"boolean":b="(boolean) "+a;break;case"object":b=null!==a?a.constructor===Array?"Array \n{\n"+this._outputFormat(a,0)+"\n}":"Object \n{\n"+this._outputFormat(a,0)+"\n}":"null";break;default:b=!1}return b},_getTabs:function(a){for(var b="",c=0;a>c;c++)b+=this._tab;return b},_outputFormat:function(a,b){var c="",d=!1;for(var e in a)if(null!==a[e])if("object"!=typeof a[e]||a[e].constructor!==Array&&a[e].constructor!==Object){if(a[e].constructor===Function)continue;c=c+this._tab+this._getTabs(b)+"["+e+"] => "+a[e]+"\n"}else a[e].constructor===Array?d="Array":a[e].constructor===Object&&(d="Object"),c+=this._tab+this._getTabs(b)+"["+e+"] => <b>"+d+"</b>\n",c+=this._tab+this._getTabs(b)+"{\n",c+=this._outputFormat(a[e],b+1)+this._tab+this._getTabs(b)+"}\n";else c=c+this._tab+this._getTabs(b)+"["+e+"] => null \n";return c},printDump:function(a,b){if(b&&"undefined"!=typeof b)if("string"==typeof b)document.getElementById(b).innerHTML="<pre>"+this._formatParam(a)+"</pre>";else{if("object"!=typeof b)throw"TARGET must be an element or an element ID";b.innerHTML="<pre>"+this._formatParam(a)+"</pre>"}else document.write("<pre>"+this._formatParam(a)+"</pre>")},returnDump:function(a){return this._formatParam(a)},alertDump:function(a){window.alert(this._formatParam(a).replace(/(<b>)(Array|Object)(<\/b>)/g,"$2"))},windowDump:function(a){var b="dumperwindow_"+1e4*Math.random(),c=window.open("",b,"width=400,height=300,left=50,top=50,status,menubar,scrollbars,resizable");c.document.open(),c.document.write("<pre>"+this._formatParam(a)+"</pre>"),c.document.close(),c.focus()}};return a}),Ink.createModule("Ink.Util.I18n","1",[],function(){"use strict";var a=/\{(?:(\{.*?})|(?:%s:)?(\d+)|(?:%s)?|([\w-]+))}/g,b=function(a,b){return"function"==typeof a?a.apply(this,b):"undefined"!=typeof a?a:""},c=function(a,b,d){return this instanceof c?void this.reset().lang(b).testMode(d).append(a||{},b):new c(a,b,d)};return c.prototype={reset:function(){return this._dicts=[],this._dict={},this._testMode=!1,this._lang=this._gLang,this},clone:function(){for(var a=new c,b=0,d=this._dicts.length;d>b;b++)a.append(this._dicts[b]);return a.testMode(this.testMode()),a.lang(this.lang()),a},append:function(a){return this._dicts.push(a),this._dict=Ink.extendObj(this._dict,a[this._lang]),this},lang:function(a){if(!arguments.length)return this._lang;if(a&&this._lang!==a){this._lang=a,this._dict={};for(var b=0,c=this._dicts.length;c>b;b++)this._dict=Ink.extendObj(this._dict,this._dicts[b][a]||{});
}return this},testMode:function(a){return arguments.length?(void 0!==a&&(this._testMode=!!a),this):!!this._testMode},getKey:function(a){var b,d=this._gLang,e=this._lang;return a in this._dict?b=this._dict[a]:(c.langGlobal(e),b=this._gDict[a],c.langGlobal(d)),b},text:function(c){if("string"==typeof c){var d=Array.prototype.slice.call(arguments,1),e=0,f="object"==typeof d[0],g=this.getKey(c);return void 0===g&&(g=this._testMode?"["+c+"]":c),"number"==typeof g&&(g+=""),"string"==typeof g?g=g.replace(a,function(a,c,g,h){var i=c?c:g?d[g-(f?0:1)]:h&&d[0]?d[0][h]||"":d[e++ +(f?1:0)];return b(i,[e].concat(d))}):"function"==typeof g?g.apply(this,d):g instanceof Array?b(g[d[0]],d):"object"==typeof g?b(g[d[0]],d):""}},ntext:function(a,b,c){var d=Array.prototype.slice.apply(arguments),e;if(2===d.length&&"number"==typeof b){if(e=this.getKey(a),!(e instanceof Array))return"";d.splice(0,1),e=e[1===b?0:1]}else d.splice(0,2),e=1===c?a:b;return this.text.apply(this,[e].concat(d))},ordinal:function(a){if(void 0===a)return"";var c=+a.toString().slice(-1),d=this.getKey("_ordinals");if(void 0===d)return"";if("string"==typeof d)return d;var e;return"function"==typeof d&&(e=d(a,c),"string"==typeof e)?e:"exceptions"in d&&(e="function"==typeof d.exceptions?d.exceptions(a,c):a in d.exceptions?b(d.exceptions[a],[a,c]):void 0,"string"==typeof e)?e:"byLastDigit"in d&&(e="function"==typeof d.byLastDigit?d.byLastDigit(c,a):c in d.byLastDigit?b(d.byLastDigit[c],[c,a]):void 0,"string"==typeof e)?e:"default"in d&&(e=b(d["default"],[a,c]),"string"==typeof e)?e:""},alias:function(){var a=Ink.bind(c.prototype.text,this);return a.ntext=Ink.bind(c.prototype.ntext,this),a.append=Ink.bind(c.prototype.append,this),a.ordinal=Ink.bind(c.prototype.ordinal,this),a.testMode=Ink.bind(c.prototype.testMode,this),a}},c.reset=function(){c.prototype._gDicts=[],c.prototype._gDict={},c.prototype._gLang="pt_PT"},c.reset(),c.appendGlobal=function(a,b){if(b){if(!(b in a)){var d={};d[b]=a,a=d}b!==c.prototype._gLang&&c.langGlobal(b)}c.prototype._gDicts.push(a),Ink.extendObj(c.prototype._gDict,a[c.prototype._gLang])},c.langGlobal=function(a){if(!arguments.length)return c.prototype._gLang;if(a&&c.prototype._gLang!==a){c.prototype._gLang=a,c.prototype._gDict={};for(var b=0,d=c.prototype._gDicts.length;d>b;b++)Ink.extendObj(c.prototype._gDict,c.prototype._gDicts[b][a]||{})}},c}),Ink.createModule("Ink.Util.Json","1",[],function(){"use strict";function twoDigits(a){var b=""+a;return 1===b.length?"0"+b:b}var function_call=Function.prototype.call,cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,dateToISOString=Date.prototype.toISOString?Ink.bind(function_call,Date.prototype.toISOString):function(a){return a.getUTCFullYear()+"-"+twoDigits(a.getUTCMonth()+1)+"-"+twoDigits(a.getUTCDate())+"T"+twoDigits(a.getUTCHours())+":"+twoDigits(a.getUTCMinutes())+":"+twoDigits(a.getUTCSeconds())+"."+String((a.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"},InkJson={_nativeJSON:window.JSON||null,_convertToUnicode:!1,_escape:function(a){var b={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};return/["\\\x00-\x1f]/.test(a)&&(a=a.replace(/([\x00-\x1f\\"])/g,function(a,c){var d=b[c];return d?d:(d=c.charCodeAt(),"\\u00"+Math.floor(d/16).toString(16)+(d%16).toString(16))})),a},_toUnicode:function(a){if(this._convertToUnicode){for(var b="",c=!1,d=!1,e=0,f=a.length;f>e;){if(c=a.charCodeAt(e),c>=32&&126>=c||8===c||9===c||10===c||12===c||13===c||32===c||34===c||47===c||58===c||92===c)d=34===c||92===c||47===c?"\\"+a.charAt(e):8===c?"\\b":9===c?"\\t":10===c?"\\n":12===c?"\\f":13===c?"\\r":a.charAt(e);else if(this._convertToUnicode){for(d=a.charCodeAt(e).toString(16)+"".toUpperCase();d.length<4;)d="0"+d;d="\\u"+d}else d=a.charAt(e);b+=d,e++}return b}return this._escape(a)},_stringifyValue:function(a){if("string"==typeof a)return'"'+this._toUnicode(a)+'"';if("number"!=typeof a||!isNaN(a)&&isFinite(a)){if("undefined"==typeof a||null===a)return"null";if("function"==typeof a.toJSON){var b=a.toJSON();return"string"==typeof b?'"'+this._escape(b)+'"':this._escape(b.toString())}if("number"==typeof a||"boolean"==typeof a)return""+a;if("function"==typeof a)return"null";if(a.constructor===Date)return'"'+this._escape(dateToISOString(a))+'"';if(a.constructor===Array){for(var c="",d=0,e=a.length;e>d;d++)d>0&&(c+=","),c+=this._stringifyValue(a[d]);return"["+c+"]"}var f="";for(var g in a)({}).hasOwnProperty.call(a,g)&&(""!==f&&(f+=","),f+='"'+this._escape(g)+'": '+this._stringifyValue(a[g]));return"{"+f+"}"}return"null"},stringify:function(a,b){return this._convertToUnicode=!!b,!this._convertToUnicode&&this._nativeJSON?this._nativeJSON.stringify(a):this._stringifyValue(a)},parse:function(text,reviver){function walk(a,b){var c,d,e=a[b];if(e&&"object"==typeof e)for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&(d=walk(e,c),void 0!==d?e[c]=d:delete e[c]);return reviver.call(a,b,e)}var j;if(text=String(text),cx.lastIndex=0,cx.test(text)&&(text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})),/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,"")))return j=eval("("+text+")"),"function"==typeof reviver?walk({"":j},""):j;throw new SyntaxError("JSON.parse")}};return InkJson}),Ink.createModule("Ink.Util.String","1",[],function(){"use strict";var InkUtilString={_chars:["&","à","á","â","ã","ä","å","æ","ç","è","é","ê","ë","ì","í","î","ï","ð","ñ","ò","ó","ô","õ","ö","ø","ù","ú","û","ü","ý","þ","ÿ","À","Á","Â","Ã","Ä","Å","Æ","Ç","È","É","Ê","Ë","Ì","Í","Î","Ï","Ð","Ñ","Ò","Ó","Ô","Õ","Ö","Ø","Ù","Ú","Û","Ü","Ý","Þ","€",'"',"ß","<",">","¢","£","¤","¥","¦","§","¨","©","ª","«","¬","","®","¯","°","±","²","³","´","µ","¶","·","¸","¹","º","»","¼","½","¾"],_entities:["amp","agrave","aacute","acirc","atilde","auml","aring","aelig","ccedil","egrave","eacute","ecirc","euml","igrave","iacute","icirc","iuml","eth","ntilde","ograve","oacute","ocirc","otilde","ouml","oslash","ugrave","uacute","ucirc","uuml","yacute","thorn","yuml","Agrave","Aacute","Acirc","Atilde","Auml","Aring","AElig","Ccedil","Egrave","Eacute","Ecirc","Euml","Igrave","Iacute","Icirc","Iuml","ETH","Ntilde","Ograve","Oacute","Ocirc","Otilde","Ouml","Oslash","Ugrave","Uacute","Ucirc","Uuml","Yacute","THORN","euro","quot","szlig","lt","gt","cent","pound","curren","yen","brvbar","sect","uml","copy","ordf","laquo","not","shy","reg","macr","deg","plusmn","sup2","sup3","acute","micro","para","middot","cedil","sup1","ordm","raquo","frac14","frac12","frac34"],_accentedChars:["à","á","â","ã","ä","å","è","é","ê","ë","ì","í","î","ï","ò","ó","ô","õ","ö","ù","ú","û","ü","ç","ñ","À","Á","Â","Ã","Ä","Å","È","É","Ê","Ë","Ì","Í","Î","Ï","Ò","Ó","Ô","Õ","Ö","Ù","Ú","Û","Ü","Ç","Ñ"],_accentedRemovedChars:["a","a","a","a","a","a","e","e","e","e","i","i","i","i","o","o","o","o","o","u","u","u","u","c","n","A","A","A","A","A","A","E","E","E","E","I","I","I","I","O","O","O","O","O","U","U","U","U","C","N"],_htmlUnsafeChars:{"<":"<",">":">","&":"&",'"':""","'":"'"},ucFirst:function(a,b){var c=b?/(^|\s)(\w)(\S{2,})/:/(^|\s)(\w)(\S{2,})/g;return a?String(a).replace(c,function(a,b,c,d){return b+c.toUpperCase()+d.toLowerCase()}):a},trim:function(a){return"string"==typeof a?a.replace(/^\s+|\s+$|\n+$/g,""):a},stripTags:function(a,b){if(b&&"string"==typeof b){for(var c=InkUtilString.trim(b).split(","),d=[],e=!1,f=0;f<c.length;f++)""!==InkUtilString.trim(c[f])&&(e=InkUtilString.trim(c[f].replace(/(<|\>)/g,"").replace(/\s/,"")),d.push("(<"+e+"\\s[^>]+>|<(\\s|\\/)?(\\s|\\/)?"+e+">)"));for(var g=d.join("|"),h=new RegExp(g,"i"),i=a.match(new RegExp("<[^>]*>","g")),j=0;j<i.length;j++)i[j].match(h)||(a=a.replace(new RegExp(i[j],"gm"),""));return a}return a.replace(/<[^\>]+\>/g,"")},htmlEntitiesEncode:function(a){if(a&&a.replace)for(var b=!1,c=0;c<InkUtilString._chars.length;c++)b=new RegExp(InkUtilString._chars[c],"gm"),a=a.replace(b,"&"+InkUtilString._entities[c]+";");return a},htmlEntitiesDecode:function(a){if(a&&a.replace){for(var b=!1,c=0;c<InkUtilString._entities.length;c++)b=new RegExp("&"+InkUtilString._entities[c]+";","gm"),a=a.replace(b,InkUtilString._chars[c]);a=a.replace(/&#[^;]+;?/g,function(a){return"x"===a.charAt(2)?String.fromCharCode(parseInt(a.substring(3),16)):String.fromCharCode(parseInt(a.substring(2),10))})}return a},utf8Encode:function(a){a=a.replace(/\r\n/g,"\n");for(var b="",c=0;c<a.length;c++){var d=a.charCodeAt(c);128>d?b+=String.fromCharCode(d):d>127&&2048>d?(b+=String.fromCharCode(d>>6|192),b+=String.fromCharCode(63&d|128)):(b+=String.fromCharCode(d>>12|224),b+=String.fromCharCode(d>>6&63|128),b+=String.fromCharCode(63&d|128))}return b},shortString:function(a,b){for(var c=a.split(" "),d="",e=0;e<c.length;e++){if((d+c[e]+" ").length>=b){d+="…";break}d+=c[e]+" "}return d},truncateString:function(a,b){return a.length-1>b?a.substr(0,b-1)+"…":a},utf8Decode:function(a){for(var b="",c=0,d=0,e=0,f=0;c<a.length;)d=a.charCodeAt(c),128>d?(b+=String.fromCharCode(d),c++):d>191&&224>d?(e=a.charCodeAt(c+1),b+=String.fromCharCode((31&d)<<6|63&e),c+=2):(e=a.charCodeAt(c+1),f=a.charCodeAt(c+2),b+=String.fromCharCode((15&d)<<12|(63&e)<<6|63&f),c+=3);return b},removeAccentedChars:function(a){for(var b=a,c=!1,d=0;d<InkUtilString._accentedChars.length;d++)c=new RegExp(InkUtilString._accentedChars[d],"gm"),b=b.replace(c,""+InkUtilString._accentedRemovedChars[d]);return b},substrCount:function(a,b){return a?a.split(b).length-1:0},evalJSON:function(strJSON,sanitize){if("undefined"==typeof sanitize||null===sanitize||InkUtilString.isJSON(strJSON))try{return"undefined"!=typeof JSON&&"undefined"!=typeof JSON.parse?JSON.parse(strJSON):eval("("+strJSON+")")}catch(e){throw new Error("ERROR: Bad JSON string...")}},isJSON:function(a){return a=a.replace(/\\./g,"@").replace(/"[^"\\\n\r]*"/g,""),/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/.test(a)},htmlEscapeUnsafe:function(a){var b=InkUtilString._htmlUnsafeChars;return null!==a?String(a).replace(/[<>&'"]/g,function(a){return b[a]}):a},normalizeWhitespace:function(a){return null!==a?InkUtilString.trim(String(a).replace(/\s+/g," ")):a},toUnicode:function(a){if("string"==typeof a){for(var b="",c=!1,d=!1,e=a.length,f=0;e>f;){if(c=a.charCodeAt(f),c>=32&&126>=c||8===c||9===c||10===c||12===c||13===c||32===c||34===c||47===c||58===c||92===c)d=8===c?"\\b":9===c?"\\t":10===c?"\\n":12===c?"\\f":13===c?"\\r":a.charAt(f);else{for(d=a.charCodeAt(f).toString(16)+"".toUpperCase();d.length<4;)d="0"+d;d="\\u"+d}b+=d,f++}return b}},escape:function(a){var b=a.charCodeAt(0).toString(16).split("");if(b.length<3){for(;b.length<2;)b.unshift("0");b.unshift("x")}else{for(;b.length<4;)b.unshift("0");b.unshift("u")}return b.unshift("\\"),b.join("")},unescape:function(a){var b=a.lastIndexOf("0");b=-1===b?2:Math.min(b,2);var c=a.substring(b),d=parseInt(c,16);return String.fromCharCode(d)},escapeText:function(a,b){void 0===b&&(b=["[","]","'",","]);for(var c=[],d,e,f=0,g=a.length;g>f;++f)d=a[f],e=d.charCodeAt(0),(32>e||e>126&&-1===b.indexOf(d))&&(d=InkUtilString.escape(d)),c.push(d);return c.join("")},escapedCharRegex:/(\\x[0-9a-fA-F]{2})|(\\u[0-9a-fA-F]{4})/g,unescapeText:function(a){for(var b;b=InkUtilString.escapedCharRegex.exec(a);)b=b[0],a=a.replace(b,InkUtilString.unescape(b)),InkUtilString.escapedCharRegex.lastIndex=0;return a},strcmp:function(a,b){return a===b?0:a>b?1:-1},packetize:function(a,b){for(var c=a.length,d=new Array(Math.ceil(c/b)),e=a.split(""),f,g=0;c;)f=Math.min(b,c),d[g++]=e.splice(0,f).join(""),c-=f;return d}};return InkUtilString}),Ink.createModule("Ink.Util.Url","1",[],function(){"use strict";var a={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",getUrl:function(){return window.location.href},genQueryString:function(a,b){var c=-1!==a.indexOf("?"),d,e,f,g=[a];for(e in b)b.hasOwnProperty(e)&&(c?d="&":(d="?",c=!0),f=b[e],"number"==typeof f||f||(f=""),g=g.concat([d,encodeURIComponent(e),"=",encodeURIComponent(f)]));return g.join("")},getQueryString:function(a){var b;b=a&&"undefined"!=typeof a?a:this.getUrl();var c={};if(b.match(/\?(.+)/i)){var d=b.replace(/^(.*)\?([^\#]+)(\#(.*))?/g,"$2");if(d.length>0)for(var e=d.split(/[;&]/),f=0;f<e.length;f++){var g=e[f].split("=");c[decodeURIComponent(g[0])]="undefined"!=typeof g[1]&&g[1]?decodeURIComponent(g[1]):!1}}return c},getAnchor:function(a){var b;b=a&&"undefined"!=typeof a?a:this.getUrl();var c=!1;return b.match(/#(.+)/)&&(c=b.replace(/([^#]+)#(.*)/,"$2")),c},getAnchorString:function(a){var b;b=a&&"undefined"!=typeof a?a:this.getUrl();var c={};if(b.match(/#(.+)/i)){var d=b.replace(/^([^#]+)#(.*)?/g,"$2");if(d.length>0)for(var e=d.split(/[;&]/),f=0;f<e.length;f++){var g=e[f].split("=");c[decodeURIComponent(g[0])]="undefined"!=typeof g[1]&&g[1]?decodeURIComponent(g[1]):!1}}return c},parseUrl:function(a){var b={};if(a&&"string"==typeof a){if(a.match(/^([^:]+):\/\//i)){var c=/^([^:]+):\/\/([^\/]*)\/?([^\?#]*)\??([^#]*)#?(.*)/i;a.match(c)&&(b.scheme=a.replace(c,"$1"),b.host=a.replace(c,"$2"),b.path="/"+a.replace(c,"$3"),b.query=a.replace(c,"$4")||!1,b.fragment=a.replace(c,"$5")||!1)}else{var d=new RegExp("^([^\\?]+)\\?([^#]+)#(.*)","i"),e=new RegExp("^([^\\?]+)\\?([^#]+)#?","i"),f=new RegExp("^([^\\?]+)\\??","i");a.match(d)?(b.scheme=!1,b.host=!1,b.path=a.replace(d,"$1"),b.query=a.replace(d,"$2"),b.fragment=a.replace(d,"$3")):a.match(e)?(b.scheme=!1,b.host=!1,b.path=a.replace(e,"$1"),b.query=a.replace(e,"$2"),b.fragment=!1):a.match(f)&&(b.scheme=!1,b.host=!1,b.path=a.replace(f,"$1"),b.query=!1,b.fragment=!1)}if(b.host){var g=/^(.*?)\\:(\\d+)$/i;if(b.host.match(g)){var h=b.host;b.host=h.replace(g,"$1"),b.port=h.replace(g,"$2")}else b.port=!1;if(b.host.match(/@/i)){var i=b.host;b.host=i.split("@")[1];var j=i.split("@")[0];j.match(/\:/)?(b.user=j.split(":")[0],b.pass=j.split(":")[1]):(b.user=j,b.pass=!1)}}}return b},format:function(a){var b="",c="",d="",e="",f="";return"string"==typeof a.protocol?b=a.protocol+"//":"string"==typeof a.scheme&&(b=a.scheme+"://"),c=a.host||a.hostname||"",d=a.path||"","string"==typeof a.query?f=a.query:"string"==typeof a.search&&(f=a.search.replace(/^\?/,"")),"string"==typeof a.fragment?e=a.fragment:"string"==typeof a.hash&&(e=a.hash.replace(/#$/,"")),[b,c,d,f&&"?"+f,e&&"#"+e].join("")},currentScriptElement:function(a){var b=document.getElementsByTagName("script");if("undefined"==typeof a)return b.length>0?b[b.length-1]:!1;for(var c=!1,d=new RegExp(""+a,"i"),e=0,f=b.length;f>e;e++)if(c=b[e],d.test(c.src))return c;return!1}};return a}),Ink.createModule("Ink.Util.Validator","1",[],function(){"use strict";var a={_countryCodes:["AO","CV","MZ","TL","PT"],_internacionalPT:351,_indicativosPT:{21:"lisboa",22:"porto",231:"mealhada",232:"viseu",233:"figueira da foz",234:"aveiro",235:"arganil",236:"pombal",238:"seia",239:"coimbra",241:"abrantes",242:"ponte de sôr",243:"santarém",244:"leiria",245:"portalegre",249:"torres novas",251:"valença",252:"vila nova de famalicão",253:"braga",254:"peso da régua",255:"penafiel",256:"são joão da madeira",258:"viana do castelo",259:"vila real",261:"torres vedras",262:"caldas da raínha",263:"vila franca de xira",265:"setúbal",266:"évora",268:"estremoz",269:"santiago do cacém",271:"guarda",272:"castelo branco",273:"bragança",274:"proença-a-nova",275:"covilhã",276:"chaves",277:"idanha-a-nova",278:"mirandela",279:"moncorvo",281:"tavira",282:"portimão",283:"odemira",284:"beja",285:"moura",286:"castro verde",289:"faro",291:"funchal, porto santo",292:"corvo, faial, flores, horta, pico",295:"angra do heroísmo, graciosa, são jorge, terceira",296:"ponta delgada, são miguel, santa maria",91:"rede móvel 91 (Vodafone / Yorn)",93:"rede móvel 93 (Optimus)",96:"rede móvel 96 (TMN)",92:"rede móvel 92 (TODOS)",707:"número único",760:"número único",800:"número grátis",808:"chamada local",30:"voip"},_internacionalCV:238,_indicativosCV:{2:"fixo",91:"móvel 91",95:"móvel 95",97:"móvel 97",98:"móvel 98",99:"móvel 99"},_internacionalAO:244,_indicativosAO:{2:"fixo",91:"móvel 91",92:"móvel 92"},_internacionalMZ:258,_indicativosMZ:{2:"fixo",82:"móvel 82",84:"móvel 84"},_internacionalTL:670,_indicativosTL:{3:"fixo",7:"móvel 7"},_characterGroups:{numbers:["0-9"],asciiAlpha:["a-zA-Z"],latin1Alpha:["a-zA-Z","À-ÿ"],unicodeAlpha:["a-zA-Z","À-ÿ","Ā-","Ⰰ-"],space:[" "],dash:["-"],underscore:["_"],nicknamePunctuation:["_.-"],singleLineWhitespace:[" "],newline:["\n"],whitespace:[" \n\f\r "],asciiPunctuation:["!-/",":-@","[-`","{-~"],latin1Punctuation:["!-/",":-@","[-`","{-~","¡-¿","×","÷"],unicodePunctuation:["!-/",":-@","[-`","{-~","¡-¿","×","÷"," -","⸀-"," -〿"]},createRegExp:function(b){var c="^[";for(var d in b)if(b.hasOwnProperty(d)){if(!(d in a._characterGroups))throw new Error("group "+d+" is not a valid character group");b[d]&&(c+=a._characterGroups[d].join(""))}return"^["===c?new RegExp("$^"):new RegExp(c+"]*?$")},checkCharacterGroups:function(b,c){return a.createRegExp(c).test(b)},unicode:function(b,c){return a.checkCharacterGroups(b,Ink.extendObj({unicodeAlpha:!0},c))},latin1:function(b,c){return a.checkCharacterGroups(b,Ink.extendObj({latin1Alpha:!0},c))},ascii:function(b,c){return a.checkCharacterGroups(b,Ink.extendObj({asciiAlpha:!0},c))},number:function(b,c){if(b+="",c=Ink.extendObj({decimalSep:".",thousandSep:"",negative:!0,decimalPlaces:null,maxDigits:null,max:null,min:null,returnNumber:!1},c||{}),c.thousandSep)return b=b.replace(new RegExp("\\"+c.thousandSep,"g"),""),c.thousandSep="",a.number(b,c);if(c.negative===!1)return c.min=0,c.negative=!0,a.number(b,c);if("."!==c.decimalSep&&(b=b.replace(new RegExp("\\"+c.decimalSep,"g"),".")),!/^(-)?(\d+)?(\.\d+)?$/.test(b)||""===b)return!1;var d;if(c.decimalSep&&-1!==b.indexOf(c.decimalSep)){if(d=b.split(c.decimalSep),null!==c.decimalPlaces&&d[1].length>c.decimalPlaces)return!1}else d=[""+b,""];if(null!==c.maxDigits&&d[0].replace(/-/g,"").length>c.maxDigits)return d;var e=parseFloat(b);return null!==c.maxExcl&&e>=c.maxExcl||null!==c.minExcl&&e<=c.minExcl?!1:null!==c.max&&e>c.max||null!==c.min&&e<c.min?!1:c.returnNumber?e:!0},_isLeapYear:function(a){var b=/^\d{4}$/;return b.test(a)?a%4?!1:a%100?!0:a%400?!1:!0:!1},_dateParsers:{"yyyy-mm-dd":{day:5,month:3,year:1,sep:"-",parser:/^(\d{4})(\-)(\d{1,2})(\-)(\d{1,2})$/},"yyyy/mm/dd":{day:5,month:3,year:1,sep:"/",parser:/^(\d{4})(\/)(\d{1,2})(\/)(\d{1,2})$/},"yy-mm-dd":{day:5,month:3,year:1,sep:"-",parser:/^(\d{2})(\-)(\d{1,2})(\-)(\d{1,2})$/},"yy/mm/dd":{day:5,month:3,year:1,sep:"/",parser:/^(\d{2})(\/)(\d{1,2})(\/)(\d{1,2})$/},"dd-mm-yyyy":{day:1,month:3,year:5,sep:"-",parser:/^(\d{1,2})(\-)(\d{1,2})(\-)(\d{4})$/},"dd/mm/yyyy":{day:1,month:3,year:5,sep:"/",parser:/^(\d{1,2})(\/)(\d{1,2})(\/)(\d{4})$/},"dd-mm-yy":{day:1,month:3,year:5,sep:"-",parser:/^(\d{1,2})(\-)(\d{1,2})(\-)(\d{2})$/},"dd/mm/yy":{day:1,month:3,year:5,sep:"/",parser:/^(\d{1,2})(\/)(\d{1,2})(\/)(\d{2})$/}},_daysInMonth:function(a,b){var c=0;return a=parseInt(a,10),b=parseInt(b,10),1===a||3===a||5===a||7===a||8===a||10===a||12===a?c=31:4===a||6===a||9===a||11===a?c=30:2===a&&(c=b%400===0||b%4===0&&b%100!==0?29:28),c},_isValidDate:function(a,b,c){var d=/^\d{4}$/,e=/^\d{1,2}$/;return d.test(a)&&e.test(b)&&e.test(c)&&b>=1&&12>=b&&c>=1&&this._daysInMonth(b,a)>=c?!0:!1},email:function(a){var b=new RegExp("^[_a-z0-9-]+((\\.|\\+)[_a-z0-9-]+)*@([\\w]*-?[\\w]*\\.)+[a-z]{2,4}$","i");return!!b.test(a)},mail:function(b){return a.email(b)},url:function(a,b){if("undefined"==typeof b||b===!1){var c=new RegExp("(^(http\\:\\/\\/|https\\:\\/\\/)(.+))","i");c.test(a)===!1&&(a="http://"+a)}var d=new RegExp("^(http:\\/\\/|https:\\/\\/)([\\w]*(-?[\\w]*)*\\.)+[a-z]{2,4}","i");return d.test(a)===!1?!1:!0},isPTPhone:function(a){a=a.toString();var b=[];for(var c in this._indicativosPT)"string"==typeof this._indicativosPT[c]&&b.push(c);var d=b.join("|"),e=/^(00351|\+351)/;e.test(a)&&(a=a.replace(e,""));var f=/(\s|\-|\.)+/g;a=a.replace(f,"");var g=/[\d]{9}/i;if(9===a.length&&g.test(a)){var h=new RegExp("^("+d+")");if(h.test(a))return!0}return!1},isPortuguesePhone:function(a){return this.isPTPhone(a)},isCVPhone:function(a){a=a.toString();var b=[];for(var c in this._indicativosCV)"string"==typeof this._indicativosCV[c]&&b.push(c);var d=b.join("|"),e=/^(00238|\+238)/;e.test(a)&&(a=a.replace(e,""));var f=/(\s|\-|\.)+/g;a=a.replace(f,"");var g=/[\d]{7}/i;if(7===a.length&&g.test(a)){var h=new RegExp("^("+d+")");if(h.test(a))return!0}return!1},isAOPhone:function(a){a=a.toString();var b=[];for(var c in this._indicativosAO)"string"==typeof this._indicativosAO[c]&&b.push(c);var d=b.join("|"),e=/^(00244|\+244)/;e.test(a)&&(a=a.replace(e,""));var f=/(\s|\-|\.)+/g;a=a.replace(f,"");var g=/[\d]{9}/i;if(9===a.length&&g.test(a)){var h=new RegExp("^("+d+")");if(h.test(a))return!0}return!1},isMZPhone:function(a){a=a.toString();var b=[];for(var c in this._indicativosMZ)"string"==typeof this._indicativosMZ[c]&&b.push(c);var d=b.join("|"),e=/^(00258|\+258)/;e.test(a)&&(a=a.replace(e,""));var f=/(\s|\-|\.)+/g;a=a.replace(f,"");var g=/[\d]{8,9}/i;if((9===a.length||8===a.length)&&g.test(a)){var h=new RegExp("^("+d+")");if(h.test(a)){if(0===a.indexOf("2")&&8===a.length)return!0;if(0===a.indexOf("8")&&9===a.length)return!0}}return!1},isTLPhone:function(a){a=a.toString();var b=[];for(var c in this._indicativosTL)"string"==typeof this._indicativosTL[c]&&b.push(c);var d=b.join("|"),e=/^(00670|\+670)/;e.test(a)&&(a=a.replace(e,""));var f=/(\s|\-|\.)+/g;a=a.replace(f,"");var g=/[\d]{7}/i;if(7===a.length&&g.test(a)){var h=new RegExp("^("+d+")");if(h.test(a))return!0}return!1},isPhone:function(){var a;if(0===arguments.length)return!1;var b=arguments[0];if(arguments.length>1){if(arguments[1].constructor!==Array){if("function"==typeof this["is"+arguments[1].toUpperCase()+"Phone"])return this["is"+arguments[1].toUpperCase()+"Phone"](b);throw"Invalid Country Code!"}var c;for(a=0;a<arguments[1].length;a++){if("function"!=typeof(c=this["is"+arguments[1][a].toUpperCase()+"Phone"]))throw"Invalid Country Code!";if(c(b))return!0}}else for(a=0;a<this._countryCodes.length;a++)if(this["is"+this._countryCodes[a]+"Phone"](b))return!0;return!1},codPostal:function(a,b,c){var d=/^(\s*\-\s*|\s+)$/,e=/^\s+|\s+$/g,f=/^[1-9]\d{3}$/,g=/^\d{3}$/,h=/^(.{4})(.*)(.{3})$/;if(a=a.replace(e,""),"undefined"!=typeof b){if(b=b.replace(e,""),f.test(a)&&g.test(b))return c?[!0,!0]:!0}else{if(f.test(a))return c?[!0,!1]:!0;var i=a.match(h);if(null!==i&&f.test(i[1])&&d.test(i[2])&&g.test(i[3]))return c?[!0,!1]:!0}return c?[!1,!1]:!1},isDate:function(a,b){if("undefined"==typeof this._dateParsers[a])return!1;var c=this._dateParsers[a].year,d=this._dateParsers[a].month,e=this._dateParsers[a].day,f=this._dateParsers[a].parser,g=this._dateParsers[a].sep,h=b.match(f);if(null!==h&&h[2]===h[4]&&h[2]===g){var i=2===h[c].length?"20"+h[c].toString():h[c];if(this._isValidDate(i,h[d].toString(),h[e].toString()))return!0}return!1},isColor:function(a){var b,c=!1,d=/^[a-zA-Z]+$/,e=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,f=/^rgb\(\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*\)$/,g=/^rgba\(\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*(1(\.0)?|0(\.[0-9])?)\s*\)$/,h=/^hsl\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*\)$/,i=/^hsla\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})(%)?\s*,\s*([0-9]{1,3})(%)?\s*,\s*(1(\.0)?|0(\.[0-9])?)\s*\)$/;if(d.test(a)||e.test(a))return!0;var j;if(null!==(b=f.exec(a))||null!==(b=g.exec(a)))for(j=b.length;j--;){if((2===j||4===j||6===j)&&"undefined"!=typeof b[j]&&""!==b[j]){if(!("undefined"!=typeof b[j-1]&&b[j-1]>=0&&b[j-1]<=100))return!1;c=!0}if(1===j||3===j||5===j&&("undefined"==typeof b[j+1]||""===b[j+1])){if(!("undefined"!=typeof b[j]&&b[j]>=0&&b[j]<=255))return!1;c=!0}}if(null!==(b=h.exec(a))||null!==(b=i.exec(a)))for(j=b.length;j--;){if(3===j||5===j){if(!("undefined"!=typeof b[j-1]&&"undefined"!=typeof b[j]&&""!==b[j]&&b[j-1]>=0&&b[j-1]<=100))return!1;c=!0}if(1===j){if(!("undefined"!=typeof b[j]&&b[j]>=0&&b[j]<=360))return!1;c=!0}}return c},isIP:function(a,b){if("string"!=typeof a)return!1;switch(b=(b||"ipv4").toLowerCase()){case"ipv4":return/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(a);case"ipv6":return/^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/.test(a);default:return!1}},_creditCardSpecs:{"default":{length:"13,14,15,16,17,18,19",prefix:/^.+/,luhn:!0},"american express":{length:"15",prefix:/^3[47]/,luhn:!0},"diners club":{length:"14,16",prefix:/^36|55|30[0-5]/,luhn:!0},discover:{length:"16",prefix:/^6(?:5|011)/,luhn:!0},jcb:{length:"15,16",prefix:/^3|1800|2131/,luhn:!0},maestro:{length:"16,18",prefix:/^50(?:20|38)|6(?:304|759)/,luhn:!0},mastercard:{length:"16",prefix:/^5[1-5]/,luhn:!0},visa:{length:"13,16",prefix:/^4/,luhn:!0}},_luhn:function(a){if(a=parseInt(a,10),"number"!=typeof a&&a%1!==0)return!1;a+="";var b=a.length,c,d=0;for(c=b-1;c>=0;c-=2)d+=parseInt(a.substr(c,1),10);for(c=b-2;c>=0;c-=2){var e=parseInt(2*a.substr(c,1),10);d+=e>=10?e-9:e}return d%10===0},isCreditCard:function(a,b){if(/\d+/.test(a)===!1)return!1;if("undefined"==typeof b)b="default";else if(b instanceof Array){var c,d=b.length;for(c=0;d>c;c++)if(this.isCreditCard(a,b[c]))return!0;return!1}if(b=b.toLowerCase(),"undefined"==typeof this._creditCardSpecs[b])return!1;var e=a.length+"";return-1===this._creditCardSpecs[b].length.split(",").indexOf(e)?!1:this._creditCardSpecs[b].prefix.test(a)?this._creditCardSpecs[b].luhn===!1?!0:this._luhn(a):!1},getEANCheckDigit:function(a){var b=0,c,d;for(a=String(a);a.length<12;)a="00000"+a;for(c=a.length,d=c-1;d>=0;d--)b+=(d%2*2+1)*Number(a.charAt(d));return 10-b%10},isEAN:function(b,c){switch(void 0===c&&(c="ean-13"),c){case"ean-13":if(13!==b.length)return!1;break;case"ean-8":if(8!==b.length)return!1;break;default:return!1}var d=b.substr(0,b.length-1),e=b.charAt(b.length-1),f=a.getEANCheckDigit(d);return String(f)===e}};return a});
//# sourceMappingURL=ink.min.js.map | iamJoeTaylor/cdnjs | ajax/libs/ink/3.1.10/js/ink.min.js | JavaScript | mit | 123,343 |
(function(e){"function"==typeof define&&define.amd?define(["jquery","moment"],e):e(jQuery,moment)})(function(e,t){var n={1:"१",2:"२",3:"३",4:"४",5:"५",6:"६",7:"७",8:"८",9:"९",0:"०"},i={"१":"1","२":"2","३":"3","४":"4","५":"5","६":"6","७":"7","८":"8","९":"9","०":"0"};t.lang("hi",{months:"जनवरी_फ़रवरी_मार्च_अप्रैल_मई_जून_जुलाई_अगस्त_सितम्बर_अक्टूबर_नवम्बर_दिसम्बर".split("_"),monthsShort:"जन._फ़र._मार्च_अप्रै._मई_जून_जुल._अग._सित._अक्टू._नव._दिस.".split("_"),weekdays:"रविवार_सोमवार_मंगलवार_बुधवार_गुरूवार_शुक्रवार_शनिवार".split("_"),weekdaysShort:"रवि_सोम_मंगल_बुध_गुरू_शुक्र_शनि".split("_"),weekdaysMin:"र_सो_मं_बु_गु_शु_श".split("_"),longDateFormat:{LT:"A h:mm बजे",L:"DD/MM/YYYY",LL:"D MMMM YYYY",LLL:"D MMMM YYYY, LT",LLLL:"dddd, D MMMM YYYY, LT"},calendar:{sameDay:"[आज] LT",nextDay:"[कल] LT",nextWeek:"dddd, LT",lastDay:"[कल] LT",lastWeek:"[पिछले] dddd, LT",sameElse:"L"},relativeTime:{future:"%s में",past:"%s पहले",s:"कुछ ही क्षण",m:"एक मिनट",mm:"%d मिनट",h:"एक घंटा",hh:"%d घंटे",d:"एक दिन",dd:"%d दिन",M:"एक महीने",MM:"%d महीने",y:"एक वर्ष",yy:"%d वर्ष"},preparse:function(e){return e.replace(/[१२३४५६७८९०]/g,function(e){return i[e]})},postformat:function(e){return e.replace(/\d/g,function(e){return n[e]})},meridiem:function(e){return 4>e?"रात":10>e?"सुबह":17>e?"दोपहर":20>e?"शाम":"रात"},week:{dow:0,doy:6}}),e.fullCalendar.datepickerLang("hi","hi",{closeText:"बंद",prevText:"पिछला",nextText:"अगला",currentText:"आज",monthNames:["जनवरी ","फरवरी","मार्च","अप्रेल","मई","जून","जूलाई","अगस्त ","सितम्बर","अक्टूबर","नवम्बर","दिसम्बर"],monthNamesShort:["जन","फर","मार्च","अप्रेल","मई","जून","जूलाई","अग","सित","अक्ट","नव","दि"],dayNames:["रविवार","सोमवार","मंगलवार","बुधवार","गुरुवार","शुक्रवार","शनिवार"],dayNamesShort:["रवि","सोम","मंगल","बुध","गुरु","शुक्र","शनि"],dayNamesMin:["रवि","सोम","मंगल","बुध","गुरु","शुक्र","शनि"],weekHeader:"हफ्ता",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""}),e.fullCalendar.lang("hi",{defaultButtonText:{month:"महीना",week:"सप्ताह",day:"दिन",list:"कार्यसूची"},allDayText:"सभी दिन",eventLimitText:function(e){return"+अधिक "+e}})}); | luhad/cdnjs | ajax/libs/fullcalendar/2.1.0-beta2/lang/hi.js | JavaScript | mit | 3,229 |
/*! UIkit 2.16.2 | http://www.getuikit.com | (c) 2014 YOOtheme | MIT License */
!function(t){var i;jQuery&&UIkit&&(i=t(jQuery,UIkit)),"function"==typeof define&&define.amd&&define("uikit-sticky",["uikit"],function(){return i||t(jQuery,UIkit)})}(function(t,i){"use strict";function e(){if(s.length){var i,e=n.scrollTop(),a=o.height(),r=a-n.height(),c=e>r?r-e:0;if(!(0>e))for(var h=0;h<s.length;h++)if(s[h].element.is(":visible")&&!s[h].animate){var l=s[h];if(l.check()){if(l.options.top<0?i=0:(i=a-l.element.outerHeight()-l.options.top-l.options.bottom-e-c,i=0>i?i+l.options.top:l.options.top),l.currentTop!=i){if(l.element.css({position:"fixed",top:i,width:"undefined"!=typeof l.getWidthFrom?t(l.getWidthFrom).width():l.element.width(),left:l.wrapper.offset().left}),!l.init&&(l.element.addClass(l.options.clsinit),location.hash&&e>0&&l.options.target)){var p=t(location.hash);p.length&&setTimeout(function(t,i){return function(){i.element.width();var n=t.offset(),o=n.top+t.outerHeight(),s=i.element.offset(),a=i.element.outerHeight(),r=s.top+a;s.top<o&&n.top<r&&(e=n.top-a-i.options.target,window.scrollTo(0,e))}}(p,l),0)}l.element.addClass(l.options.clsactive),l.element.css("margin",""),l.options.animation&&l.init&&l.element.addClass(l.options.animation),l.currentTop=i}}else null!==l.currentTop&&l.reset();l.init=!0}}}var n=i.$win,o=i.$doc,s=[];return i.component("sticky",{defaults:{top:0,bottom:0,animation:"",clsinit:"@-sticky-init",clsactive:"@-active",getWidthFrom:"",media:!1,target:!1},boot:function(){i.$doc.on("scrolling.uk.document",e),i.$win.on("resize orientationchange",i.Utils.debounce(function(){if(s.length){for(var t=0;t<s.length;t++)s[t].reset(!0);e()}},100)),i.ready(function(t){setTimeout(function(){i.$("[data-@-sticky]",t).each(function(){var t=i.$(this);t.data("sticky")||i.sticky(t,i.Utils.options(t.attr("data-@-sticky")))}),e()},0)})},init:function(){var t=i.$('<div class="@-sticky-placeholder"></div>').css({height:"absolute"!=this.element.css("position")?this.element.outerHeight():"","float":"none"!=this.element.css("float")?this.element.css("float"):"",margin:this.element.css("margin")});t=this.element.css("margin",0).wrap(t).parent(),this.sticky={options:this.options,element:this.element,currentTop:null,wrapper:t,init:!1,getWidthFrom:this.options.getWidthFrom||t,reset:function(t){var e=function(){this.element.css({position:"",top:"",width:"",left:"",margin:"0"}),this.element.removeClass([this.options.animation,"@-animation-reverse",this.options.clsactive].join(" ")),this.currentTop=null,this.animate=!1}.bind(this);!t&&this.options.animation&&i.support.animation?(this.animate=!0,this.element.removeClass(this.options.animation).one(i.support.animation.end,function(){e()}).width(),this.element.addClass(this.options.animation+" @-animation-reverse")):e()},check:function(){if(this.options.media)switch(typeof this.options.media){case"number":if(window.innerWidth<this.options.media)return!1;break;case"string":if(window.matchMedia&&!window.matchMedia(this.options.media).matches)return!1}var t=n.scrollTop(),i=o.height(),e=i-window.innerHeight,s=t>e?e-t:0,a=this.wrapper.offset().top,r=a-this.options.top-s;return t>=r}},s.push(this.sticky)},update:function(){e()}}),i.sticky}); | dlueth/cdnjs | ajax/libs/uikit/2.16.2/js/components/sticky.min.js | JavaScript | mit | 3,227 |
/*!
* VERSION: 1.13.1
* DATE: 2014-07-19
* UPDATES AND DOCS AT: http://www.greensock.com
*
* Includes all of the following: TweenLite, TweenMax, TimelineLite, TimelineMax, EasePack, CSSPlugin, RoundPropsPlugin, BezierPlugin, AttrPlugin, DirectionalRotationPlugin
*
* @license Copyright (c) 2008-2014, GreenSock. All rights reserved.
* This work is subject to the terms at http://www.greensock.com/terms_of_use.html or for
* Club GreenSock members, the software agreement that was issued with your membership.
*
* @author: Jack Doyle, jack@greensock.com
**/
var _gsScope="undefined"!=typeof module&&module.exports&&"undefined"!=typeof global?global:this||window;(_gsScope._gsQueue||(_gsScope._gsQueue=[])).push(function(){"use strict";_gsScope._gsDefine("TweenMax",["core.Animation","core.SimpleTimeline","TweenLite"],function(t,e,i){var s=function(t){var e,i=[],s=t.length;for(e=0;e!==s;i.push(t[e++]));return i},r=function(t,e,s){i.call(this,t,e,s),this._cycle=0,this._yoyo=this.vars.yoyo===!0,this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._dirty=!0,this.render=r.prototype.render},n=1e-10,a=i._internals,o=a.isSelector,h=a.isArray,l=r.prototype=i.to({},.1,{}),_=[];r.version="1.13.1",l.constructor=r,l.kill()._gc=!1,r.killTweensOf=r.killDelayedCallsTo=i.killTweensOf,r.getTweensOf=i.getTweensOf,r.lagSmoothing=i.lagSmoothing,r.ticker=i.ticker,r.render=i.render,l.invalidate=function(){return this._yoyo=this.vars.yoyo===!0,this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._uncache(!0),i.prototype.invalidate.call(this)},l.updateTo=function(t,e){var s,r=this.ratio;e&&this._startTime<this._timeline._time&&(this._startTime=this._timeline._time,this._uncache(!1),this._gc?this._enabled(!0,!1):this._timeline.insert(this,this._startTime-this._delay));for(s in t)this.vars[s]=t[s];if(this._initted)if(e)this._initted=!1;else if(this._gc&&this._enabled(!0,!1),this._notifyPluginsOfEnabled&&this._firstPT&&i._onPluginEvent("_onDisable",this),this._time/this._duration>.998){var n=this._time;this.render(0,!0,!1),this._initted=!1,this.render(n,!0,!1)}else if(this._time>0){this._initted=!1,this._init();for(var a,o=1/(1-r),h=this._firstPT;h;)a=h.s+h.c,h.c*=o,h.s=a-h.c,h=h._next}return this},l.render=function(t,e,i){this._initted||0===this._duration&&this.vars.repeat&&this.invalidate();var s,r,o,h,l,u,p,c,f=this._dirty?this.totalDuration():this._totalDuration,m=this._time,d=this._totalTime,g=this._cycle,v=this._duration,y=this._rawPrevTime;if(t>=f?(this._totalTime=f,this._cycle=this._repeat,this._yoyo&&0!==(1&this._cycle)?(this._time=0,this.ratio=this._ease._calcEnd?this._ease.getRatio(0):0):(this._time=v,this.ratio=this._ease._calcEnd?this._ease.getRatio(1):1),this._reversed||(s=!0,r="onComplete"),0===v&&(this._initted||!this.vars.lazy||i)&&(this._startTime===this._timeline._duration&&(t=0),(0===t||0>y||y===n)&&y!==t&&(i=!0,y>n&&(r="onReverseComplete")),this._rawPrevTime=c=!e||t||y===t?t:n)):1e-7>t?(this._totalTime=this._time=this._cycle=0,this.ratio=this._ease._calcEnd?this._ease.getRatio(0):0,(0!==d||0===v&&y>0&&y!==n)&&(r="onReverseComplete",s=this._reversed),0>t?(this._active=!1,0===v&&(this._initted||!this.vars.lazy||i)&&(y>=0&&(i=!0),this._rawPrevTime=c=!e||t||y===t?t:n)):this._initted||(i=!0)):(this._totalTime=this._time=t,0!==this._repeat&&(h=v+this._repeatDelay,this._cycle=this._totalTime/h>>0,0!==this._cycle&&this._cycle===this._totalTime/h&&this._cycle--,this._time=this._totalTime-this._cycle*h,this._yoyo&&0!==(1&this._cycle)&&(this._time=v-this._time),this._time>v?this._time=v:0>this._time&&(this._time=0)),this._easeType?(l=this._time/v,u=this._easeType,p=this._easePower,(1===u||3===u&&l>=.5)&&(l=1-l),3===u&&(l*=2),1===p?l*=l:2===p?l*=l*l:3===p?l*=l*l*l:4===p&&(l*=l*l*l*l),this.ratio=1===u?1-l:2===u?l:.5>this._time/v?l/2:1-l/2):this.ratio=this._ease.getRatio(this._time/v)),m===this._time&&!i&&g===this._cycle)return d!==this._totalTime&&this._onUpdate&&(e||this._onUpdate.apply(this.vars.onUpdateScope||this,this.vars.onUpdateParams||_)),void 0;if(!this._initted){if(this._init(),!this._initted||this._gc)return;if(!i&&this._firstPT&&(this.vars.lazy!==!1&&this._duration||this.vars.lazy&&!this._duration))return this._time=m,this._totalTime=d,this._rawPrevTime=y,this._cycle=g,a.lazyTweens.push(this),this._lazy=t,void 0;this._time&&!s?this.ratio=this._ease.getRatio(this._time/v):s&&this._ease._calcEnd&&(this.ratio=this._ease.getRatio(0===this._time?0:1))}for(this._lazy!==!1&&(this._lazy=!1),this._active||!this._paused&&this._time!==m&&t>=0&&(this._active=!0),0===d&&(2===this._initted&&t>0&&this._init(),this._startAt&&(t>=0?this._startAt.render(t,e,i):r||(r="_dummyGS")),this.vars.onStart&&(0!==this._totalTime||0===v)&&(e||this.vars.onStart.apply(this.vars.onStartScope||this,this.vars.onStartParams||_))),o=this._firstPT;o;)o.f?o.t[o.p](o.c*this.ratio+o.s):o.t[o.p]=o.c*this.ratio+o.s,o=o._next;this._onUpdate&&(0>t&&this._startAt&&this._startTime&&this._startAt.render(t,e,i),e||(this._totalTime!==d||s)&&this._onUpdate.apply(this.vars.onUpdateScope||this,this.vars.onUpdateParams||_)),this._cycle!==g&&(e||this._gc||this.vars.onRepeat&&this.vars.onRepeat.apply(this.vars.onRepeatScope||this,this.vars.onRepeatParams||_)),r&&(!this._gc||i)&&(0>t&&this._startAt&&!this._onUpdate&&this._startTime&&this._startAt.render(t,e,i),s&&(this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),!e&&this.vars[r]&&this.vars[r].apply(this.vars[r+"Scope"]||this,this.vars[r+"Params"]||_),0===v&&this._rawPrevTime===n&&c!==n&&(this._rawPrevTime=0))},r.to=function(t,e,i){return new r(t,e,i)},r.from=function(t,e,i){return i.runBackwards=!0,i.immediateRender=0!=i.immediateRender,new r(t,e,i)},r.fromTo=function(t,e,i,s){return s.startAt=i,s.immediateRender=0!=s.immediateRender&&0!=i.immediateRender,new r(t,e,s)},r.staggerTo=r.allTo=function(t,e,n,a,l,u,p){a=a||0;var c,f,m,d,g=n.delay||0,v=[],y=function(){n.onComplete&&n.onComplete.apply(n.onCompleteScope||this,arguments),l.apply(p||this,u||_)};for(h(t)||("string"==typeof t&&(t=i.selector(t)||t),o(t)&&(t=s(t))),c=t.length,m=0;c>m;m++){f={};for(d in n)f[d]=n[d];f.delay=g,m===c-1&&l&&(f.onComplete=y),v[m]=new r(t[m],e,f),g+=a}return v},r.staggerFrom=r.allFrom=function(t,e,i,s,n,a,o){return i.runBackwards=!0,i.immediateRender=0!=i.immediateRender,r.staggerTo(t,e,i,s,n,a,o)},r.staggerFromTo=r.allFromTo=function(t,e,i,s,n,a,o,h){return s.startAt=i,s.immediateRender=0!=s.immediateRender&&0!=i.immediateRender,r.staggerTo(t,e,s,n,a,o,h)},r.delayedCall=function(t,e,i,s,n){return new r(e,0,{delay:t,onComplete:e,onCompleteParams:i,onCompleteScope:s,onReverseComplete:e,onReverseCompleteParams:i,onReverseCompleteScope:s,immediateRender:!1,useFrames:n,overwrite:0})},r.set=function(t,e){return new r(t,0,e)},r.isTweening=function(t){return i.getTweensOf(t,!0).length>0};var u=function(t,e){for(var s=[],r=0,n=t._first;n;)n instanceof i?s[r++]=n:(e&&(s[r++]=n),s=s.concat(u(n,e)),r=s.length),n=n._next;return s},p=r.getAllTweens=function(e){return u(t._rootTimeline,e).concat(u(t._rootFramesTimeline,e))};r.killAll=function(t,i,s,r){null==i&&(i=!0),null==s&&(s=!0);var n,a,o,h=p(0!=r),l=h.length,_=i&&s&&r;for(o=0;l>o;o++)a=h[o],(_||a instanceof e||(n=a.target===a.vars.onComplete)&&s||i&&!n)&&(t?a.totalTime(a._reversed?0:a.totalDuration()):a._enabled(!1,!1))},r.killChildTweensOf=function(t,e){if(null!=t){var n,l,_,u,p,c=a.tweenLookup;if("string"==typeof t&&(t=i.selector(t)||t),o(t)&&(t=s(t)),h(t))for(u=t.length;--u>-1;)r.killChildTweensOf(t[u],e);else{n=[];for(_ in c)for(l=c[_].target.parentNode;l;)l===t&&(n=n.concat(c[_].tweens)),l=l.parentNode;for(p=n.length,u=0;p>u;u++)e&&n[u].totalTime(n[u].totalDuration()),n[u]._enabled(!1,!1)}}};var c=function(t,i,s,r){i=i!==!1,s=s!==!1,r=r!==!1;for(var n,a,o=p(r),h=i&&s&&r,l=o.length;--l>-1;)a=o[l],(h||a instanceof e||(n=a.target===a.vars.onComplete)&&s||i&&!n)&&a.paused(t)};return r.pauseAll=function(t,e,i){c(!0,t,e,i)},r.resumeAll=function(t,e,i){c(!1,t,e,i)},r.globalTimeScale=function(e){var s=t._rootTimeline,r=i.ticker.time;return arguments.length?(e=e||n,s._startTime=r-(r-s._startTime)*s._timeScale/e,s=t._rootFramesTimeline,r=i.ticker.frame,s._startTime=r-(r-s._startTime)*s._timeScale/e,s._timeScale=t._rootTimeline._timeScale=e,e):s._timeScale},l.progress=function(t){return arguments.length?this.totalTime(this.duration()*(this._yoyo&&0!==(1&this._cycle)?1-t:t)+this._cycle*(this._duration+this._repeatDelay),!1):this._time/this.duration()},l.totalProgress=function(t){return arguments.length?this.totalTime(this.totalDuration()*t,!1):this._totalTime/this.totalDuration()},l.time=function(t,e){return arguments.length?(this._dirty&&this.totalDuration(),t>this._duration&&(t=this._duration),this._yoyo&&0!==(1&this._cycle)?t=this._duration-t+this._cycle*(this._duration+this._repeatDelay):0!==this._repeat&&(t+=this._cycle*(this._duration+this._repeatDelay)),this.totalTime(t,e)):this._time},l.duration=function(e){return arguments.length?t.prototype.duration.call(this,e):this._duration},l.totalDuration=function(t){return arguments.length?-1===this._repeat?this:this.duration((t-this._repeat*this._repeatDelay)/(this._repeat+1)):(this._dirty&&(this._totalDuration=-1===this._repeat?999999999999:this._duration*(this._repeat+1)+this._repeatDelay*this._repeat,this._dirty=!1),this._totalDuration)},l.repeat=function(t){return arguments.length?(this._repeat=t,this._uncache(!0)):this._repeat},l.repeatDelay=function(t){return arguments.length?(this._repeatDelay=t,this._uncache(!0)):this._repeatDelay},l.yoyo=function(t){return arguments.length?(this._yoyo=t,this):this._yoyo},r},!0),_gsScope._gsDefine("TimelineLite",["core.Animation","core.SimpleTimeline","TweenLite"],function(t,e,i){var s=function(t){e.call(this,t),this._labels={},this.autoRemoveChildren=this.vars.autoRemoveChildren===!0,this.smoothChildTiming=this.vars.smoothChildTiming===!0,this._sortChildren=!0,this._onUpdate=this.vars.onUpdate;var i,s,r=this.vars;for(s in r)i=r[s],o(i)&&-1!==i.join("").indexOf("{self}")&&(r[s]=this._swapSelfInParams(i));o(r.tweens)&&this.add(r.tweens,0,r.align,r.stagger)},r=1e-10,n=i._internals,a=n.isSelector,o=n.isArray,h=n.lazyTweens,l=n.lazyRender,_=[],u=_gsScope._gsDefine.globals,p=function(t){var e,i={};for(e in t)i[e]=t[e];return i},c=function(t,e,i,s){t._timeline.pause(t._startTime),e&&e.apply(s||t._timeline,i||_)},f=function(t){var e,i=[],s=t.length;for(e=0;e!==s;i.push(t[e++]));return i},m=s.prototype=new e;return s.version="1.13.1",m.constructor=s,m.kill()._gc=!1,m.to=function(t,e,s,r){var n=s.repeat&&u.TweenMax||i;return e?this.add(new n(t,e,s),r):this.set(t,s,r)},m.from=function(t,e,s,r){return this.add((s.repeat&&u.TweenMax||i).from(t,e,s),r)},m.fromTo=function(t,e,s,r,n){var a=r.repeat&&u.TweenMax||i;return e?this.add(a.fromTo(t,e,s,r),n):this.set(t,r,n)},m.staggerTo=function(t,e,r,n,o,h,l,_){var u,c=new s({onComplete:h,onCompleteParams:l,onCompleteScope:_,smoothChildTiming:this.smoothChildTiming});for("string"==typeof t&&(t=i.selector(t)||t),a(t)&&(t=f(t)),n=n||0,u=0;t.length>u;u++)r.startAt&&(r.startAt=p(r.startAt)),c.to(t[u],e,p(r),u*n);return this.add(c,o)},m.staggerFrom=function(t,e,i,s,r,n,a,o){return i.immediateRender=0!=i.immediateRender,i.runBackwards=!0,this.staggerTo(t,e,i,s,r,n,a,o)},m.staggerFromTo=function(t,e,i,s,r,n,a,o,h){return s.startAt=i,s.immediateRender=0!=s.immediateRender&&0!=i.immediateRender,this.staggerTo(t,e,s,r,n,a,o,h)},m.call=function(t,e,s,r){return this.add(i.delayedCall(0,t,e,s),r)},m.set=function(t,e,s){return s=this._parseTimeOrLabel(s,0,!0),null==e.immediateRender&&(e.immediateRender=s===this._time&&!this._paused),this.add(new i(t,0,e),s)},s.exportRoot=function(t,e){t=t||{},null==t.smoothChildTiming&&(t.smoothChildTiming=!0);var r,n,a=new s(t),o=a._timeline;for(null==e&&(e=!0),o._remove(a,!0),a._startTime=0,a._rawPrevTime=a._time=a._totalTime=o._time,r=o._first;r;)n=r._next,e&&r instanceof i&&r.target===r.vars.onComplete||a.add(r,r._startTime-r._delay),r=n;return o.add(a,0),a},m.add=function(r,n,a,h){var l,_,u,p,c,f;if("number"!=typeof n&&(n=this._parseTimeOrLabel(n,0,!0,r)),!(r instanceof t)){if(r instanceof Array||r&&r.push&&o(r)){for(a=a||"normal",h=h||0,l=n,_=r.length,u=0;_>u;u++)o(p=r[u])&&(p=new s({tweens:p})),this.add(p,l),"string"!=typeof p&&"function"!=typeof p&&("sequence"===a?l=p._startTime+p.totalDuration()/p._timeScale:"start"===a&&(p._startTime-=p.delay())),l+=h;return this._uncache(!0)}if("string"==typeof r)return this.addLabel(r,n);if("function"!=typeof r)throw"Cannot add "+r+" into the timeline; it is not a tween, timeline, function, or string.";r=i.delayedCall(0,r)}if(e.prototype.add.call(this,r,n),(this._gc||this._time===this._duration)&&!this._paused&&this._duration<this.duration())for(c=this,f=c.rawTime()>r._startTime;c._timeline;)f&&c._timeline.smoothChildTiming?c.totalTime(c._totalTime,!0):c._gc&&c._enabled(!0,!1),c=c._timeline;return this},m.remove=function(e){if(e instanceof t)return this._remove(e,!1);if(e instanceof Array||e&&e.push&&o(e)){for(var i=e.length;--i>-1;)this.remove(e[i]);return this}return"string"==typeof e?this.removeLabel(e):this.kill(null,e)},m._remove=function(t,i){e.prototype._remove.call(this,t,i);var s=this._last;return s?this._time>s._startTime+s._totalDuration/s._timeScale&&(this._time=this.duration(),this._totalTime=this._totalDuration):this._time=this._totalTime=this._duration=this._totalDuration=0,this},m.append=function(t,e){return this.add(t,this._parseTimeOrLabel(null,e,!0,t))},m.insert=m.insertMultiple=function(t,e,i,s){return this.add(t,e||0,i,s)},m.appendMultiple=function(t,e,i,s){return this.add(t,this._parseTimeOrLabel(null,e,!0,t),i,s)},m.addLabel=function(t,e){return this._labels[t]=this._parseTimeOrLabel(e),this},m.addPause=function(t,e,i,s){return this.call(c,["{self}",e,i,s],this,t)},m.removeLabel=function(t){return delete this._labels[t],this},m.getLabelTime=function(t){return null!=this._labels[t]?this._labels[t]:-1},m._parseTimeOrLabel=function(e,i,s,r){var n;if(r instanceof t&&r.timeline===this)this.remove(r);else if(r&&(r instanceof Array||r.push&&o(r)))for(n=r.length;--n>-1;)r[n]instanceof t&&r[n].timeline===this&&this.remove(r[n]);if("string"==typeof i)return this._parseTimeOrLabel(i,s&&"number"==typeof e&&null==this._labels[i]?e-this.duration():0,s);if(i=i||0,"string"!=typeof e||!isNaN(e)&&null==this._labels[e])null==e&&(e=this.duration());else{if(n=e.indexOf("="),-1===n)return null==this._labels[e]?s?this._labels[e]=this.duration()+i:i:this._labels[e]+i;i=parseInt(e.charAt(n-1)+"1",10)*Number(e.substr(n+1)),e=n>1?this._parseTimeOrLabel(e.substr(0,n-1),0,s):this.duration()}return Number(e)+i},m.seek=function(t,e){return this.totalTime("number"==typeof t?t:this._parseTimeOrLabel(t),e!==!1)},m.stop=function(){return this.paused(!0)},m.gotoAndPlay=function(t,e){return this.play(t,e)},m.gotoAndStop=function(t,e){return this.pause(t,e)},m.render=function(t,e,i){this._gc&&this._enabled(!0,!1);var s,n,a,o,u,p=this._dirty?this.totalDuration():this._totalDuration,c=this._time,f=this._startTime,m=this._timeScale,d=this._paused;if(t>=p?(this._totalTime=this._time=p,this._reversed||this._hasPausedChild()||(n=!0,o="onComplete",0===this._duration&&(0===t||0>this._rawPrevTime||this._rawPrevTime===r)&&this._rawPrevTime!==t&&this._first&&(u=!0,this._rawPrevTime>r&&(o="onReverseComplete"))),this._rawPrevTime=this._duration||!e||t||this._rawPrevTime===t?t:r,t=p+1e-4):1e-7>t?(this._totalTime=this._time=0,(0!==c||0===this._duration&&this._rawPrevTime!==r&&(this._rawPrevTime>0||0>t&&this._rawPrevTime>=0))&&(o="onReverseComplete",n=this._reversed),0>t?(this._active=!1,this._rawPrevTime>=0&&this._first&&(u=!0),this._rawPrevTime=t):(this._rawPrevTime=this._duration||!e||t||this._rawPrevTime===t?t:r,t=0,this._initted||(u=!0))):this._totalTime=this._time=this._rawPrevTime=t,this._time!==c&&this._first||i||u){if(this._initted||(this._initted=!0),this._active||!this._paused&&this._time!==c&&t>0&&(this._active=!0),0===c&&this.vars.onStart&&0!==this._time&&(e||this.vars.onStart.apply(this.vars.onStartScope||this,this.vars.onStartParams||_)),this._time>=c)for(s=this._first;s&&(a=s._next,!this._paused||d);)(s._active||s._startTime<=this._time&&!s._paused&&!s._gc)&&(s._reversed?s.render((s._dirty?s.totalDuration():s._totalDuration)-(t-s._startTime)*s._timeScale,e,i):s.render((t-s._startTime)*s._timeScale,e,i)),s=a;else for(s=this._last;s&&(a=s._prev,!this._paused||d);)(s._active||c>=s._startTime&&!s._paused&&!s._gc)&&(s._reversed?s.render((s._dirty?s.totalDuration():s._totalDuration)-(t-s._startTime)*s._timeScale,e,i):s.render((t-s._startTime)*s._timeScale,e,i)),s=a;this._onUpdate&&(e||(h.length&&l(),this._onUpdate.apply(this.vars.onUpdateScope||this,this.vars.onUpdateParams||_))),o&&(this._gc||(f===this._startTime||m!==this._timeScale)&&(0===this._time||p>=this.totalDuration())&&(n&&(h.length&&l(),this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),!e&&this.vars[o]&&this.vars[o].apply(this.vars[o+"Scope"]||this,this.vars[o+"Params"]||_)))}},m._hasPausedChild=function(){for(var t=this._first;t;){if(t._paused||t instanceof s&&t._hasPausedChild())return!0;t=t._next}return!1},m.getChildren=function(t,e,s,r){r=r||-9999999999;for(var n=[],a=this._first,o=0;a;)r>a._startTime||(a instanceof i?e!==!1&&(n[o++]=a):(s!==!1&&(n[o++]=a),t!==!1&&(n=n.concat(a.getChildren(!0,e,s)),o=n.length))),a=a._next;return n},m.getTweensOf=function(t,e){var s,r,n=this._gc,a=[],o=0;for(n&&this._enabled(!0,!0),s=i.getTweensOf(t),r=s.length;--r>-1;)(s[r].timeline===this||e&&this._contains(s[r]))&&(a[o++]=s[r]);return n&&this._enabled(!1,!0),a},m._contains=function(t){for(var e=t.timeline;e;){if(e===this)return!0;e=e.timeline}return!1},m.shiftChildren=function(t,e,i){i=i||0;for(var s,r=this._first,n=this._labels;r;)r._startTime>=i&&(r._startTime+=t),r=r._next;if(e)for(s in n)n[s]>=i&&(n[s]+=t);return this._uncache(!0)},m._kill=function(t,e){if(!t&&!e)return this._enabled(!1,!1);for(var i=e?this.getTweensOf(e):this.getChildren(!0,!0,!1),s=i.length,r=!1;--s>-1;)i[s]._kill(t,e)&&(r=!0);return r},m.clear=function(t){var e=this.getChildren(!1,!0,!0),i=e.length;for(this._time=this._totalTime=0;--i>-1;)e[i]._enabled(!1,!1);return t!==!1&&(this._labels={}),this._uncache(!0)},m.invalidate=function(){for(var t=this._first;t;)t.invalidate(),t=t._next;return this},m._enabled=function(t,i){if(t===this._gc)for(var s=this._first;s;)s._enabled(t,!0),s=s._next;return e.prototype._enabled.call(this,t,i)},m.duration=function(t){return arguments.length?(0!==this.duration()&&0!==t&&this.timeScale(this._duration/t),this):(this._dirty&&this.totalDuration(),this._duration)},m.totalDuration=function(t){if(!arguments.length){if(this._dirty){for(var e,i,s=0,r=this._last,n=999999999999;r;)e=r._prev,r._dirty&&r.totalDuration(),r._startTime>n&&this._sortChildren&&!r._paused?this.add(r,r._startTime-r._delay):n=r._startTime,0>r._startTime&&!r._paused&&(s-=r._startTime,this._timeline.smoothChildTiming&&(this._startTime+=r._startTime/this._timeScale),this.shiftChildren(-r._startTime,!1,-9999999999),n=0),i=r._startTime+r._totalDuration/r._timeScale,i>s&&(s=i),r=e;this._duration=this._totalDuration=s,this._dirty=!1}return this._totalDuration}return 0!==this.totalDuration()&&0!==t&&this.timeScale(this._totalDuration/t),this},m.usesFrames=function(){for(var e=this._timeline;e._timeline;)e=e._timeline;return e===t._rootFramesTimeline},m.rawTime=function(){return this._paused?this._totalTime:(this._timeline.rawTime()-this._startTime)*this._timeScale},s},!0),_gsScope._gsDefine("TimelineMax",["TimelineLite","TweenLite","easing.Ease"],function(t,e,i){var s=function(e){t.call(this,e),this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._cycle=0,this._yoyo=this.vars.yoyo===!0,this._dirty=!0},r=1e-10,n=[],a=e._internals,o=a.lazyTweens,h=a.lazyRender,l=new i(null,null,1,0),_=s.prototype=new t;return _.constructor=s,_.kill()._gc=!1,s.version="1.13.1",_.invalidate=function(){return this._yoyo=this.vars.yoyo===!0,this._repeat=this.vars.repeat||0,this._repeatDelay=this.vars.repeatDelay||0,this._uncache(!0),t.prototype.invalidate.call(this)},_.addCallback=function(t,i,s,r){return this.add(e.delayedCall(0,t,s,r),i)},_.removeCallback=function(t,e){if(t)if(null==e)this._kill(null,t);else for(var i=this.getTweensOf(t,!1),s=i.length,r=this._parseTimeOrLabel(e);--s>-1;)i[s]._startTime===r&&i[s]._enabled(!1,!1);return this},_.tweenTo=function(t,i){i=i||{};var s,r,a,o={ease:l,overwrite:i.delay?2:1,useFrames:this.usesFrames(),immediateRender:!1};for(r in i)o[r]=i[r];return o.time=this._parseTimeOrLabel(t),s=Math.abs(Number(o.time)-this._time)/this._timeScale||.001,a=new e(this,s,o),o.onStart=function(){a.target.paused(!0),a.vars.time!==a.target.time()&&s===a.duration()&&a.duration(Math.abs(a.vars.time-a.target.time())/a.target._timeScale),i.onStart&&i.onStart.apply(i.onStartScope||a,i.onStartParams||n)},a},_.tweenFromTo=function(t,e,i){i=i||{},t=this._parseTimeOrLabel(t),i.startAt={onComplete:this.seek,onCompleteParams:[t],onCompleteScope:this},i.immediateRender=i.immediateRender!==!1;var s=this.tweenTo(e,i);return s.duration(Math.abs(s.vars.time-t)/this._timeScale||.001)},_.render=function(t,e,i){this._gc&&this._enabled(!0,!1);var s,a,l,_,u,p,c=this._dirty?this.totalDuration():this._totalDuration,f=this._duration,m=this._time,d=this._totalTime,g=this._startTime,v=this._timeScale,y=this._rawPrevTime,T=this._paused,w=this._cycle;if(t>=c?(this._locked||(this._totalTime=c,this._cycle=this._repeat),this._reversed||this._hasPausedChild()||(a=!0,_="onComplete",0===this._duration&&(0===t||0>y||y===r)&&y!==t&&this._first&&(u=!0,y>r&&(_="onReverseComplete"))),this._rawPrevTime=this._duration||!e||t||this._rawPrevTime===t?t:r,this._yoyo&&0!==(1&this._cycle)?this._time=t=0:(this._time=f,t=f+1e-4)):1e-7>t?(this._locked||(this._totalTime=this._cycle=0),this._time=0,(0!==m||0===f&&y!==r&&(y>0||0>t&&y>=0)&&!this._locked)&&(_="onReverseComplete",a=this._reversed),0>t?(this._active=!1,y>=0&&this._first&&(u=!0),this._rawPrevTime=t):(this._rawPrevTime=f||!e||t||this._rawPrevTime===t?t:r,t=0,this._initted||(u=!0))):(0===f&&0>y&&(u=!0),this._time=this._rawPrevTime=t,this._locked||(this._totalTime=t,0!==this._repeat&&(p=f+this._repeatDelay,this._cycle=this._totalTime/p>>0,0!==this._cycle&&this._cycle===this._totalTime/p&&this._cycle--,this._time=this._totalTime-this._cycle*p,this._yoyo&&0!==(1&this._cycle)&&(this._time=f-this._time),this._time>f?(this._time=f,t=f+1e-4):0>this._time?this._time=t=0:t=this._time))),this._cycle!==w&&!this._locked){var x=this._yoyo&&0!==(1&w),b=x===(this._yoyo&&0!==(1&this._cycle)),P=this._totalTime,S=this._cycle,k=this._rawPrevTime,R=this._time;if(this._totalTime=w*f,w>this._cycle?x=!x:this._totalTime+=f,this._time=m,this._rawPrevTime=0===f?y-1e-4:y,this._cycle=w,this._locked=!0,m=x?0:f,this.render(m,e,0===f),e||this._gc||this.vars.onRepeat&&this.vars.onRepeat.apply(this.vars.onRepeatScope||this,this.vars.onRepeatParams||n),b&&(m=x?f+1e-4:-1e-4,this.render(m,!0,!1)),this._locked=!1,this._paused&&!T)return;this._time=R,this._totalTime=P,this._cycle=S,this._rawPrevTime=k}if(!(this._time!==m&&this._first||i||u))return d!==this._totalTime&&this._onUpdate&&(e||this._onUpdate.apply(this.vars.onUpdateScope||this,this.vars.onUpdateParams||n)),void 0;if(this._initted||(this._initted=!0),this._active||!this._paused&&this._totalTime!==d&&t>0&&(this._active=!0),0===d&&this.vars.onStart&&0!==this._totalTime&&(e||this.vars.onStart.apply(this.vars.onStartScope||this,this.vars.onStartParams||n)),this._time>=m)for(s=this._first;s&&(l=s._next,!this._paused||T);)(s._active||s._startTime<=this._time&&!s._paused&&!s._gc)&&(s._reversed?s.render((s._dirty?s.totalDuration():s._totalDuration)-(t-s._startTime)*s._timeScale,e,i):s.render((t-s._startTime)*s._timeScale,e,i)),s=l;else for(s=this._last;s&&(l=s._prev,!this._paused||T);)(s._active||m>=s._startTime&&!s._paused&&!s._gc)&&(s._reversed?s.render((s._dirty?s.totalDuration():s._totalDuration)-(t-s._startTime)*s._timeScale,e,i):s.render((t-s._startTime)*s._timeScale,e,i)),s=l;this._onUpdate&&(e||(o.length&&h(),this._onUpdate.apply(this.vars.onUpdateScope||this,this.vars.onUpdateParams||n))),_&&(this._locked||this._gc||(g===this._startTime||v!==this._timeScale)&&(0===this._time||c>=this.totalDuration())&&(a&&(o.length&&h(),this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),!e&&this.vars[_]&&this.vars[_].apply(this.vars[_+"Scope"]||this,this.vars[_+"Params"]||n)))},_.getActive=function(t,e,i){null==t&&(t=!0),null==e&&(e=!0),null==i&&(i=!1);var s,r,n=[],a=this.getChildren(t,e,i),o=0,h=a.length;for(s=0;h>s;s++)r=a[s],r.isActive()&&(n[o++]=r);return n},_.getLabelAfter=function(t){t||0!==t&&(t=this._time);var e,i=this.getLabelsArray(),s=i.length;for(e=0;s>e;e++)if(i[e].time>t)return i[e].name;return null},_.getLabelBefore=function(t){null==t&&(t=this._time);for(var e=this.getLabelsArray(),i=e.length;--i>-1;)if(t>e[i].time)return e[i].name;return null},_.getLabelsArray=function(){var t,e=[],i=0;for(t in this._labels)e[i++]={time:this._labels[t],name:t};return e.sort(function(t,e){return t.time-e.time}),e},_.progress=function(t){return arguments.length?this.totalTime(this.duration()*(this._yoyo&&0!==(1&this._cycle)?1-t:t)+this._cycle*(this._duration+this._repeatDelay),!1):this._time/this.duration()},_.totalProgress=function(t){return arguments.length?this.totalTime(this.totalDuration()*t,!1):this._totalTime/this.totalDuration()},_.totalDuration=function(e){return arguments.length?-1===this._repeat?this:this.duration((e-this._repeat*this._repeatDelay)/(this._repeat+1)):(this._dirty&&(t.prototype.totalDuration.call(this),this._totalDuration=-1===this._repeat?999999999999:this._duration*(this._repeat+1)+this._repeatDelay*this._repeat),this._totalDuration)},_.time=function(t,e){return arguments.length?(this._dirty&&this.totalDuration(),t>this._duration&&(t=this._duration),this._yoyo&&0!==(1&this._cycle)?t=this._duration-t+this._cycle*(this._duration+this._repeatDelay):0!==this._repeat&&(t+=this._cycle*(this._duration+this._repeatDelay)),this.totalTime(t,e)):this._time},_.repeat=function(t){return arguments.length?(this._repeat=t,this._uncache(!0)):this._repeat},_.repeatDelay=function(t){return arguments.length?(this._repeatDelay=t,this._uncache(!0)):this._repeatDelay},_.yoyo=function(t){return arguments.length?(this._yoyo=t,this):this._yoyo},_.currentLabel=function(t){return arguments.length?this.seek(t,!0):this.getLabelBefore(this._time+1e-8)},s},!0),function(){var t=180/Math.PI,e=[],i=[],s=[],r={},n=function(t,e,i,s){this.a=t,this.b=e,this.c=i,this.d=s,this.da=s-t,this.ca=i-t,this.ba=e-t},a=",x,y,z,left,top,right,bottom,marginTop,marginLeft,marginRight,marginBottom,paddingLeft,paddingTop,paddingRight,paddingBottom,backgroundPosition,backgroundPosition_y,",o=function(t,e,i,s){var r={a:t},n={},a={},o={c:s},h=(t+e)/2,l=(e+i)/2,_=(i+s)/2,u=(h+l)/2,p=(l+_)/2,c=(p-u)/8;return r.b=h+(t-h)/4,n.b=u+c,r.c=n.a=(r.b+n.b)/2,n.c=a.a=(u+p)/2,a.b=p-c,o.b=_+(s-_)/4,a.c=o.a=(a.b+o.b)/2,[r,n,a,o]},h=function(t,r,n,a,h){var l,_,u,p,c,f,m,d,g,v,y,T,w,x=t.length-1,b=0,P=t[0].a;for(l=0;x>l;l++)c=t[b],_=c.a,u=c.d,p=t[b+1].d,h?(y=e[l],T=i[l],w=.25*(T+y)*r/(a?.5:s[l]||.5),f=u-(u-_)*(a?.5*r:0!==y?w/y:0),m=u+(p-u)*(a?.5*r:0!==T?w/T:0),d=u-(f+((m-f)*(3*y/(y+T)+.5)/4||0))):(f=u-.5*(u-_)*r,m=u+.5*(p-u)*r,d=u-(f+m)/2),f+=d,m+=d,c.c=g=f,c.b=0!==l?P:P=c.a+.6*(c.c-c.a),c.da=u-_,c.ca=g-_,c.ba=P-_,n?(v=o(_,P,g,u),t.splice(b,1,v[0],v[1],v[2],v[3]),b+=4):b++,P=m;c=t[b],c.b=P,c.c=P+.4*(c.d-P),c.da=c.d-c.a,c.ca=c.c-c.a,c.ba=P-c.a,n&&(v=o(c.a,P,c.c,c.d),t.splice(b,1,v[0],v[1],v[2],v[3]))},l=function(t,s,r,a){var o,h,l,_,u,p,c=[];if(a)for(t=[a].concat(t),h=t.length;--h>-1;)"string"==typeof(p=t[h][s])&&"="===p.charAt(1)&&(t[h][s]=a[s]+Number(p.charAt(0)+p.substr(2)));if(o=t.length-2,0>o)return c[0]=new n(t[0][s],0,0,t[-1>o?0:1][s]),c;for(h=0;o>h;h++)l=t[h][s],_=t[h+1][s],c[h]=new n(l,0,0,_),r&&(u=t[h+2][s],e[h]=(e[h]||0)+(_-l)*(_-l),i[h]=(i[h]||0)+(u-_)*(u-_));return c[h]=new n(t[h][s],0,0,t[h+1][s]),c},_=function(t,n,o,_,u,p){var c,f,m,d,g,v,y,T,w={},x=[],b=p||t[0];u="string"==typeof u?","+u+",":a,null==n&&(n=1);for(f in t[0])x.push(f);if(t.length>1){for(T=t[t.length-1],y=!0,c=x.length;--c>-1;)if(f=x[c],Math.abs(b[f]-T[f])>.05){y=!1;break}y&&(t=t.concat(),p&&t.unshift(p),t.push(t[1]),p=t[t.length-3])}for(e.length=i.length=s.length=0,c=x.length;--c>-1;)f=x[c],r[f]=-1!==u.indexOf(","+f+","),w[f]=l(t,f,r[f],p);for(c=e.length;--c>-1;)e[c]=Math.sqrt(e[c]),i[c]=Math.sqrt(i[c]);if(!_){for(c=x.length;--c>-1;)if(r[f])for(m=w[x[c]],v=m.length-1,d=0;v>d;d++)g=m[d+1].da/i[d]+m[d].da/e[d],s[d]=(s[d]||0)+g*g;for(c=s.length;--c>-1;)s[c]=Math.sqrt(s[c])}for(c=x.length,d=o?4:1;--c>-1;)f=x[c],m=w[f],h(m,n,o,_,r[f]),y&&(m.splice(0,d),m.splice(m.length-d,d));return w},u=function(t,e,i){e=e||"soft";var s,r,a,o,h,l,_,u,p,c,f,m={},d="cubic"===e?3:2,g="soft"===e,v=[];if(g&&i&&(t=[i].concat(t)),null==t||d+1>t.length)throw"invalid Bezier data";for(p in t[0])v.push(p);for(l=v.length;--l>-1;){for(p=v[l],m[p]=h=[],c=0,u=t.length,_=0;u>_;_++)s=null==i?t[_][p]:"string"==typeof(f=t[_][p])&&"="===f.charAt(1)?i[p]+Number(f.charAt(0)+f.substr(2)):Number(f),g&&_>1&&u-1>_&&(h[c++]=(s+h[c-2])/2),h[c++]=s;for(u=c-d+1,c=0,_=0;u>_;_+=d)s=h[_],r=h[_+1],a=h[_+2],o=2===d?0:h[_+3],h[c++]=f=3===d?new n(s,r,a,o):new n(s,(2*r+s)/3,(2*r+a)/3,a);h.length=c}return m},p=function(t,e,i){for(var s,r,n,a,o,h,l,_,u,p,c,f=1/i,m=t.length;--m>-1;)for(p=t[m],n=p.a,a=p.d-n,o=p.c-n,h=p.b-n,s=r=0,_=1;i>=_;_++)l=f*_,u=1-l,s=r-(r=(l*l*a+3*u*(l*o+u*h))*l),c=m*i+_-1,e[c]=(e[c]||0)+s*s},c=function(t,e){e=e>>0||6;var i,s,r,n,a=[],o=[],h=0,l=0,_=e-1,u=[],c=[];for(i in t)p(t[i],a,e);for(r=a.length,s=0;r>s;s++)h+=Math.sqrt(a[s]),n=s%e,c[n]=h,n===_&&(l+=h,n=s/e>>0,u[n]=c,o[n]=l,h=0,c=[]);return{length:l,lengths:o,segments:u}},f=_gsScope._gsDefine.plugin({propName:"bezier",priority:-1,version:"1.3.3",API:2,global:!0,init:function(t,e,i){this._target=t,e instanceof Array&&(e={values:e}),this._func={},this._round={},this._props=[],this._timeRes=null==e.timeResolution?6:parseInt(e.timeResolution,10);var s,r,n,a,o,h=e.values||[],l={},p=h[0],f=e.autoRotate||i.vars.orientToBezier;this._autoRotate=f?f instanceof Array?f:[["x","y","rotation",f===!0?0:Number(f)||0]]:null;for(s in p)this._props.push(s);for(n=this._props.length;--n>-1;)s=this._props[n],this._overwriteProps.push(s),r=this._func[s]="function"==typeof t[s],l[s]=r?t[s.indexOf("set")||"function"!=typeof t["get"+s.substr(3)]?s:"get"+s.substr(3)]():parseFloat(t[s]),o||l[s]!==h[0][s]&&(o=l);if(this._beziers="cubic"!==e.type&&"quadratic"!==e.type&&"soft"!==e.type?_(h,isNaN(e.curviness)?1:e.curviness,!1,"thruBasic"===e.type,e.correlate,o):u(h,e.type,l),this._segCount=this._beziers[s].length,this._timeRes){var m=c(this._beziers,this._timeRes);this._length=m.length,this._lengths=m.lengths,this._segments=m.segments,this._l1=this._li=this._s1=this._si=0,this._l2=this._lengths[0],this._curSeg=this._segments[0],this._s2=this._curSeg[0],this._prec=1/this._curSeg.length}if(f=this._autoRotate)for(this._initialRotations=[],f[0]instanceof Array||(this._autoRotate=f=[f]),n=f.length;--n>-1;){for(a=0;3>a;a++)s=f[n][a],this._func[s]="function"==typeof t[s]?t[s.indexOf("set")||"function"!=typeof t["get"+s.substr(3)]?s:"get"+s.substr(3)]:!1;s=f[n][2],this._initialRotations[n]=this._func[s]?this._func[s].call(this._target):this._target[s]}return this._startRatio=i.vars.runBackwards?1:0,!0},set:function(e){var i,s,r,n,a,o,h,l,_,u,p=this._segCount,c=this._func,f=this._target,m=e!==this._startRatio;if(this._timeRes){if(_=this._lengths,u=this._curSeg,e*=this._length,r=this._li,e>this._l2&&p-1>r){for(l=p-1;l>r&&e>=(this._l2=_[++r]););this._l1=_[r-1],this._li=r,this._curSeg=u=this._segments[r],this._s2=u[this._s1=this._si=0]}else if(this._l1>e&&r>0){for(;r>0&&(this._l1=_[--r])>=e;);0===r&&this._l1>e?this._l1=0:r++,this._l2=_[r],this._li=r,this._curSeg=u=this._segments[r],this._s1=u[(this._si=u.length-1)-1]||0,this._s2=u[this._si]}if(i=r,e-=this._l1,r=this._si,e>this._s2&&u.length-1>r){for(l=u.length-1;l>r&&e>=(this._s2=u[++r]););this._s1=u[r-1],this._si=r}else if(this._s1>e&&r>0){for(;r>0&&(this._s1=u[--r])>=e;);0===r&&this._s1>e?this._s1=0:r++,this._s2=u[r],this._si=r}o=(r+(e-this._s1)/(this._s2-this._s1))*this._prec}else i=0>e?0:e>=1?p-1:p*e>>0,o=(e-i*(1/p))*p;for(s=1-o,r=this._props.length;--r>-1;)n=this._props[r],a=this._beziers[n][i],h=(o*o*a.da+3*s*(o*a.ca+s*a.ba))*o+a.a,this._round[n]&&(h=Math.round(h)),c[n]?f[n](h):f[n]=h;if(this._autoRotate){var d,g,v,y,T,w,x,b=this._autoRotate;
for(r=b.length;--r>-1;)n=b[r][2],w=b[r][3]||0,x=b[r][4]===!0?1:t,a=this._beziers[b[r][0]],d=this._beziers[b[r][1]],a&&d&&(a=a[i],d=d[i],g=a.a+(a.b-a.a)*o,y=a.b+(a.c-a.b)*o,g+=(y-g)*o,y+=(a.c+(a.d-a.c)*o-y)*o,v=d.a+(d.b-d.a)*o,T=d.b+(d.c-d.b)*o,v+=(T-v)*o,T+=(d.c+(d.d-d.c)*o-T)*o,h=m?Math.atan2(T-v,y-g)*x+w:this._initialRotations[r],c[n]?f[n](h):f[n]=h)}}}),m=f.prototype;f.bezierThrough=_,f.cubicToQuadratic=o,f._autoCSS=!0,f.quadraticToCubic=function(t,e,i){return new n(t,(2*e+t)/3,(2*e+i)/3,i)},f._cssRegister=function(){var t=_gsScope._gsDefine.globals.CSSPlugin;if(t){var e=t._internals,i=e._parseToProxy,s=e._setPluginRatio,r=e.CSSPropTween;e._registerComplexSpecialProp("bezier",{parser:function(t,e,n,a,o,h){e instanceof Array&&(e={values:e}),h=new f;var l,_,u,p=e.values,c=p.length-1,m=[],d={};if(0>c)return o;for(l=0;c>=l;l++)u=i(t,p[l],a,o,h,c!==l),m[l]=u.end;for(_ in e)d[_]=e[_];return d.values=m,o=new r(t,"bezier",0,0,u.pt,2),o.data=u,o.plugin=h,o.setRatio=s,0===d.autoRotate&&(d.autoRotate=!0),!d.autoRotate||d.autoRotate instanceof Array||(l=d.autoRotate===!0?0:Number(d.autoRotate),d.autoRotate=null!=u.end.left?[["left","top","rotation",l,!1]]:null!=u.end.x?[["x","y","rotation",l,!1]]:!1),d.autoRotate&&(a._transform||a._enableTransforms(!1),u.autoRotate=a._target._gsTransform),h._onInitTween(u.proxy,d,a._tween),o}})}},m._roundProps=function(t,e){for(var i=this._overwriteProps,s=i.length;--s>-1;)(t[i[s]]||t.bezier||t.bezierThrough)&&(this._round[i[s]]=e)},m._kill=function(t){var e,i,s=this._props;for(e in this._beziers)if(e in t)for(delete this._beziers[e],delete this._func[e],i=s.length;--i>-1;)s[i]===e&&s.splice(i,1);return this._super._kill.call(this,t)}}(),_gsScope._gsDefine("plugins.CSSPlugin",["plugins.TweenPlugin","TweenLite"],function(t,e){var i,s,r,n,a=function(){t.call(this,"css"),this._overwriteProps.length=0,this.setRatio=a.prototype.setRatio},o={},h=a.prototype=new t("css");h.constructor=a,a.version="1.13.1",a.API=2,a.defaultTransformPerspective=0,a.defaultSkewType="compensated",h="px",a.suffixMap={top:h,right:h,bottom:h,left:h,width:h,height:h,fontSize:h,padding:h,margin:h,perspective:h,lineHeight:""};var l,_,u,p,c,f,m=/(?:\d|\-\d|\.\d|\-\.\d)+/g,d=/(?:\d|\-\d|\.\d|\-\.\d|\+=\d|\-=\d|\+=.\d|\-=\.\d)+/g,g=/(?:\+=|\-=|\-|\b)[\d\-\.]+[a-zA-Z0-9]*(?:%|\b)/gi,v=/[^\d\-\.]/g,y=/(?:\d|\-|\+|=|#|\.)*/g,T=/opacity *= *([^)]*)/i,w=/opacity:([^;]*)/i,x=/alpha\(opacity *=.+?\)/i,b=/^(rgb|hsl)/,P=/([A-Z])/g,S=/-([a-z])/gi,k=/(^(?:url\(\"|url\())|(?:(\"\))$|\)$)/gi,R=function(t,e){return e.toUpperCase()},A=/(?:Left|Right|Width)/i,C=/(M11|M12|M21|M22)=[\d\-\.e]+/gi,O=/progid\:DXImageTransform\.Microsoft\.Matrix\(.+?\)/i,D=/,(?=[^\)]*(?:\(|$))/gi,M=Math.PI/180,z=180/Math.PI,I={},E=document,L=E.createElement("div"),F=E.createElement("img"),N=a._internals={_specialProps:o},X=navigator.userAgent,U=function(){var t,e=X.indexOf("Android"),i=E.createElement("div");return u=-1!==X.indexOf("Safari")&&-1===X.indexOf("Chrome")&&(-1===e||Number(X.substr(e+8,1))>3),c=u&&6>Number(X.substr(X.indexOf("Version/")+8,1)),p=-1!==X.indexOf("Firefox"),/MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(X)&&(f=parseFloat(RegExp.$1)),i.innerHTML="<a style='top:1px;opacity:.55;'>a</a>",t=i.getElementsByTagName("a")[0],t?/^0.55/.test(t.style.opacity):!1}(),Y=function(t){return T.test("string"==typeof t?t:(t.currentStyle?t.currentStyle.filter:t.style.filter)||"")?parseFloat(RegExp.$1)/100:1},j=function(t){window.console&&console.log(t)},B="",q="",V=function(t,e){e=e||L;var i,s,r=e.style;if(void 0!==r[t])return t;for(t=t.charAt(0).toUpperCase()+t.substr(1),i=["O","Moz","ms","Ms","Webkit"],s=5;--s>-1&&void 0===r[i[s]+t];);return s>=0?(q=3===s?"ms":i[s],B="-"+q.toLowerCase()+"-",q+t):null},G=E.defaultView?E.defaultView.getComputedStyle:function(){},W=a.getStyle=function(t,e,i,s,r){var n;return U||"opacity"!==e?(!s&&t.style[e]?n=t.style[e]:(i=i||G(t))?n=i[e]||i.getPropertyValue(e)||i.getPropertyValue(e.replace(P,"-$1").toLowerCase()):t.currentStyle&&(n=t.currentStyle[e]),null==r||n&&"none"!==n&&"auto"!==n&&"auto auto"!==n?n:r):Y(t)},Q=N.convertToPixels=function(t,i,s,r,n){if("px"===r||!r)return s;if("auto"===r||!s)return 0;var o,h,l,_=A.test(i),u=t,p=L.style,c=0>s;if(c&&(s=-s),"%"===r&&-1!==i.indexOf("border"))o=s/100*(_?t.clientWidth:t.clientHeight);else{if(p.cssText="border:0 solid red;position:"+W(t,"position")+";line-height:0;","%"!==r&&u.appendChild)p[_?"borderLeftWidth":"borderTopWidth"]=s+r;else{if(u=t.parentNode||E.body,h=u._gsCache,l=e.ticker.frame,h&&_&&h.time===l)return h.width*s/100;p[_?"width":"height"]=s+r}u.appendChild(L),o=parseFloat(L[_?"offsetWidth":"offsetHeight"]),u.removeChild(L),_&&"%"===r&&a.cacheWidths!==!1&&(h=u._gsCache=u._gsCache||{},h.time=l,h.width=100*(o/s)),0!==o||n||(o=Q(t,i,s,r,!0))}return c?-o:o},Z=N.calculateOffset=function(t,e,i){if("absolute"!==W(t,"position",i))return 0;var s="left"===e?"Left":"Top",r=W(t,"margin"+s,i);return t["offset"+s]-(Q(t,e,parseFloat(r),r.replace(y,""))||0)},$=function(t,e){var i,s,r={};if(e=e||G(t,null))if(i=e.length)for(;--i>-1;)r[e[i].replace(S,R)]=e.getPropertyValue(e[i]);else for(i in e)r[i]=e[i];else if(e=t.currentStyle||t.style)for(i in e)"string"==typeof i&&void 0===r[i]&&(r[i.replace(S,R)]=e[i]);return U||(r.opacity=Y(t)),s=Pe(t,e,!1),r.rotation=s.rotation,r.skewX=s.skewX,r.scaleX=s.scaleX,r.scaleY=s.scaleY,r.x=s.x,r.y=s.y,xe&&(r.z=s.z,r.rotationX=s.rotationX,r.rotationY=s.rotationY,r.scaleZ=s.scaleZ),r.filters&&delete r.filters,r},H=function(t,e,i,s,r){var n,a,o,h={},l=t.style;for(a in i)"cssText"!==a&&"length"!==a&&isNaN(a)&&(e[a]!==(n=i[a])||r&&r[a])&&-1===a.indexOf("Origin")&&("number"==typeof n||"string"==typeof n)&&(h[a]="auto"!==n||"left"!==a&&"top"!==a?""!==n&&"auto"!==n&&"none"!==n||"string"!=typeof e[a]||""===e[a].replace(v,"")?n:0:Z(t,a),void 0!==l[a]&&(o=new ue(l,a,l[a],o)));if(s)for(a in s)"className"!==a&&(h[a]=s[a]);return{difs:h,firstMPT:o}},K={width:["Left","Right"],height:["Top","Bottom"]},J=["marginLeft","marginRight","marginTop","marginBottom"],te=function(t,e,i){var s=parseFloat("width"===e?t.offsetWidth:t.offsetHeight),r=K[e],n=r.length;for(i=i||G(t,null);--n>-1;)s-=parseFloat(W(t,"padding"+r[n],i,!0))||0,s-=parseFloat(W(t,"border"+r[n]+"Width",i,!0))||0;return s},ee=function(t,e){(null==t||""===t||"auto"===t||"auto auto"===t)&&(t="0 0");var i=t.split(" "),s=-1!==t.indexOf("left")?"0%":-1!==t.indexOf("right")?"100%":i[0],r=-1!==t.indexOf("top")?"0%":-1!==t.indexOf("bottom")?"100%":i[1];return null==r?r="0":"center"===r&&(r="50%"),("center"===s||isNaN(parseFloat(s))&&-1===(s+"").indexOf("="))&&(s="50%"),e&&(e.oxp=-1!==s.indexOf("%"),e.oyp=-1!==r.indexOf("%"),e.oxr="="===s.charAt(1),e.oyr="="===r.charAt(1),e.ox=parseFloat(s.replace(v,"")),e.oy=parseFloat(r.replace(v,""))),s+" "+r+(i.length>2?" "+i[2]:"")},ie=function(t,e){return"string"==typeof t&&"="===t.charAt(1)?parseInt(t.charAt(0)+"1",10)*parseFloat(t.substr(2)):parseFloat(t)-parseFloat(e)},se=function(t,e){return null==t?e:"string"==typeof t&&"="===t.charAt(1)?parseInt(t.charAt(0)+"1",10)*Number(t.substr(2))+e:parseFloat(t)},re=function(t,e,i,s){var r,n,a,o,h=1e-6;return null==t?o=e:"number"==typeof t?o=t:(r=360,n=t.split("_"),a=Number(n[0].replace(v,""))*(-1===t.indexOf("rad")?1:z)-("="===t.charAt(1)?0:e),n.length&&(s&&(s[i]=e+a),-1!==t.indexOf("short")&&(a%=r,a!==a%(r/2)&&(a=0>a?a+r:a-r)),-1!==t.indexOf("_cw")&&0>a?a=(a+9999999999*r)%r-(0|a/r)*r:-1!==t.indexOf("ccw")&&a>0&&(a=(a-9999999999*r)%r-(0|a/r)*r)),o=e+a),h>o&&o>-h&&(o=0),o},ne={aqua:[0,255,255],lime:[0,255,0],silver:[192,192,192],black:[0,0,0],maroon:[128,0,0],teal:[0,128,128],blue:[0,0,255],navy:[0,0,128],white:[255,255,255],fuchsia:[255,0,255],olive:[128,128,0],yellow:[255,255,0],orange:[255,165,0],gray:[128,128,128],purple:[128,0,128],green:[0,128,0],red:[255,0,0],pink:[255,192,203],cyan:[0,255,255],transparent:[255,255,255,0]},ae=function(t,e,i){return t=0>t?t+1:t>1?t-1:t,0|255*(1>6*t?e+6*(i-e)*t:.5>t?i:2>3*t?e+6*(i-e)*(2/3-t):e)+.5},oe=function(t){var e,i,s,r,n,a;return t&&""!==t?"number"==typeof t?[t>>16,255&t>>8,255&t]:(","===t.charAt(t.length-1)&&(t=t.substr(0,t.length-1)),ne[t]?ne[t]:"#"===t.charAt(0)?(4===t.length&&(e=t.charAt(1),i=t.charAt(2),s=t.charAt(3),t="#"+e+e+i+i+s+s),t=parseInt(t.substr(1),16),[t>>16,255&t>>8,255&t]):"hsl"===t.substr(0,3)?(t=t.match(m),r=Number(t[0])%360/360,n=Number(t[1])/100,a=Number(t[2])/100,i=.5>=a?a*(n+1):a+n-a*n,e=2*a-i,t.length>3&&(t[3]=Number(t[3])),t[0]=ae(r+1/3,e,i),t[1]=ae(r,e,i),t[2]=ae(r-1/3,e,i),t):(t=t.match(m)||ne.transparent,t[0]=Number(t[0]),t[1]=Number(t[1]),t[2]=Number(t[2]),t.length>3&&(t[3]=Number(t[3])),t)):ne.black},he="(?:\\b(?:(?:rgb|rgba|hsl|hsla)\\(.+?\\))|\\B#.+?\\b";for(h in ne)he+="|"+h+"\\b";he=RegExp(he+")","gi");var le=function(t,e,i,s){if(null==t)return function(t){return t};var r,n=e?(t.match(he)||[""])[0]:"",a=t.split(n).join("").match(g)||[],o=t.substr(0,t.indexOf(a[0])),h=")"===t.charAt(t.length-1)?")":"",l=-1!==t.indexOf(" ")?" ":",",_=a.length,u=_>0?a[0].replace(m,""):"";return _?r=e?function(t){var e,p,c,f;if("number"==typeof t)t+=u;else if(s&&D.test(t)){for(f=t.replace(D,"|").split("|"),c=0;f.length>c;c++)f[c]=r(f[c]);return f.join(",")}if(e=(t.match(he)||[n])[0],p=t.split(e).join("").match(g)||[],c=p.length,_>c--)for(;_>++c;)p[c]=i?p[0|(c-1)/2]:a[c];return o+p.join(l)+l+e+h+(-1!==t.indexOf("inset")?" inset":"")}:function(t){var e,n,p;if("number"==typeof t)t+=u;else if(s&&D.test(t)){for(n=t.replace(D,"|").split("|"),p=0;n.length>p;p++)n[p]=r(n[p]);return n.join(",")}if(e=t.match(g)||[],p=e.length,_>p--)for(;_>++p;)e[p]=i?e[0|(p-1)/2]:a[p];return o+e.join(l)+h}:function(t){return t}},_e=function(t){return t=t.split(","),function(e,i,s,r,n,a,o){var h,l=(i+"").split(" ");for(o={},h=0;4>h;h++)o[t[h]]=l[h]=l[h]||l[(h-1)/2>>0];return r.parse(e,o,n,a)}},ue=(N._setPluginRatio=function(t){this.plugin.setRatio(t);for(var e,i,s,r,n=this.data,a=n.proxy,o=n.firstMPT,h=1e-6;o;)e=a[o.v],o.r?e=Math.round(e):h>e&&e>-h&&(e=0),o.t[o.p]=e,o=o._next;if(n.autoRotate&&(n.autoRotate.rotation=a.rotation),1===t)for(o=n.firstMPT;o;){if(i=o.t,i.type){if(1===i.type){for(r=i.xs0+i.s+i.xs1,s=1;i.l>s;s++)r+=i["xn"+s]+i["xs"+(s+1)];i.e=r}}else i.e=i.s+i.xs0;o=o._next}},function(t,e,i,s,r){this.t=t,this.p=e,this.v=i,this.r=r,s&&(s._prev=this,this._next=s)}),pe=(N._parseToProxy=function(t,e,i,s,r,n){var a,o,h,l,_,u=s,p={},c={},f=i._transform,m=I;for(i._transform=null,I=e,s=_=i.parse(t,e,s,r),I=m,n&&(i._transform=f,u&&(u._prev=null,u._prev&&(u._prev._next=null)));s&&s!==u;){if(1>=s.type&&(o=s.p,c[o]=s.s+s.c,p[o]=s.s,n||(l=new ue(s,"s",o,l,s.r),s.c=0),1===s.type))for(a=s.l;--a>0;)h="xn"+a,o=s.p+"_"+h,c[o]=s.data[h],p[o]=s[h],n||(l=new ue(s,h,o,l,s.rxp[h]));s=s._next}return{proxy:p,end:c,firstMPT:l,pt:_}},N.CSSPropTween=function(t,e,s,r,a,o,h,l,_,u,p){this.t=t,this.p=e,this.s=s,this.c=r,this.n=h||e,t instanceof pe||n.push(this.n),this.r=l,this.type=o||0,_&&(this.pr=_,i=!0),this.b=void 0===u?s:u,this.e=void 0===p?s+r:p,a&&(this._next=a,a._prev=this)}),ce=a.parseComplex=function(t,e,i,s,r,n,a,o,h,_){i=i||n||"",a=new pe(t,e,0,0,a,_?2:1,null,!1,o,i,s),s+="";var u,p,c,f,g,v,y,T,w,x,P,S,k=i.split(", ").join(",").split(" "),R=s.split(", ").join(",").split(" "),A=k.length,C=l!==!1;for((-1!==s.indexOf(",")||-1!==i.indexOf(","))&&(k=k.join(" ").replace(D,", ").split(" "),R=R.join(" ").replace(D,", ").split(" "),A=k.length),A!==R.length&&(k=(n||"").split(" "),A=k.length),a.plugin=h,a.setRatio=_,u=0;A>u;u++)if(f=k[u],g=R[u],T=parseFloat(f),T||0===T)a.appendXtra("",T,ie(g,T),g.replace(d,""),C&&-1!==g.indexOf("px"),!0);else if(r&&("#"===f.charAt(0)||ne[f]||b.test(f)))S=","===g.charAt(g.length-1)?"),":")",f=oe(f),g=oe(g),w=f.length+g.length>6,w&&!U&&0===g[3]?(a["xs"+a.l]+=a.l?" transparent":"transparent",a.e=a.e.split(R[u]).join("transparent")):(U||(w=!1),a.appendXtra(w?"rgba(":"rgb(",f[0],g[0]-f[0],",",!0,!0).appendXtra("",f[1],g[1]-f[1],",",!0).appendXtra("",f[2],g[2]-f[2],w?",":S,!0),w&&(f=4>f.length?1:f[3],a.appendXtra("",f,(4>g.length?1:g[3])-f,S,!1)));else if(v=f.match(m)){if(y=g.match(d),!y||y.length!==v.length)return a;for(c=0,p=0;v.length>p;p++)P=v[p],x=f.indexOf(P,c),a.appendXtra(f.substr(c,x-c),Number(P),ie(y[p],P),"",C&&"px"===f.substr(x+P.length,2),0===p),c=x+P.length;a["xs"+a.l]+=f.substr(c)}else a["xs"+a.l]+=a.l?" "+f:f;if(-1!==s.indexOf("=")&&a.data){for(S=a.xs0+a.data.s,u=1;a.l>u;u++)S+=a["xs"+u]+a.data["xn"+u];a.e=S+a["xs"+u]}return a.l||(a.type=-1,a.xs0=a.e),a.xfirst||a},fe=9;for(h=pe.prototype,h.l=h.pr=0;--fe>0;)h["xn"+fe]=0,h["xs"+fe]="";h.xs0="",h._next=h._prev=h.xfirst=h.data=h.plugin=h.setRatio=h.rxp=null,h.appendXtra=function(t,e,i,s,r,n){var a=this,o=a.l;return a["xs"+o]+=n&&o?" "+t:t||"",i||0===o||a.plugin?(a.l++,a.type=a.setRatio?2:1,a["xs"+a.l]=s||"",o>0?(a.data["xn"+o]=e+i,a.rxp["xn"+o]=r,a["xn"+o]=e,a.plugin||(a.xfirst=new pe(a,"xn"+o,e,i,a.xfirst||a,0,a.n,r,a.pr),a.xfirst.xs0=0),a):(a.data={s:e+i},a.rxp={},a.s=e,a.c=i,a.r=r,a)):(a["xs"+o]+=e+(s||""),a)};var me=function(t,e){e=e||{},this.p=e.prefix?V(t)||t:t,o[t]=o[this.p]=this,this.format=e.formatter||le(e.defaultValue,e.color,e.collapsible,e.multi),e.parser&&(this.parse=e.parser),this.clrs=e.color,this.multi=e.multi,this.keyword=e.keyword,this.dflt=e.defaultValue,this.pr=e.priority||0},de=N._registerComplexSpecialProp=function(t,e,i){"object"!=typeof e&&(e={parser:i});var s,r,n=t.split(","),a=e.defaultValue;for(i=i||[a],s=0;n.length>s;s++)e.prefix=0===s&&e.prefix,e.defaultValue=i[s]||a,r=new me(n[s],e)},ge=function(t){if(!o[t]){var e=t.charAt(0).toUpperCase()+t.substr(1)+"Plugin";de(t,{parser:function(t,i,s,r,n,a,h){var l=(_gsScope.GreenSockGlobals||_gsScope).com.greensock.plugins[e];return l?(l._cssRegister(),o[s].parse(t,i,s,r,n,a,h)):(j("Error: "+e+" js file not loaded."),n)}})}};h=me.prototype,h.parseComplex=function(t,e,i,s,r,n){var a,o,h,l,_,u,p=this.keyword;if(this.multi&&(D.test(i)||D.test(e)?(o=e.replace(D,"|").split("|"),h=i.replace(D,"|").split("|")):p&&(o=[e],h=[i])),h){for(l=h.length>o.length?h.length:o.length,a=0;l>a;a++)e=o[a]=o[a]||this.dflt,i=h[a]=h[a]||this.dflt,p&&(_=e.indexOf(p),u=i.indexOf(p),_!==u&&(i=-1===u?h:o,i[a]+=" "+p));e=o.join(", "),i=h.join(", ")}return ce(t,this.p,e,i,this.clrs,this.dflt,s,this.pr,r,n)},h.parse=function(t,e,i,s,n,a){return this.parseComplex(t.style,this.format(W(t,this.p,r,!1,this.dflt)),this.format(e),n,a)},a.registerSpecialProp=function(t,e,i){de(t,{parser:function(t,s,r,n,a,o){var h=new pe(t,r,0,0,a,2,r,!1,i);return h.plugin=o,h.setRatio=e(t,s,n._tween,r),h},priority:i})};var ve="scaleX,scaleY,scaleZ,x,y,z,skewX,skewY,rotation,rotationX,rotationY,perspective,xPercent,yPercent".split(","),ye=V("transform"),Te=B+"transform",we=V("transformOrigin"),xe=null!==V("perspective"),be=N.Transform=function(){this.skewY=0},Pe=N.getTransform=function(t,e,i,s){if(t._gsTransform&&i&&!s)return t._gsTransform;var r,n,o,h,l,_,u,p,c,f,m,d,g,v=i?t._gsTransform||new be:new be,y=0>v.scaleX,T=2e-5,w=1e5,x=179.99,b=x*M,P=xe?parseFloat(W(t,we,e,!1,"0 0 0").split(" ")[2])||v.zOrigin||0:0;if(ye?r=W(t,Te,e,!0):t.currentStyle&&(r=t.currentStyle.filter.match(C),r=r&&4===r.length?[r[0].substr(4),Number(r[2].substr(4)),Number(r[1].substr(4)),r[3].substr(4),v.x||0,v.y||0].join(","):""),r&&"none"!==r&&"matrix(1, 0, 0, 1, 0, 0)"!==r){for(n=(r||"").match(/(?:\-|\b)[\d\-\.e]+\b/gi)||[],o=n.length;--o>-1;)h=Number(n[o]),n[o]=(l=h-(h|=0))?(0|l*w+(0>l?-.5:.5))/w+h:h;if(16===n.length){var S=n[8],k=n[9],R=n[10],A=n[12],O=n[13],D=n[14];if(v.zOrigin&&(D=-v.zOrigin,A=S*D-n[12],O=k*D-n[13],D=R*D+v.zOrigin-n[14]),!i||s||null==v.rotationX){var I,E,L,F,N,X,U,Y=n[0],j=n[1],B=n[2],q=n[3],V=n[4],G=n[5],Q=n[6],Z=n[7],$=n[11],H=Math.atan2(Q,R),K=-b>H||H>b;v.rotationX=H*z,H&&(F=Math.cos(-H),N=Math.sin(-H),I=V*F+S*N,E=G*F+k*N,L=Q*F+R*N,S=V*-N+S*F,k=G*-N+k*F,R=Q*-N+R*F,$=Z*-N+$*F,V=I,G=E,Q=L),H=Math.atan2(S,Y),v.rotationY=H*z,H&&(X=-b>H||H>b,F=Math.cos(-H),N=Math.sin(-H),I=Y*F-S*N,E=j*F-k*N,L=B*F-R*N,k=j*N+k*F,R=B*N+R*F,$=q*N+$*F,Y=I,j=E,B=L),H=Math.atan2(j,G),v.rotation=H*z,H&&(U=-b>H||H>b,F=Math.cos(-H),N=Math.sin(-H),Y=Y*F+V*N,E=j*F+G*N,G=j*-N+G*F,Q=B*-N+Q*F,j=E),U&&K?v.rotation=v.rotationX=0:U&&X?v.rotation=v.rotationY=0:X&&K&&(v.rotationY=v.rotationX=0),v.scaleX=(0|Math.sqrt(Y*Y+j*j)*w+.5)/w,v.scaleY=(0|Math.sqrt(G*G+k*k)*w+.5)/w,v.scaleZ=(0|Math.sqrt(Q*Q+R*R)*w+.5)/w,v.skewX=0,v.perspective=$?1/(0>$?-$:$):0,v.x=A,v.y=O,v.z=D}}else if(!(xe&&!s&&n.length&&v.x===n[4]&&v.y===n[5]&&(v.rotationX||v.rotationY)||void 0!==v.x&&"none"===W(t,"display",e))){var J=n.length>=6,te=J?n[0]:1,ee=n[1]||0,ie=n[2]||0,se=J?n[3]:1;v.x=n[4]||0,v.y=n[5]||0,_=Math.sqrt(te*te+ee*ee),u=Math.sqrt(se*se+ie*ie),p=te||ee?Math.atan2(ee,te)*z:v.rotation||0,c=ie||se?Math.atan2(ie,se)*z+p:v.skewX||0,f=_-Math.abs(v.scaleX||0),m=u-Math.abs(v.scaleY||0),Math.abs(c)>90&&270>Math.abs(c)&&(y?(_*=-1,c+=0>=p?180:-180,p+=0>=p?180:-180):(u*=-1,c+=0>=c?180:-180)),d=(p-v.rotation)%180,g=(c-v.skewX)%180,(void 0===v.skewX||f>T||-T>f||m>T||-T>m||d>-x&&x>d&&false|d*w||g>-x&&x>g&&false|g*w)&&(v.scaleX=_,v.scaleY=u,v.rotation=p,v.skewX=c),xe&&(v.rotationX=v.rotationY=v.z=0,v.perspective=parseFloat(a.defaultTransformPerspective)||0,v.scaleZ=1)}v.zOrigin=P;for(o in v)T>v[o]&&v[o]>-T&&(v[o]=0)}else v={x:0,y:0,z:0,scaleX:1,scaleY:1,scaleZ:1,skewX:0,perspective:0,rotation:0,rotationX:0,rotationY:0,zOrigin:0};return i&&(t._gsTransform=v),v.xPercent=v.yPercent=0,v},Se=function(t){var e,i,s=this.data,r=-s.rotation*M,n=r+s.skewX*M,a=1e5,o=(0|Math.cos(r)*s.scaleX*a)/a,h=(0|Math.sin(r)*s.scaleX*a)/a,l=(0|Math.sin(n)*-s.scaleY*a)/a,_=(0|Math.cos(n)*s.scaleY*a)/a,u=this.t.style,p=this.t.currentStyle;if(p){i=h,h=-l,l=-i,e=p.filter,u.filter="";var c,m,d=this.t.offsetWidth,g=this.t.offsetHeight,v="absolute"!==p.position,w="progid:DXImageTransform.Microsoft.Matrix(M11="+o+", M12="+h+", M21="+l+", M22="+_,x=s.x+d*s.xPercent/100,b=s.y+g*s.yPercent/100;if(null!=s.ox&&(c=(s.oxp?.01*d*s.ox:s.ox)-d/2,m=(s.oyp?.01*g*s.oy:s.oy)-g/2,x+=c-(c*o+m*h),b+=m-(c*l+m*_)),v?(c=d/2,m=g/2,w+=", Dx="+(c-(c*o+m*h)+x)+", Dy="+(m-(c*l+m*_)+b)+")"):w+=", sizingMethod='auto expand')",u.filter=-1!==e.indexOf("DXImageTransform.Microsoft.Matrix(")?e.replace(O,w):w+" "+e,(0===t||1===t)&&1===o&&0===h&&0===l&&1===_&&(v&&-1===w.indexOf("Dx=0, Dy=0")||T.test(e)&&100!==parseFloat(RegExp.$1)||-1===e.indexOf("gradient("&&e.indexOf("Alpha"))&&u.removeAttribute("filter")),!v){var P,S,k,R=8>f?1:-1;for(c=s.ieOffsetX||0,m=s.ieOffsetY||0,s.ieOffsetX=Math.round((d-((0>o?-o:o)*d+(0>h?-h:h)*g))/2+x),s.ieOffsetY=Math.round((g-((0>_?-_:_)*g+(0>l?-l:l)*d))/2+b),fe=0;4>fe;fe++)S=J[fe],P=p[S],i=-1!==P.indexOf("px")?parseFloat(P):Q(this.t,S,parseFloat(P),P.replace(y,""))||0,k=i!==s[S]?2>fe?-s.ieOffsetX:-s.ieOffsetY:2>fe?c-s.ieOffsetX:m-s.ieOffsetY,u[S]=(s[S]=Math.round(i-k*(0===fe||2===fe?1:R)))+"px"}}},ke=N.set3DTransformRatio=function(t){var e,i,s,r,n,a,o,h,l,_,u,c,f,m,d,g,v,y,T,w,x,b,P,S=this.data,k=this.t.style,R=S.rotation*M,A=S.scaleX,C=S.scaleY,O=S.scaleZ,D=S.x,z=S.y,I=S.z,E=S.perspective;if(!(1!==t&&0!==t||"auto"!==S.force3D||S.rotationY||S.rotationX||1!==O||E||I))return Re.call(this,t),void 0;if(p){var L=1e-4;L>A&&A>-L&&(A=O=2e-5),L>C&&C>-L&&(C=O=2e-5),!E||S.z||S.rotationX||S.rotationY||(E=0)}if(R||S.skewX)y=Math.cos(R),T=Math.sin(R),e=y,n=T,S.skewX&&(R-=S.skewX*M,y=Math.cos(R),T=Math.sin(R),"simple"===S.skewType&&(w=Math.tan(S.skewX*M),w=Math.sqrt(1+w*w),y*=w,T*=w)),i=-T,a=y;else{if(!(S.rotationY||S.rotationX||1!==O||E))return k[ye]=(S.xPercent||S.yPercent?"translate("+S.xPercent+"%,"+S.yPercent+"%) translate3d(":"translate3d(")+D+"px,"+z+"px,"+I+"px)"+(1!==A||1!==C?" scale("+A+","+C+")":""),void 0;e=a=1,i=n=0}u=1,s=r=o=h=l=_=c=f=m=0,d=E?-1/E:0,g=S.zOrigin,v=1e5,R=S.rotationY*M,R&&(y=Math.cos(R),T=Math.sin(R),l=u*-T,f=d*-T,s=e*T,o=n*T,u*=y,d*=y,e*=y,n*=y),R=S.rotationX*M,R&&(y=Math.cos(R),T=Math.sin(R),w=i*y+s*T,x=a*y+o*T,b=_*y+u*T,P=m*y+d*T,s=i*-T+s*y,o=a*-T+o*y,u=_*-T+u*y,d=m*-T+d*y,i=w,a=x,_=b,m=P),1!==O&&(s*=O,o*=O,u*=O,d*=O),1!==C&&(i*=C,a*=C,_*=C,m*=C),1!==A&&(e*=A,n*=A,l*=A,f*=A),g&&(c-=g,r=s*c,h=o*c,c=u*c+g),r=(w=(r+=D)-(r|=0))?(0|w*v+(0>w?-.5:.5))/v+r:r,h=(w=(h+=z)-(h|=0))?(0|w*v+(0>w?-.5:.5))/v+h:h,c=(w=(c+=I)-(c|=0))?(0|w*v+(0>w?-.5:.5))/v+c:c,k[ye]=(S.xPercent||S.yPercent?"translate("+S.xPercent+"%,"+S.yPercent+"%) matrix3d(":"matrix3d(")+[(0|e*v)/v,(0|n*v)/v,(0|l*v)/v,(0|f*v)/v,(0|i*v)/v,(0|a*v)/v,(0|_*v)/v,(0|m*v)/v,(0|s*v)/v,(0|o*v)/v,(0|u*v)/v,(0|d*v)/v,r,h,c,E?1+-c/E:1].join(",")+")"},Re=N.set2DTransformRatio=function(t){var e,i,s,r,n,a=this.data,o=this.t,h=o.style,l=a.x,_=a.y;return a.rotationX||a.rotationY||a.z||a.force3D===!0||"auto"===a.force3D&&1!==t&&0!==t?(this.setRatio=ke,ke.call(this,t),void 0):(a.rotation||a.skewX?(e=a.rotation*M,i=e-a.skewX*M,s=1e5,r=a.scaleX*s,n=a.scaleY*s,h[ye]=(a.xPercent||a.yPercent?"translate("+a.xPercent+"%,"+a.yPercent+"%) matrix(":"matrix(")+(0|Math.cos(e)*r)/s+","+(0|Math.sin(e)*r)/s+","+(0|Math.sin(i)*-n)/s+","+(0|Math.cos(i)*n)/s+","+l+","+_+")"):h[ye]=(a.xPercent||a.yPercent?"translate("+a.xPercent+"%,"+a.yPercent+"%) matrix(":"matrix(")+a.scaleX+",0,0,"+a.scaleY+","+l+","+_+")",void 0)};de("transform,scale,scaleX,scaleY,scaleZ,x,y,z,rotation,rotationX,rotationY,rotationZ,skewX,skewY,shortRotation,shortRotationX,shortRotationY,shortRotationZ,transformOrigin,transformPerspective,directionalRotation,parseTransform,force3D,skewType,xPercent,yPercent",{parser:function(t,e,i,s,n,o,h){if(s._transform)return n;var l,_,u,p,c,f,m,d=s._transform=Pe(t,r,!0,h.parseTransform),g=t.style,v=1e-6,y=ve.length,T=h,w={};if("string"==typeof T.transform&&ye)u=L.style,u[ye]=T.transform,u.display="block",u.position="absolute",E.body.appendChild(L),l=Pe(L,null,!1),E.body.removeChild(L);else if("object"==typeof T){if(l={scaleX:se(null!=T.scaleX?T.scaleX:T.scale,d.scaleX),scaleY:se(null!=T.scaleY?T.scaleY:T.scale,d.scaleY),scaleZ:se(T.scaleZ,d.scaleZ),x:se(T.x,d.x),y:se(T.y,d.y),z:se(T.z,d.z),xPercent:se(T.xPercent,d.xPercent),yPercent:se(T.yPercent,d.yPercent),perspective:se(T.transformPerspective,d.perspective)},m=T.directionalRotation,null!=m)if("object"==typeof m)for(u in m)T[u]=m[u];else T.rotation=m;"string"==typeof T.x&&-1!==T.x.indexOf("%")&&(l.x=0,l.xPercent=se(T.x,d.xPercent)),"string"==typeof T.y&&-1!==T.y.indexOf("%")&&(l.y=0,l.yPercent=se(T.y,d.yPercent)),l.rotation=re("rotation"in T?T.rotation:"shortRotation"in T?T.shortRotation+"_short":"rotationZ"in T?T.rotationZ:d.rotation,d.rotation,"rotation",w),xe&&(l.rotationX=re("rotationX"in T?T.rotationX:"shortRotationX"in T?T.shortRotationX+"_short":d.rotationX||0,d.rotationX,"rotationX",w),l.rotationY=re("rotationY"in T?T.rotationY:"shortRotationY"in T?T.shortRotationY+"_short":d.rotationY||0,d.rotationY,"rotationY",w)),l.skewX=null==T.skewX?d.skewX:re(T.skewX,d.skewX),l.skewY=null==T.skewY?d.skewY:re(T.skewY,d.skewY),(_=l.skewY-d.skewY)&&(l.skewX+=_,l.rotation+=_)}for(xe&&null!=T.force3D&&(d.force3D=T.force3D,f=!0),d.skewType=T.skewType||d.skewType||a.defaultSkewType,c=d.force3D||d.z||d.rotationX||d.rotationY||l.z||l.rotationX||l.rotationY||l.perspective,c||null==T.scale||(l.scaleZ=1);--y>-1;)i=ve[y],p=l[i]-d[i],(p>v||-v>p||null!=I[i])&&(f=!0,n=new pe(d,i,d[i],p,n),i in w&&(n.e=w[i]),n.xs0=0,n.plugin=o,s._overwriteProps.push(n.n));return p=T.transformOrigin,(p||xe&&c&&d.zOrigin)&&(ye?(f=!0,i=we,p=(p||W(t,i,r,!1,"50% 50%"))+"",n=new pe(g,i,0,0,n,-1,"transformOrigin"),n.b=g[i],n.plugin=o,xe?(u=d.zOrigin,p=p.split(" "),d.zOrigin=(p.length>2&&(0===u||"0px"!==p[2])?parseFloat(p[2]):u)||0,n.xs0=n.e=p[0]+" "+(p[1]||"50%")+" 0px",n=new pe(d,"zOrigin",0,0,n,-1,n.n),n.b=u,n.xs0=n.e=d.zOrigin):n.xs0=n.e=p):ee(p+"",d)),f&&(s._transformType=c||3===this._transformType?3:2),n},prefix:!0}),de("boxShadow",{defaultValue:"0px 0px 0px 0px #999",prefix:!0,color:!0,multi:!0,keyword:"inset"}),de("borderRadius",{defaultValue:"0px",parser:function(t,e,i,n,a){e=this.format(e);var o,h,l,_,u,p,c,f,m,d,g,v,y,T,w,x,b=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"],P=t.style;for(m=parseFloat(t.offsetWidth),d=parseFloat(t.offsetHeight),o=e.split(" "),h=0;b.length>h;h++)this.p.indexOf("border")&&(b[h]=V(b[h])),u=_=W(t,b[h],r,!1,"0px"),-1!==u.indexOf(" ")&&(_=u.split(" "),u=_[0],_=_[1]),p=l=o[h],c=parseFloat(u),v=u.substr((c+"").length),y="="===p.charAt(1),y?(f=parseInt(p.charAt(0)+"1",10),p=p.substr(2),f*=parseFloat(p),g=p.substr((f+"").length-(0>f?1:0))||""):(f=parseFloat(p),g=p.substr((f+"").length)),""===g&&(g=s[i]||v),g!==v&&(T=Q(t,"borderLeft",c,v),w=Q(t,"borderTop",c,v),"%"===g?(u=100*(T/m)+"%",_=100*(w/d)+"%"):"em"===g?(x=Q(t,"borderLeft",1,"em"),u=T/x+"em",_=w/x+"em"):(u=T+"px",_=w+"px"),y&&(p=parseFloat(u)+f+g,l=parseFloat(_)+f+g)),a=ce(P,b[h],u+" "+_,p+" "+l,!1,"0px",a);return a},prefix:!0,formatter:le("0px 0px 0px 0px",!1,!0)}),de("backgroundPosition",{defaultValue:"0 0",parser:function(t,e,i,s,n,a){var o,h,l,_,u,p,c="background-position",m=r||G(t,null),d=this.format((m?f?m.getPropertyValue(c+"-x")+" "+m.getPropertyValue(c+"-y"):m.getPropertyValue(c):t.currentStyle.backgroundPositionX+" "+t.currentStyle.backgroundPositionY)||"0 0"),g=this.format(e);if(-1!==d.indexOf("%")!=(-1!==g.indexOf("%"))&&(p=W(t,"backgroundImage").replace(k,""),p&&"none"!==p)){for(o=d.split(" "),h=g.split(" "),F.setAttribute("src",p),l=2;--l>-1;)d=o[l],_=-1!==d.indexOf("%"),_!==(-1!==h[l].indexOf("%"))&&(u=0===l?t.offsetWidth-F.width:t.offsetHeight-F.height,o[l]=_?parseFloat(d)/100*u+"px":100*(parseFloat(d)/u)+"%");d=o.join(" ")}return this.parseComplex(t.style,d,g,n,a)},formatter:ee}),de("backgroundSize",{defaultValue:"0 0",formatter:ee}),de("perspective",{defaultValue:"0px",prefix:!0}),de("perspectiveOrigin",{defaultValue:"50% 50%",prefix:!0}),de("transformStyle",{prefix:!0}),de("backfaceVisibility",{prefix:!0}),de("userSelect",{prefix:!0}),de("margin",{parser:_e("marginTop,marginRight,marginBottom,marginLeft")}),de("padding",{parser:_e("paddingTop,paddingRight,paddingBottom,paddingLeft")}),de("clip",{defaultValue:"rect(0px,0px,0px,0px)",parser:function(t,e,i,s,n,a){var o,h,l;return 9>f?(h=t.currentStyle,l=8>f?" ":",",o="rect("+h.clipTop+l+h.clipRight+l+h.clipBottom+l+h.clipLeft+")",e=this.format(e).split(",").join(l)):(o=this.format(W(t,this.p,r,!1,this.dflt)),e=this.format(e)),this.parseComplex(t.style,o,e,n,a)}}),de("textShadow",{defaultValue:"0px 0px 0px #999",color:!0,multi:!0}),de("autoRound,strictUnits",{parser:function(t,e,i,s,r){return r}}),de("border",{defaultValue:"0px solid #000",parser:function(t,e,i,s,n,a){return this.parseComplex(t.style,this.format(W(t,"borderTopWidth",r,!1,"0px")+" "+W(t,"borderTopStyle",r,!1,"solid")+" "+W(t,"borderTopColor",r,!1,"#000")),this.format(e),n,a)},color:!0,formatter:function(t){var e=t.split(" ");return e[0]+" "+(e[1]||"solid")+" "+(t.match(he)||["#000"])[0]}}),de("borderWidth",{parser:_e("borderTopWidth,borderRightWidth,borderBottomWidth,borderLeftWidth")}),de("float,cssFloat,styleFloat",{parser:function(t,e,i,s,r){var n=t.style,a="cssFloat"in n?"cssFloat":"styleFloat";return new pe(n,a,0,0,r,-1,i,!1,0,n[a],e)}});var Ae=function(t){var e,i=this.t,s=i.filter||W(this.data,"filter"),r=0|this.s+this.c*t;100===r&&(-1===s.indexOf("atrix(")&&-1===s.indexOf("radient(")&&-1===s.indexOf("oader(")?(i.removeAttribute("filter"),e=!W(this.data,"filter")):(i.filter=s.replace(x,""),e=!0)),e||(this.xn1&&(i.filter=s=s||"alpha(opacity="+r+")"),-1===s.indexOf("pacity")?0===r&&this.xn1||(i.filter=s+" alpha(opacity="+r+")"):i.filter=s.replace(T,"opacity="+r))};de("opacity,alpha,autoAlpha",{defaultValue:"1",parser:function(t,e,i,s,n,a){var o=parseFloat(W(t,"opacity",r,!1,"1")),h=t.style,l="autoAlpha"===i;return"string"==typeof e&&"="===e.charAt(1)&&(e=("-"===e.charAt(0)?-1:1)*parseFloat(e.substr(2))+o),l&&1===o&&"hidden"===W(t,"visibility",r)&&0!==e&&(o=0),U?n=new pe(h,"opacity",o,e-o,n):(n=new pe(h,"opacity",100*o,100*(e-o),n),n.xn1=l?1:0,h.zoom=1,n.type=2,n.b="alpha(opacity="+n.s+")",n.e="alpha(opacity="+(n.s+n.c)+")",n.data=t,n.plugin=a,n.setRatio=Ae),l&&(n=new pe(h,"visibility",0,0,n,-1,null,!1,0,0!==o?"inherit":"hidden",0===e?"hidden":"inherit"),n.xs0="inherit",s._overwriteProps.push(n.n),s._overwriteProps.push(i)),n}});var Ce=function(t,e){e&&(t.removeProperty?("ms"===e.substr(0,2)&&(e="M"+e.substr(1)),t.removeProperty(e.replace(P,"-$1").toLowerCase())):t.removeAttribute(e))},Oe=function(t){if(this.t._gsClassPT=this,1===t||0===t){this.t.setAttribute("class",0===t?this.b:this.e);for(var e=this.data,i=this.t.style;e;)e.v?i[e.p]=e.v:Ce(i,e.p),e=e._next;1===t&&this.t._gsClassPT===this&&(this.t._gsClassPT=null)}else this.t.getAttribute("class")!==this.e&&this.t.setAttribute("class",this.e)};de("className",{parser:function(t,e,s,n,a,o,h){var l,_,u,p,c,f=t.getAttribute("class")||"",m=t.style.cssText;if(a=n._classNamePT=new pe(t,s,0,0,a,2),a.setRatio=Oe,a.pr=-11,i=!0,a.b=f,_=$(t,r),u=t._gsClassPT){for(p={},c=u.data;c;)p[c.p]=1,c=c._next;u.setRatio(1)}return t._gsClassPT=a,a.e="="!==e.charAt(1)?e:f.replace(RegExp("\\s*\\b"+e.substr(2)+"\\b"),"")+("+"===e.charAt(0)?" "+e.substr(2):""),n._tween._duration&&(t.setAttribute("class",a.e),l=H(t,_,$(t),h,p),t.setAttribute("class",f),a.data=l.firstMPT,t.style.cssText=m,a=a.xfirst=n.parse(t,l.difs,a,o)),a}});var De=function(t){if((1===t||0===t)&&this.data._totalTime===this.data._totalDuration&&"isFromStart"!==this.data.data){var e,i,s,r,n=this.t.style,a=o.transform.parse;if("all"===this.e)n.cssText="",r=!0;else for(e=this.e.split(","),s=e.length;--s>-1;)i=e[s],o[i]&&(o[i].parse===a?r=!0:i="transformOrigin"===i?we:o[i].p),Ce(n,i);r&&(Ce(n,ye),this.t._gsTransform&&delete this.t._gsTransform)}};for(de("clearProps",{parser:function(t,e,s,r,n){return n=new pe(t,s,0,0,n,2),n.setRatio=De,n.e=e,n.pr=-10,n.data=r._tween,i=!0,n}}),h="bezier,throwProps,physicsProps,physics2D".split(","),fe=h.length;fe--;)ge(h[fe]);h=a.prototype,h._firstPT=null,h._onInitTween=function(t,e,o){if(!t.nodeType)return!1;this._target=t,this._tween=o,this._vars=e,l=e.autoRound,i=!1,s=e.suffixMap||a.suffixMap,r=G(t,""),n=this._overwriteProps;var h,p,f,m,d,g,v,y,T,x=t.style;if(_&&""===x.zIndex&&(h=W(t,"zIndex",r),("auto"===h||""===h)&&this._addLazySet(x,"zIndex",0)),"string"==typeof e&&(m=x.cssText,h=$(t,r),x.cssText=m+";"+e,h=H(t,h,$(t)).difs,!U&&w.test(e)&&(h.opacity=parseFloat(RegExp.$1)),e=h,x.cssText=m),this._firstPT=p=this.parse(t,e,null),this._transformType){for(T=3===this._transformType,ye?u&&(_=!0,""===x.zIndex&&(v=W(t,"zIndex",r),("auto"===v||""===v)&&this._addLazySet(x,"zIndex",0)),c&&this._addLazySet(x,"WebkitBackfaceVisibility",this._vars.WebkitBackfaceVisibility||(T?"visible":"hidden"))):x.zoom=1,f=p;f&&f._next;)f=f._next;y=new pe(t,"transform",0,0,null,2),this._linkCSSP(y,null,f),y.setRatio=T&&xe?ke:ye?Re:Se,y.data=this._transform||Pe(t,r,!0),n.pop()}if(i){for(;p;){for(g=p._next,f=m;f&&f.pr>p.pr;)f=f._next;(p._prev=f?f._prev:d)?p._prev._next=p:m=p,(p._next=f)?f._prev=p:d=p,p=g}this._firstPT=m}return!0},h.parse=function(t,e,i,n){var a,h,_,u,p,c,f,m,d,g,v=t.style;for(a in e)c=e[a],h=o[a],h?i=h.parse(t,c,a,this,i,n,e):(p=W(t,a,r)+"",d="string"==typeof c,"color"===a||"fill"===a||"stroke"===a||-1!==a.indexOf("Color")||d&&b.test(c)?(d||(c=oe(c),c=(c.length>3?"rgba(":"rgb(")+c.join(",")+")"),i=ce(v,a,p,c,!0,"transparent",i,0,n)):!d||-1===c.indexOf(" ")&&-1===c.indexOf(",")?(_=parseFloat(p),f=_||0===_?p.substr((_+"").length):"",(""===p||"auto"===p)&&("width"===a||"height"===a?(_=te(t,a,r),f="px"):"left"===a||"top"===a?(_=Z(t,a,r),f="px"):(_="opacity"!==a?0:1,f="")),g=d&&"="===c.charAt(1),g?(u=parseInt(c.charAt(0)+"1",10),c=c.substr(2),u*=parseFloat(c),m=c.replace(y,"")):(u=parseFloat(c),m=d?c.substr((u+"").length)||"":""),""===m&&(m=a in s?s[a]:f),c=u||0===u?(g?u+_:u)+m:e[a],f!==m&&""!==m&&(u||0===u)&&_&&(_=Q(t,a,_,f),"%"===m?(_/=Q(t,a,100,"%")/100,e.strictUnits!==!0&&(p=_+"%")):"em"===m?_/=Q(t,a,1,"em"):"px"!==m&&(u=Q(t,a,u,m),m="px"),g&&(u||0===u)&&(c=u+_+m)),g&&(u+=_),!_&&0!==_||!u&&0!==u?void 0!==v[a]&&(c||"NaN"!=c+""&&null!=c)?(i=new pe(v,a,u||_||0,0,i,-1,a,!1,0,p,c),i.xs0="none"!==c||"display"!==a&&-1===a.indexOf("Style")?c:p):j("invalid "+a+" tween value: "+e[a]):(i=new pe(v,a,_,u-_,i,0,a,l!==!1&&("px"===m||"zIndex"===a),0,p,c),i.xs0=m)):i=ce(v,a,p,c,!0,null,i,0,n)),n&&i&&!i.plugin&&(i.plugin=n);
return i},h.setRatio=function(t){var e,i,s,r=this._firstPT,n=1e-6;if(1!==t||this._tween._time!==this._tween._duration&&0!==this._tween._time)if(t||this._tween._time!==this._tween._duration&&0!==this._tween._time||this._tween._rawPrevTime===-1e-6)for(;r;){if(e=r.c*t+r.s,r.r?e=Math.round(e):n>e&&e>-n&&(e=0),r.type)if(1===r.type)if(s=r.l,2===s)r.t[r.p]=r.xs0+e+r.xs1+r.xn1+r.xs2;else if(3===s)r.t[r.p]=r.xs0+e+r.xs1+r.xn1+r.xs2+r.xn2+r.xs3;else if(4===s)r.t[r.p]=r.xs0+e+r.xs1+r.xn1+r.xs2+r.xn2+r.xs3+r.xn3+r.xs4;else if(5===s)r.t[r.p]=r.xs0+e+r.xs1+r.xn1+r.xs2+r.xn2+r.xs3+r.xn3+r.xs4+r.xn4+r.xs5;else{for(i=r.xs0+e+r.xs1,s=1;r.l>s;s++)i+=r["xn"+s]+r["xs"+(s+1)];r.t[r.p]=i}else-1===r.type?r.t[r.p]=r.xs0:r.setRatio&&r.setRatio(t);else r.t[r.p]=e+r.xs0;r=r._next}else for(;r;)2!==r.type?r.t[r.p]=r.b:r.setRatio(t),r=r._next;else for(;r;)2!==r.type?r.t[r.p]=r.e:r.setRatio(t),r=r._next},h._enableTransforms=function(t){this._transformType=t||3===this._transformType?3:2,this._transform=this._transform||Pe(this._target,r,!0)};var Me=function(){this.t[this.p]=this.e,this.data._linkCSSP(this,this._next,null,!0)};h._addLazySet=function(t,e,i){var s=this._firstPT=new pe(t,e,0,0,this._firstPT,2);s.e=i,s.setRatio=Me,s.data=this},h._linkCSSP=function(t,e,i,s){return t&&(e&&(e._prev=t),t._next&&(t._next._prev=t._prev),t._prev?t._prev._next=t._next:this._firstPT===t&&(this._firstPT=t._next,s=!0),i?i._next=t:s||null!==this._firstPT||(this._firstPT=t),t._next=e,t._prev=i),t},h._kill=function(e){var i,s,r,n=e;if(e.autoAlpha||e.alpha){n={};for(s in e)n[s]=e[s];n.opacity=1,n.autoAlpha&&(n.visibility=1)}return e.className&&(i=this._classNamePT)&&(r=i.xfirst,r&&r._prev?this._linkCSSP(r._prev,i._next,r._prev._prev):r===this._firstPT&&(this._firstPT=i._next),i._next&&this._linkCSSP(i._next,i._next._next,r._prev),this._classNamePT=null),t.prototype._kill.call(this,n)};var ze=function(t,e,i){var s,r,n,a;if(t.slice)for(r=t.length;--r>-1;)ze(t[r],e,i);else for(s=t.childNodes,r=s.length;--r>-1;)n=s[r],a=n.type,n.style&&(e.push($(n)),i&&i.push(n)),1!==a&&9!==a&&11!==a||!n.childNodes.length||ze(n,e,i)};return a.cascadeTo=function(t,i,s){var r,n,a,o=e.to(t,i,s),h=[o],l=[],_=[],u=[],p=e._internals.reservedProps;for(t=o._targets||o.target,ze(t,l,u),o.render(i,!0),ze(t,_),o.render(0,!0),o._enabled(!0),r=u.length;--r>-1;)if(n=H(u[r],l[r],_[r]),n.firstMPT){n=n.difs;for(a in s)p[a]&&(n[a]=s[a]);h.push(e.to(u[r],i,n))}return h},t.activate([a]),a},!0),function(){var t=_gsScope._gsDefine.plugin({propName:"roundProps",priority:-1,API:2,init:function(t,e,i){return this._tween=i,!0}}),e=t.prototype;e._onInitAllProps=function(){for(var t,e,i,s=this._tween,r=s.vars.roundProps instanceof Array?s.vars.roundProps:s.vars.roundProps.split(","),n=r.length,a={},o=s._propLookup.roundProps;--n>-1;)a[r[n]]=1;for(n=r.length;--n>-1;)for(t=r[n],e=s._firstPT;e;)i=e._next,e.pg?e.t._roundProps(a,!0):e.n===t&&(this._add(e.t,t,e.s,e.c),i&&(i._prev=e._prev),e._prev?e._prev._next=i:s._firstPT===e&&(s._firstPT=i),e._next=e._prev=null,s._propLookup[t]=o),e=i;return!1},e._add=function(t,e,i,s){this._addTween(t,e,i,i+s,e,!0),this._overwriteProps.push(e)}}(),_gsScope._gsDefine.plugin({propName:"attr",API:2,version:"0.3.3",init:function(t,e){var i,s,r;if("function"!=typeof t.setAttribute)return!1;this._target=t,this._proxy={},this._start={},this._end={};for(i in e)this._start[i]=this._proxy[i]=s=t.getAttribute(i),r=this._addTween(this._proxy,i,parseFloat(s),e[i],i),this._end[i]=r?r.s+r.c:e[i],this._overwriteProps.push(i);return!0},set:function(t){this._super.setRatio.call(this,t);for(var e,i=this._overwriteProps,s=i.length,r=1===t?this._end:t?this._proxy:this._start;--s>-1;)e=i[s],this._target.setAttribute(e,r[e]+"")}}),_gsScope._gsDefine.plugin({propName:"directionalRotation",version:"0.2.1",API:2,init:function(t,e){"object"!=typeof e&&(e={rotation:e}),this.finals={};var i,s,r,n,a,o,h=e.useRadians===!0?2*Math.PI:360,l=1e-6;for(i in e)"useRadians"!==i&&(o=(e[i]+"").split("_"),s=o[0],r=parseFloat("function"!=typeof t[i]?t[i]:t[i.indexOf("set")||"function"!=typeof t["get"+i.substr(3)]?i:"get"+i.substr(3)]()),n=this.finals[i]="string"==typeof s&&"="===s.charAt(1)?r+parseInt(s.charAt(0)+"1",10)*Number(s.substr(2)):Number(s)||0,a=n-r,o.length&&(s=o.join("_"),-1!==s.indexOf("short")&&(a%=h,a!==a%(h/2)&&(a=0>a?a+h:a-h)),-1!==s.indexOf("_cw")&&0>a?a=(a+9999999999*h)%h-(0|a/h)*h:-1!==s.indexOf("ccw")&&a>0&&(a=(a-9999999999*h)%h-(0|a/h)*h)),(a>l||-l>a)&&(this._addTween(t,i,r,r+a,i),this._overwriteProps.push(i)));return!0},set:function(t){var e;if(1!==t)this._super.setRatio.call(this,t);else for(e=this._firstPT;e;)e.f?e.t[e.p](this.finals[e.p]):e.t[e.p]=this.finals[e.p],e=e._next}})._autoCSS=!0,_gsScope._gsDefine("easing.Back",["easing.Ease"],function(t){var e,i,s,r=_gsScope.GreenSockGlobals||_gsScope,n=r.com.greensock,a=2*Math.PI,o=Math.PI/2,h=n._class,l=function(e,i){var s=h("easing."+e,function(){},!0),r=s.prototype=new t;return r.constructor=s,r.getRatio=i,s},_=t.register||function(){},u=function(t,e,i,s){var r=h("easing."+t,{easeOut:new e,easeIn:new i,easeInOut:new s},!0);return _(r,t),r},p=function(t,e,i){this.t=t,this.v=e,i&&(this.next=i,i.prev=this,this.c=i.v-e,this.gap=i.t-t)},c=function(e,i){var s=h("easing."+e,function(t){this._p1=t||0===t?t:1.70158,this._p2=1.525*this._p1},!0),r=s.prototype=new t;return r.constructor=s,r.getRatio=i,r.config=function(t){return new s(t)},s},f=u("Back",c("BackOut",function(t){return(t-=1)*t*((this._p1+1)*t+this._p1)+1}),c("BackIn",function(t){return t*t*((this._p1+1)*t-this._p1)}),c("BackInOut",function(t){return 1>(t*=2)?.5*t*t*((this._p2+1)*t-this._p2):.5*((t-=2)*t*((this._p2+1)*t+this._p2)+2)})),m=h("easing.SlowMo",function(t,e,i){e=e||0===e?e:.7,null==t?t=.7:t>1&&(t=1),this._p=1!==t?e:0,this._p1=(1-t)/2,this._p2=t,this._p3=this._p1+this._p2,this._calcEnd=i===!0},!0),d=m.prototype=new t;return d.constructor=m,d.getRatio=function(t){var e=t+(.5-t)*this._p;return this._p1>t?this._calcEnd?1-(t=1-t/this._p1)*t:e-(t=1-t/this._p1)*t*t*t*e:t>this._p3?this._calcEnd?1-(t=(t-this._p3)/this._p1)*t:e+(t-e)*(t=(t-this._p3)/this._p1)*t*t*t:this._calcEnd?1:e},m.ease=new m(.7,.7),d.config=m.config=function(t,e,i){return new m(t,e,i)},e=h("easing.SteppedEase",function(t){t=t||1,this._p1=1/t,this._p2=t+1},!0),d=e.prototype=new t,d.constructor=e,d.getRatio=function(t){return 0>t?t=0:t>=1&&(t=.999999999),(this._p2*t>>0)*this._p1},d.config=e.config=function(t){return new e(t)},i=h("easing.RoughEase",function(e){e=e||{};for(var i,s,r,n,a,o,h=e.taper||"none",l=[],_=0,u=0|(e.points||20),c=u,f=e.randomize!==!1,m=e.clamp===!0,d=e.template instanceof t?e.template:null,g="number"==typeof e.strength?.4*e.strength:.4;--c>-1;)i=f?Math.random():1/u*c,s=d?d.getRatio(i):i,"none"===h?r=g:"out"===h?(n=1-i,r=n*n*g):"in"===h?r=i*i*g:.5>i?(n=2*i,r=.5*n*n*g):(n=2*(1-i),r=.5*n*n*g),f?s+=Math.random()*r-.5*r:c%2?s+=.5*r:s-=.5*r,m&&(s>1?s=1:0>s&&(s=0)),l[_++]={x:i,y:s};for(l.sort(function(t,e){return t.x-e.x}),o=new p(1,1,null),c=u;--c>-1;)a=l[c],o=new p(a.x,a.y,o);this._prev=new p(0,0,0!==o.t?o:o.next)},!0),d=i.prototype=new t,d.constructor=i,d.getRatio=function(t){var e=this._prev;if(t>e.t){for(;e.next&&t>=e.t;)e=e.next;e=e.prev}else for(;e.prev&&e.t>=t;)e=e.prev;return this._prev=e,e.v+(t-e.t)/e.gap*e.c},d.config=function(t){return new i(t)},i.ease=new i,u("Bounce",l("BounceOut",function(t){return 1/2.75>t?7.5625*t*t:2/2.75>t?7.5625*(t-=1.5/2.75)*t+.75:2.5/2.75>t?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375}),l("BounceIn",function(t){return 1/2.75>(t=1-t)?1-7.5625*t*t:2/2.75>t?1-(7.5625*(t-=1.5/2.75)*t+.75):2.5/2.75>t?1-(7.5625*(t-=2.25/2.75)*t+.9375):1-(7.5625*(t-=2.625/2.75)*t+.984375)}),l("BounceInOut",function(t){var e=.5>t;return t=e?1-2*t:2*t-1,t=1/2.75>t?7.5625*t*t:2/2.75>t?7.5625*(t-=1.5/2.75)*t+.75:2.5/2.75>t?7.5625*(t-=2.25/2.75)*t+.9375:7.5625*(t-=2.625/2.75)*t+.984375,e?.5*(1-t):.5*t+.5})),u("Circ",l("CircOut",function(t){return Math.sqrt(1-(t-=1)*t)}),l("CircIn",function(t){return-(Math.sqrt(1-t*t)-1)}),l("CircInOut",function(t){return 1>(t*=2)?-.5*(Math.sqrt(1-t*t)-1):.5*(Math.sqrt(1-(t-=2)*t)+1)})),s=function(e,i,s){var r=h("easing."+e,function(t,e){this._p1=t||1,this._p2=e||s,this._p3=this._p2/a*(Math.asin(1/this._p1)||0)},!0),n=r.prototype=new t;return n.constructor=r,n.getRatio=i,n.config=function(t,e){return new r(t,e)},r},u("Elastic",s("ElasticOut",function(t){return this._p1*Math.pow(2,-10*t)*Math.sin((t-this._p3)*a/this._p2)+1},.3),s("ElasticIn",function(t){return-(this._p1*Math.pow(2,10*(t-=1))*Math.sin((t-this._p3)*a/this._p2))},.3),s("ElasticInOut",function(t){return 1>(t*=2)?-.5*this._p1*Math.pow(2,10*(t-=1))*Math.sin((t-this._p3)*a/this._p2):.5*this._p1*Math.pow(2,-10*(t-=1))*Math.sin((t-this._p3)*a/this._p2)+1},.45)),u("Expo",l("ExpoOut",function(t){return 1-Math.pow(2,-10*t)}),l("ExpoIn",function(t){return Math.pow(2,10*(t-1))-.001}),l("ExpoInOut",function(t){return 1>(t*=2)?.5*Math.pow(2,10*(t-1)):.5*(2-Math.pow(2,-10*(t-1)))})),u("Sine",l("SineOut",function(t){return Math.sin(t*o)}),l("SineIn",function(t){return-Math.cos(t*o)+1}),l("SineInOut",function(t){return-.5*(Math.cos(Math.PI*t)-1)})),h("easing.EaseLookup",{find:function(e){return t.map[e]}},!0),_(r.SlowMo,"SlowMo","ease,"),_(i,"RoughEase","ease,"),_(e,"SteppedEase","ease,"),f},!0)}),_gsScope._gsDefine&&_gsScope._gsQueue.pop()(),function(t,e){"use strict";var i=t.GreenSockGlobals=t.GreenSockGlobals||t;if(!i.TweenLite){var s,r,n,a,o,h=function(t){var e,s=t.split("."),r=i;for(e=0;s.length>e;e++)r[s[e]]=r=r[s[e]]||{};return r},l=h("com.greensock"),_=1e-10,u=function(t){var e,i=[],s=t.length;for(e=0;e!==s;i.push(t[e++]));return i},p=function(){},c=function(){var t=Object.prototype.toString,e=t.call([]);return function(i){return null!=i&&(i instanceof Array||"object"==typeof i&&!!i.push&&t.call(i)===e)}}(),f={},m=function(s,r,n,a){this.sc=f[s]?f[s].sc:[],f[s]=this,this.gsClass=null,this.func=n;var o=[];this.check=function(l){for(var _,u,p,c,d=r.length,g=d;--d>-1;)(_=f[r[d]]||new m(r[d],[])).gsClass?(o[d]=_.gsClass,g--):l&&_.sc.push(this);if(0===g&&n)for(u=("com.greensock."+s).split("."),p=u.pop(),c=h(u.join("."))[p]=this.gsClass=n.apply(n,o),a&&(i[p]=c,"function"==typeof define&&define.amd?define((t.GreenSockAMDPath?t.GreenSockAMDPath+"/":"")+s.split(".").pop(),[],function(){return c}):s===e&&"undefined"!=typeof module&&module.exports&&(module.exports=c)),d=0;this.sc.length>d;d++)this.sc[d].check()},this.check(!0)},d=t._gsDefine=function(t,e,i,s){return new m(t,e,i,s)},g=l._class=function(t,e,i){return e=e||function(){},d(t,[],function(){return e},i),e};d.globals=i;var v=[0,0,1,1],y=[],T=g("easing.Ease",function(t,e,i,s){this._func=t,this._type=i||0,this._power=s||0,this._params=e?v.concat(e):v},!0),w=T.map={},x=T.register=function(t,e,i,s){for(var r,n,a,o,h=e.split(","),_=h.length,u=(i||"easeIn,easeOut,easeInOut").split(",");--_>-1;)for(n=h[_],r=s?g("easing."+n,null,!0):l.easing[n]||{},a=u.length;--a>-1;)o=u[a],w[n+"."+o]=w[o+n]=r[o]=t.getRatio?t:t[o]||new t};for(n=T.prototype,n._calcEnd=!1,n.getRatio=function(t){if(this._func)return this._params[0]=t,this._func.apply(null,this._params);var e=this._type,i=this._power,s=1===e?1-t:2===e?t:.5>t?2*t:2*(1-t);return 1===i?s*=s:2===i?s*=s*s:3===i?s*=s*s*s:4===i&&(s*=s*s*s*s),1===e?1-s:2===e?s:.5>t?s/2:1-s/2},s=["Linear","Quad","Cubic","Quart","Quint,Strong"],r=s.length;--r>-1;)n=s[r]+",Power"+r,x(new T(null,null,1,r),n,"easeOut",!0),x(new T(null,null,2,r),n,"easeIn"+(0===r?",easeNone":"")),x(new T(null,null,3,r),n,"easeInOut");w.linear=l.easing.Linear.easeIn,w.swing=l.easing.Quad.easeInOut;var b=g("events.EventDispatcher",function(t){this._listeners={},this._eventTarget=t||this});n=b.prototype,n.addEventListener=function(t,e,i,s,r){r=r||0;var n,h,l=this._listeners[t],_=0;for(null==l&&(this._listeners[t]=l=[]),h=l.length;--h>-1;)n=l[h],n.c===e&&n.s===i?l.splice(h,1):0===_&&r>n.pr&&(_=h+1);l.splice(_,0,{c:e,s:i,up:s,pr:r}),this!==a||o||a.wake()},n.removeEventListener=function(t,e){var i,s=this._listeners[t];if(s)for(i=s.length;--i>-1;)if(s[i].c===e)return s.splice(i,1),void 0},n.dispatchEvent=function(t){var e,i,s,r=this._listeners[t];if(r)for(e=r.length,i=this._eventTarget;--e>-1;)s=r[e],s.up?s.c.call(s.s||i,{type:t,target:i}):s.c.call(s.s||i)};var P=t.requestAnimationFrame,S=t.cancelAnimationFrame,k=Date.now||function(){return(new Date).getTime()},R=k();for(s=["ms","moz","webkit","o"],r=s.length;--r>-1&&!P;)P=t[s[r]+"RequestAnimationFrame"],S=t[s[r]+"CancelAnimationFrame"]||t[s[r]+"CancelRequestAnimationFrame"];g("Ticker",function(t,e){var i,s,r,n,h,l=this,u=k(),c=e!==!1&&P,f=500,m=33,d=function(t){var e,a,o=k()-R;o>f&&(u+=o-m),R+=o,l.time=(R-u)/1e3,e=l.time-h,(!i||e>0||t===!0)&&(l.frame++,h+=e+(e>=n?.004:n-e),a=!0),t!==!0&&(r=s(d)),a&&l.dispatchEvent("tick")};b.call(l),l.time=l.frame=0,l.tick=function(){d(!0)},l.lagSmoothing=function(t,e){f=t||1/_,m=Math.min(e,f,0)},l.sleep=function(){null!=r&&(c&&S?S(r):clearTimeout(r),s=p,r=null,l===a&&(o=!1))},l.wake=function(){null!==r?l.sleep():l.frame>10&&(R=k()-f+5),s=0===i?p:c&&P?P:function(t){return setTimeout(t,0|1e3*(h-l.time)+1)},l===a&&(o=!0),d(2)},l.fps=function(t){return arguments.length?(i=t,n=1/(i||60),h=this.time+n,l.wake(),void 0):i},l.useRAF=function(t){return arguments.length?(l.sleep(),c=t,l.fps(i),void 0):c},l.fps(t),setTimeout(function(){c&&(!r||5>l.frame)&&l.useRAF(!1)},1500)}),n=l.Ticker.prototype=new l.events.EventDispatcher,n.constructor=l.Ticker;var A=g("core.Animation",function(t,e){if(this.vars=e=e||{},this._duration=this._totalDuration=t||0,this._delay=Number(e.delay)||0,this._timeScale=1,this._active=e.immediateRender===!0,this.data=e.data,this._reversed=e.reversed===!0,B){o||a.wake();var i=this.vars.useFrames?j:B;i.add(this,i._time),this.vars.paused&&this.paused(!0)}});a=A.ticker=new l.Ticker,n=A.prototype,n._dirty=n._gc=n._initted=n._paused=!1,n._totalTime=n._time=0,n._rawPrevTime=-1,n._next=n._last=n._onUpdate=n._timeline=n.timeline=null,n._paused=!1;var C=function(){o&&k()-R>2e3&&a.wake(),setTimeout(C,2e3)};C(),n.play=function(t,e){return null!=t&&this.seek(t,e),this.reversed(!1).paused(!1)},n.pause=function(t,e){return null!=t&&this.seek(t,e),this.paused(!0)},n.resume=function(t,e){return null!=t&&this.seek(t,e),this.paused(!1)},n.seek=function(t,e){return this.totalTime(Number(t),e!==!1)},n.restart=function(t,e){return this.reversed(!1).paused(!1).totalTime(t?-this._delay:0,e!==!1,!0)},n.reverse=function(t,e){return null!=t&&this.seek(t||this.totalDuration(),e),this.reversed(!0).paused(!1)},n.render=function(){},n.invalidate=function(){return this},n.isActive=function(){var t,e=this._timeline,i=this._startTime;return!e||!this._gc&&!this._paused&&e.isActive()&&(t=e.rawTime())>=i&&i+this.totalDuration()/this._timeScale>t},n._enabled=function(t,e){return o||a.wake(),this._gc=!t,this._active=this.isActive(),e!==!0&&(t&&!this.timeline?this._timeline.add(this,this._startTime-this._delay):!t&&this.timeline&&this._timeline._remove(this,!0)),!1},n._kill=function(){return this._enabled(!1,!1)},n.kill=function(t,e){return this._kill(t,e),this},n._uncache=function(t){for(var e=t?this:this.timeline;e;)e._dirty=!0,e=e.timeline;return this},n._swapSelfInParams=function(t){for(var e=t.length,i=t.concat();--e>-1;)"{self}"===t[e]&&(i[e]=this);return i},n.eventCallback=function(t,e,i,s){if("on"===(t||"").substr(0,2)){var r=this.vars;if(1===arguments.length)return r[t];null==e?delete r[t]:(r[t]=e,r[t+"Params"]=c(i)&&-1!==i.join("").indexOf("{self}")?this._swapSelfInParams(i):i,r[t+"Scope"]=s),"onUpdate"===t&&(this._onUpdate=e)}return this},n.delay=function(t){return arguments.length?(this._timeline.smoothChildTiming&&this.startTime(this._startTime+t-this._delay),this._delay=t,this):this._delay},n.duration=function(t){return arguments.length?(this._duration=this._totalDuration=t,this._uncache(!0),this._timeline.smoothChildTiming&&this._time>0&&this._time<this._duration&&0!==t&&this.totalTime(this._totalTime*(t/this._duration),!0),this):(this._dirty=!1,this._duration)},n.totalDuration=function(t){return this._dirty=!1,arguments.length?this.duration(t):this._totalDuration},n.time=function(t,e){return arguments.length?(this._dirty&&this.totalDuration(),this.totalTime(t>this._duration?this._duration:t,e)):this._time},n.totalTime=function(t,e,i){if(o||a.wake(),!arguments.length)return this._totalTime;if(this._timeline){if(0>t&&!i&&(t+=this.totalDuration()),this._timeline.smoothChildTiming){this._dirty&&this.totalDuration();var s=this._totalDuration,r=this._timeline;if(t>s&&!i&&(t=s),this._startTime=(this._paused?this._pauseTime:r._time)-(this._reversed?s-t:t)/this._timeScale,r._dirty||this._uncache(!1),r._timeline)for(;r._timeline;)r._timeline._time!==(r._startTime+r._totalTime)/r._timeScale&&r.totalTime(r._totalTime,!0),r=r._timeline}this._gc&&this._enabled(!0,!1),(this._totalTime!==t||0===this._duration)&&(this.render(t,e,!1),I.length&&q())}return this},n.progress=n.totalProgress=function(t,e){return arguments.length?this.totalTime(this.duration()*t,e):this._time/this.duration()},n.startTime=function(t){return arguments.length?(t!==this._startTime&&(this._startTime=t,this.timeline&&this.timeline._sortChildren&&this.timeline.add(this,t-this._delay)),this):this._startTime},n.timeScale=function(t){if(!arguments.length)return this._timeScale;if(t=t||_,this._timeline&&this._timeline.smoothChildTiming){var e=this._pauseTime,i=e||0===e?e:this._timeline.totalTime();this._startTime=i-(i-this._startTime)*this._timeScale/t}return this._timeScale=t,this._uncache(!1)},n.reversed=function(t){return arguments.length?(t!=this._reversed&&(this._reversed=t,this.totalTime(this._timeline&&!this._timeline.smoothChildTiming?this.totalDuration()-this._totalTime:this._totalTime,!0)),this):this._reversed},n.paused=function(t){if(!arguments.length)return this._paused;if(t!=this._paused&&this._timeline){o||t||a.wake();var e=this._timeline,i=e.rawTime(),s=i-this._pauseTime;!t&&e.smoothChildTiming&&(this._startTime+=s,this._uncache(!1)),this._pauseTime=t?i:null,this._paused=t,this._active=this.isActive(),!t&&0!==s&&this._initted&&this.duration()&&this.render(e.smoothChildTiming?this._totalTime:(i-this._startTime)/this._timeScale,!0,!0)}return this._gc&&!t&&this._enabled(!0,!1),this};var O=g("core.SimpleTimeline",function(t){A.call(this,0,t),this.autoRemoveChildren=this.smoothChildTiming=!0});n=O.prototype=new A,n.constructor=O,n.kill()._gc=!1,n._first=n._last=null,n._sortChildren=!1,n.add=n.insert=function(t,e){var i,s;if(t._startTime=Number(e||0)+t._delay,t._paused&&this!==t._timeline&&(t._pauseTime=t._startTime+(this.rawTime()-t._startTime)/t._timeScale),t.timeline&&t.timeline._remove(t,!0),t.timeline=t._timeline=this,t._gc&&t._enabled(!0,!0),i=this._last,this._sortChildren)for(s=t._startTime;i&&i._startTime>s;)i=i._prev;return i?(t._next=i._next,i._next=t):(t._next=this._first,this._first=t),t._next?t._next._prev=t:this._last=t,t._prev=i,this._timeline&&this._uncache(!0),this},n._remove=function(t,e){return t.timeline===this&&(e||t._enabled(!1,!0),t._prev?t._prev._next=t._next:this._first===t&&(this._first=t._next),t._next?t._next._prev=t._prev:this._last===t&&(this._last=t._prev),t._next=t._prev=t.timeline=null,this._timeline&&this._uncache(!0)),this},n.render=function(t,e,i){var s,r=this._first;for(this._totalTime=this._time=this._rawPrevTime=t;r;)s=r._next,(r._active||t>=r._startTime&&!r._paused)&&(r._reversed?r.render((r._dirty?r.totalDuration():r._totalDuration)-(t-r._startTime)*r._timeScale,e,i):r.render((t-r._startTime)*r._timeScale,e,i)),r=s},n.rawTime=function(){return o||a.wake(),this._totalTime};var D=g("TweenLite",function(e,i,s){if(A.call(this,i,s),this.render=D.prototype.render,null==e)throw"Cannot tween a null target.";this.target=e="string"!=typeof e?e:D.selector(e)||e;var r,n,a,o=e.jquery||e.length&&e!==t&&e[0]&&(e[0]===t||e[0].nodeType&&e[0].style&&!e.nodeType),h=this.vars.overwrite;if(this._overwrite=h=null==h?Y[D.defaultOverwrite]:"number"==typeof h?h>>0:Y[h],(o||e instanceof Array||e.push&&c(e))&&"number"!=typeof e[0])for(this._targets=a=u(e),this._propLookup=[],this._siblings=[],r=0;a.length>r;r++)n=a[r],n?"string"!=typeof n?n.length&&n!==t&&n[0]&&(n[0]===t||n[0].nodeType&&n[0].style&&!n.nodeType)?(a.splice(r--,1),this._targets=a=a.concat(u(n))):(this._siblings[r]=V(n,this,!1),1===h&&this._siblings[r].length>1&&G(n,this,null,1,this._siblings[r])):(n=a[r--]=D.selector(n),"string"==typeof n&&a.splice(r+1,1)):a.splice(r--,1);else this._propLookup={},this._siblings=V(e,this,!1),1===h&&this._siblings.length>1&&G(e,this,null,1,this._siblings);(this.vars.immediateRender||0===i&&0===this._delay&&this.vars.immediateRender!==!1)&&(this._time=-_,this.render(-this._delay))},!0),M=function(e){return e.length&&e!==t&&e[0]&&(e[0]===t||e[0].nodeType&&e[0].style&&!e.nodeType)},z=function(t,e){var i,s={};for(i in t)U[i]||i in e&&"transform"!==i&&"x"!==i&&"y"!==i&&"width"!==i&&"height"!==i&&"className"!==i&&"border"!==i||!(!F[i]||F[i]&&F[i]._autoCSS)||(s[i]=t[i],delete t[i]);t.css=s};n=D.prototype=new A,n.constructor=D,n.kill()._gc=!1,n.ratio=0,n._firstPT=n._targets=n._overwrittenProps=n._startAt=null,n._notifyPluginsOfEnabled=n._lazy=!1,D.version="1.13.1",D.defaultEase=n._ease=new T(null,null,1,1),D.defaultOverwrite="auto",D.ticker=a,D.autoSleep=!0,D.lagSmoothing=function(t,e){a.lagSmoothing(t,e)},D.selector=t.$||t.jQuery||function(e){var i=t.$||t.jQuery;return i?(D.selector=i,i(e)):"undefined"==typeof document?e:document.querySelectorAll?document.querySelectorAll(e):document.getElementById("#"===e.charAt(0)?e.substr(1):e)};var I=[],E={},L=D._internals={isArray:c,isSelector:M,lazyTweens:I},F=D._plugins={},N=L.tweenLookup={},X=0,U=L.reservedProps={ease:1,delay:1,overwrite:1,onComplete:1,onCompleteParams:1,onCompleteScope:1,useFrames:1,runBackwards:1,startAt:1,onUpdate:1,onUpdateParams:1,onUpdateScope:1,onStart:1,onStartParams:1,onStartScope:1,onReverseComplete:1,onReverseCompleteParams:1,onReverseCompleteScope:1,onRepeat:1,onRepeatParams:1,onRepeatScope:1,easeParams:1,yoyo:1,immediateRender:1,repeat:1,repeatDelay:1,data:1,paused:1,reversed:1,autoCSS:1,lazy:1},Y={none:0,all:1,auto:2,concurrent:3,allOnStart:4,preexisting:5,"true":1,"false":0},j=A._rootFramesTimeline=new O,B=A._rootTimeline=new O,q=L.lazyRender=function(){var t=I.length;for(E={};--t>-1;)s=I[t],s&&s._lazy!==!1&&(s.render(s._lazy,!1,!0),s._lazy=!1);I.length=0};B._startTime=a.time,j._startTime=a.frame,B._active=j._active=!0,setTimeout(q,1),A._updateRoot=D.render=function(){var t,e,i;if(I.length&&q(),B.render((a.time-B._startTime)*B._timeScale,!1,!1),j.render((a.frame-j._startTime)*j._timeScale,!1,!1),I.length&&q(),!(a.frame%120)){for(i in N){for(e=N[i].tweens,t=e.length;--t>-1;)e[t]._gc&&e.splice(t,1);0===e.length&&delete N[i]}if(i=B._first,(!i||i._paused)&&D.autoSleep&&!j._first&&1===a._listeners.tick.length){for(;i&&i._paused;)i=i._next;i||a.sleep()}}},a.addEventListener("tick",A._updateRoot);var V=function(t,e,i){var s,r,n=t._gsTweenID;if(N[n||(t._gsTweenID=n="t"+X++)]||(N[n]={target:t,tweens:[]}),e&&(s=N[n].tweens,s[r=s.length]=e,i))for(;--r>-1;)s[r]===e&&s.splice(r,1);return N[n].tweens},G=function(t,e,i,s,r){var n,a,o,h;if(1===s||s>=4){for(h=r.length,n=0;h>n;n++)if((o=r[n])!==e)o._gc||o._enabled(!1,!1)&&(a=!0);else if(5===s)break;return a}var l,u=e._startTime+_,p=[],c=0,f=0===e._duration;for(n=r.length;--n>-1;)(o=r[n])===e||o._gc||o._paused||(o._timeline!==e._timeline?(l=l||W(e,0,f),0===W(o,l,f)&&(p[c++]=o)):u>=o._startTime&&o._startTime+o.totalDuration()/o._timeScale>u&&((f||!o._initted)&&2e-10>=u-o._startTime||(p[c++]=o)));for(n=c;--n>-1;)o=p[n],2===s&&o._kill(i,t)&&(a=!0),(2!==s||!o._firstPT&&o._initted)&&o._enabled(!1,!1)&&(a=!0);return a},W=function(t,e,i){for(var s=t._timeline,r=s._timeScale,n=t._startTime;s._timeline;){if(n+=s._startTime,r*=s._timeScale,s._paused)return-100;s=s._timeline}return n/=r,n>e?n-e:i&&n===e||!t._initted&&2*_>n-e?_:(n+=t.totalDuration()/t._timeScale/r)>e+_?0:n-e-_};n._init=function(){var t,e,i,s,r,n=this.vars,a=this._overwrittenProps,o=this._duration,h=!!n.immediateRender,l=n.ease;if(n.startAt){this._startAt&&(this._startAt.render(-1,!0),this._startAt.kill()),r={};for(s in n.startAt)r[s]=n.startAt[s];if(r.overwrite=!1,r.immediateRender=!0,r.lazy=h&&n.lazy!==!1,r.startAt=r.delay=null,this._startAt=D.to(this.target,0,r),h)if(this._time>0)this._startAt=null;else if(0!==o)return}else if(n.runBackwards&&0!==o)if(this._startAt)this._startAt.render(-1,!0),this._startAt.kill(),this._startAt=null;else{i={};for(s in n)U[s]&&"autoCSS"!==s||(i[s]=n[s]);if(i.overwrite=0,i.data="isFromStart",i.lazy=h&&n.lazy!==!1,i.immediateRender=h,this._startAt=D.to(this.target,0,i),h){if(0===this._time)return}else this._startAt._init(),this._startAt._enabled(!1)}if(this._ease=l=l?l instanceof T?l:"function"==typeof l?new T(l,n.easeParams):w[l]||D.defaultEase:D.defaultEase,n.easeParams instanceof Array&&l.config&&(this._ease=l.config.apply(l,n.easeParams)),this._easeType=this._ease._type,this._easePower=this._ease._power,this._firstPT=null,this._targets)for(t=this._targets.length;--t>-1;)this._initProps(this._targets[t],this._propLookup[t]={},this._siblings[t],a?a[t]:null)&&(e=!0);else e=this._initProps(this.target,this._propLookup,this._siblings,a);if(e&&D._onPluginEvent("_onInitAllProps",this),a&&(this._firstPT||"function"!=typeof this.target&&this._enabled(!1,!1)),n.runBackwards)for(i=this._firstPT;i;)i.s+=i.c,i.c=-i.c,i=i._next;this._onUpdate=n.onUpdate,this._initted=!0},n._initProps=function(e,i,s,r){var n,a,o,h,l,_;if(null==e)return!1;E[e._gsTweenID]&&q(),this.vars.css||e.style&&e!==t&&e.nodeType&&F.css&&this.vars.autoCSS!==!1&&z(this.vars,e);for(n in this.vars){if(_=this.vars[n],U[n])_&&(_ instanceof Array||_.push&&c(_))&&-1!==_.join("").indexOf("{self}")&&(this.vars[n]=_=this._swapSelfInParams(_,this));else if(F[n]&&(h=new F[n])._onInitTween(e,this.vars[n],this)){for(this._firstPT=l={_next:this._firstPT,t:h,p:"setRatio",s:0,c:1,f:!0,n:n,pg:!0,pr:h._priority},a=h._overwriteProps.length;--a>-1;)i[h._overwriteProps[a]]=this._firstPT;(h._priority||h._onInitAllProps)&&(o=!0),(h._onDisable||h._onEnable)&&(this._notifyPluginsOfEnabled=!0)}else this._firstPT=i[n]=l={_next:this._firstPT,t:e,p:n,f:"function"==typeof e[n],n:n,pg:!1,pr:0},l.s=l.f?e[n.indexOf("set")||"function"!=typeof e["get"+n.substr(3)]?n:"get"+n.substr(3)]():parseFloat(e[n]),l.c="string"==typeof _&&"="===_.charAt(1)?parseInt(_.charAt(0)+"1",10)*Number(_.substr(2)):Number(_)-l.s||0;l&&l._next&&(l._next._prev=l)}return r&&this._kill(r,e)?this._initProps(e,i,s,r):this._overwrite>1&&this._firstPT&&s.length>1&&G(e,this,i,this._overwrite,s)?(this._kill(i,e),this._initProps(e,i,s,r)):(this._firstPT&&(this.vars.lazy!==!1&&this._duration||this.vars.lazy&&!this._duration)&&(E[e._gsTweenID]=!0),o)},n.render=function(t,e,i){var s,r,n,a,o=this._time,h=this._duration,l=this._rawPrevTime;if(t>=h)this._totalTime=this._time=h,this.ratio=this._ease._calcEnd?this._ease.getRatio(1):1,this._reversed||(s=!0,r="onComplete"),0===h&&(this._initted||!this.vars.lazy||i)&&(this._startTime===this._timeline._duration&&(t=0),(0===t||0>l||l===_)&&l!==t&&(i=!0,l>_&&(r="onReverseComplete")),this._rawPrevTime=a=!e||t||l===t?t:_);else if(1e-7>t)this._totalTime=this._time=0,this.ratio=this._ease._calcEnd?this._ease.getRatio(0):0,(0!==o||0===h&&l>0&&l!==_)&&(r="onReverseComplete",s=this._reversed),0>t?(this._active=!1,0===h&&(this._initted||!this.vars.lazy||i)&&(l>=0&&(i=!0),this._rawPrevTime=a=!e||t||l===t?t:_)):this._initted||(i=!0);else if(this._totalTime=this._time=t,this._easeType){var u=t/h,p=this._easeType,c=this._easePower;(1===p||3===p&&u>=.5)&&(u=1-u),3===p&&(u*=2),1===c?u*=u:2===c?u*=u*u:3===c?u*=u*u*u:4===c&&(u*=u*u*u*u),this.ratio=1===p?1-u:2===p?u:.5>t/h?u/2:1-u/2}else this.ratio=this._ease.getRatio(t/h);if(this._time!==o||i){if(!this._initted){if(this._init(),!this._initted||this._gc)return;if(!i&&this._firstPT&&(this.vars.lazy!==!1&&this._duration||this.vars.lazy&&!this._duration))return this._time=this._totalTime=o,this._rawPrevTime=l,I.push(this),this._lazy=t,void 0;this._time&&!s?this.ratio=this._ease.getRatio(this._time/h):s&&this._ease._calcEnd&&(this.ratio=this._ease.getRatio(0===this._time?0:1))}for(this._lazy!==!1&&(this._lazy=!1),this._active||!this._paused&&this._time!==o&&t>=0&&(this._active=!0),0===o&&(this._startAt&&(t>=0?this._startAt.render(t,e,i):r||(r="_dummyGS")),this.vars.onStart&&(0!==this._time||0===h)&&(e||this.vars.onStart.apply(this.vars.onStartScope||this,this.vars.onStartParams||y))),n=this._firstPT;n;)n.f?n.t[n.p](n.c*this.ratio+n.s):n.t[n.p]=n.c*this.ratio+n.s,n=n._next;this._onUpdate&&(0>t&&this._startAt&&this._startTime&&this._startAt.render(t,e,i),e||(this._time!==o||s)&&this._onUpdate.apply(this.vars.onUpdateScope||this,this.vars.onUpdateParams||y)),r&&(!this._gc||i)&&(0>t&&this._startAt&&!this._onUpdate&&this._startTime&&this._startAt.render(t,e,i),s&&(this._timeline.autoRemoveChildren&&this._enabled(!1,!1),this._active=!1),!e&&this.vars[r]&&this.vars[r].apply(this.vars[r+"Scope"]||this,this.vars[r+"Params"]||y),0===h&&this._rawPrevTime===_&&a!==_&&(this._rawPrevTime=0))}},n._kill=function(t,e){if("all"===t&&(t=null),null==t&&(null==e||e===this.target))return this._lazy=!1,this._enabled(!1,!1);e="string"!=typeof e?e||this._targets||this.target:D.selector(e)||e;var i,s,r,n,a,o,h,l;if((c(e)||M(e))&&"number"!=typeof e[0])for(i=e.length;--i>-1;)this._kill(t,e[i])&&(o=!0);else{if(this._targets){for(i=this._targets.length;--i>-1;)if(e===this._targets[i]){a=this._propLookup[i]||{},this._overwrittenProps=this._overwrittenProps||[],s=this._overwrittenProps[i]=t?this._overwrittenProps[i]||{}:"all";break}}else{if(e!==this.target)return!1;a=this._propLookup,s=this._overwrittenProps=t?this._overwrittenProps||{}:"all"}if(a){h=t||a,l=t!==s&&"all"!==s&&t!==a&&("object"!=typeof t||!t._tempKill);for(r in h)(n=a[r])&&(n.pg&&n.t._kill(h)&&(o=!0),n.pg&&0!==n.t._overwriteProps.length||(n._prev?n._prev._next=n._next:n===this._firstPT&&(this._firstPT=n._next),n._next&&(n._next._prev=n._prev),n._next=n._prev=null),delete a[r]),l&&(s[r]=1);!this._firstPT&&this._initted&&this._enabled(!1,!1)}}return o},n.invalidate=function(){return this._notifyPluginsOfEnabled&&D._onPluginEvent("_onDisable",this),this._firstPT=null,this._overwrittenProps=null,this._onUpdate=null,this._startAt=null,this._initted=this._active=this._notifyPluginsOfEnabled=this._lazy=!1,this._propLookup=this._targets?{}:[],this},n._enabled=function(t,e){if(o||a.wake(),t&&this._gc){var i,s=this._targets;if(s)for(i=s.length;--i>-1;)this._siblings[i]=V(s[i],this,!0);else this._siblings=V(this.target,this,!0)}return A.prototype._enabled.call(this,t,e),this._notifyPluginsOfEnabled&&this._firstPT?D._onPluginEvent(t?"_onEnable":"_onDisable",this):!1},D.to=function(t,e,i){return new D(t,e,i)},D.from=function(t,e,i){return i.runBackwards=!0,i.immediateRender=0!=i.immediateRender,new D(t,e,i)},D.fromTo=function(t,e,i,s){return s.startAt=i,s.immediateRender=0!=s.immediateRender&&0!=i.immediateRender,new D(t,e,s)},D.delayedCall=function(t,e,i,s,r){return new D(e,0,{delay:t,onComplete:e,onCompleteParams:i,onCompleteScope:s,onReverseComplete:e,onReverseCompleteParams:i,onReverseCompleteScope:s,immediateRender:!1,useFrames:r,overwrite:0})},D.set=function(t,e){return new D(t,0,e)},D.getTweensOf=function(t,e){if(null==t)return[];t="string"!=typeof t?t:D.selector(t)||t;var i,s,r,n;if((c(t)||M(t))&&"number"!=typeof t[0]){for(i=t.length,s=[];--i>-1;)s=s.concat(D.getTweensOf(t[i],e));for(i=s.length;--i>-1;)for(n=s[i],r=i;--r>-1;)n===s[r]&&s.splice(i,1)}else for(s=V(t).concat(),i=s.length;--i>-1;)(s[i]._gc||e&&!s[i].isActive())&&s.splice(i,1);return s},D.killTweensOf=D.killDelayedCallsTo=function(t,e,i){"object"==typeof e&&(i=e,e=!1);for(var s=D.getTweensOf(t,e),r=s.length;--r>-1;)s[r]._kill(i,t)};var Q=g("plugins.TweenPlugin",function(t,e){this._overwriteProps=(t||"").split(","),this._propName=this._overwriteProps[0],this._priority=e||0,this._super=Q.prototype},!0);if(n=Q.prototype,Q.version="1.10.1",Q.API=2,n._firstPT=null,n._addTween=function(t,e,i,s,r,n){var a,o;
return null!=s&&(a="number"==typeof s||"="!==s.charAt(1)?Number(s)-i:parseInt(s.charAt(0)+"1",10)*Number(s.substr(2)))?(this._firstPT=o={_next:this._firstPT,t:t,p:e,s:i,c:a,f:"function"==typeof t[e],n:r||e,r:n},o._next&&(o._next._prev=o),o):void 0},n.setRatio=function(t){for(var e,i=this._firstPT,s=1e-6;i;)e=i.c*t+i.s,i.r?e=Math.round(e):s>e&&e>-s&&(e=0),i.f?i.t[i.p](e):i.t[i.p]=e,i=i._next},n._kill=function(t){var e,i=this._overwriteProps,s=this._firstPT;if(null!=t[this._propName])this._overwriteProps=[];else for(e=i.length;--e>-1;)null!=t[i[e]]&&i.splice(e,1);for(;s;)null!=t[s.n]&&(s._next&&(s._next._prev=s._prev),s._prev?(s._prev._next=s._next,s._prev=null):this._firstPT===s&&(this._firstPT=s._next)),s=s._next;return!1},n._roundProps=function(t,e){for(var i=this._firstPT;i;)(t[this._propName]||null!=i.n&&t[i.n.split(this._propName+"_").join("")])&&(i.r=e),i=i._next},D._onPluginEvent=function(t,e){var i,s,r,n,a,o=e._firstPT;if("_onInitAllProps"===t){for(;o;){for(a=o._next,s=r;s&&s.pr>o.pr;)s=s._next;(o._prev=s?s._prev:n)?o._prev._next=o:r=o,(o._next=s)?s._prev=o:n=o,o=a}o=e._firstPT=r}for(;o;)o.pg&&"function"==typeof o.t[t]&&o.t[t]()&&(i=!0),o=o._next;return i},Q.activate=function(t){for(var e=t.length;--e>-1;)t[e].API===Q.API&&(F[(new t[e])._propName]=t[e]);return!0},d.plugin=function(t){if(!(t&&t.propName&&t.init&&t.API))throw"illegal plugin definition.";var e,i=t.propName,s=t.priority||0,r=t.overwriteProps,n={init:"_onInitTween",set:"setRatio",kill:"_kill",round:"_roundProps",initAll:"_onInitAllProps"},a=g("plugins."+i.charAt(0).toUpperCase()+i.substr(1)+"Plugin",function(){Q.call(this,i,s),this._overwriteProps=r||[]},t.global===!0),o=a.prototype=new Q(i);o.constructor=a,a.API=t.API;for(e in n)"function"==typeof t[e]&&(o[n[e]]=t[e]);return a.version=t.version,Q.activate([a]),a},s=t._gsQueue){for(r=0;s.length>r;r++)s[r]();for(n in f)f[n].func||t.console.log("GSAP encountered missing dependency: com.greensock."+n)}o=!1}}("undefined"!=typeof module&&module.exports&&"undefined"!=typeof global?global:this||window,"TweenMax"); | codevinsky/cdnjs | ajax/libs/gsap/1.13.1/TweenMax.min.js | JavaScript | mit | 98,785 |
"use strict";angular.module("ngLocale",[],["$provide",function(a){var d={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};function c(f){f=f+"";var e=f.indexOf(".");return(e==-1)?0:f.length-e-1}function b(j,e){var g=e;if(undefined===g){g=Math.min(c(j),3)}var i=Math.pow(10,g);var h=((j*i)|0)%i;return{v:g,f:h}}a.value("$locale",{DATETIME_FORMATS:{AMPMS:["am","pm"],DAY:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],ERANAMES:["Before Christ","Anno Domini"],ERAS:["BC","AD"],FIRSTDAYOFWEEK:0,MONTH:["January","February","March","April","May","June","July","August","September","October","November","December"],SHORTDAY:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],SHORTMONTH:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],WEEKENDRANGE:[5,6],fullDate:"EEEE, d MMMM y",longDate:"d MMMM y",medium:"d MMM y HH:mm:ss",mediumDate:"d MMM y",mediumTime:"HH:mm:ss","short":"dd/MM/y HH:mm",shortDate:"dd/MM/y",shortTime:"HH:mm"},NUMBER_FORMATS:{CURRENCY_SYM:"\u00a3",DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"\u00a4-",negSuf:"",posPre:"\u00a4",posSuf:""}]},id:"en-im",pluralCat:function(h,f){var g=h|0;var e=b(h,f);if(g==1&&e.v==0){return d.ONE}return d.OTHER}})}]); | viskin/cdnjs | ajax/libs/angular-i18n/1.4.0/angular-locale_en-im.min.js | JavaScript | mit | 1,368 |
/*
* /MathJax/jax/output/HTML-CSS/fonts/Neo-Euler/Symbols/Regular/Main.js
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.NeoEulerMathJax_Symbols={directory:"Symbols/Regular",family:"NeoEulerMathJax_Symbols",testString:"\u00A0\u2320\u2321\u2329\u232A\u239B\u239C\u239D\u239E\u239F\u23A0\u23A1\u23A2\u23A3\u23A4",32:[0,0,333,0,0],160:[0,0,333,0,0],8992:[915,0,444,180,452],8993:[925,0,444,-23,265],9001:[737,237,388,107,330],9002:[737,237,388,57,280],9115:[1808,0,883,292,851],9116:[620,0,875,292,403],9117:[1808,0,883,292,851],9118:[1808,0,873,22,581],9119:[620,0,875,472,583],9120:[1808,0,873,22,581],9121:[1799,0,666,326,659],9122:[602,0,666,326,395],9123:[1800,-1,666,326,659],9124:[1799,0,666,7,340],9125:[602,0,666,271,340],9126:[1800,-1,666,7,340],9127:[909,0,889,395,718],9128:[1820,0,889,170,492],9129:[909,0,889,395,718],9130:[320,0,889,395,492],9131:[909,0,889,170,492],9132:[1820,0,889,395,718],9133:[909,0,889,170,492],9134:[381,0,444,181,265]};MathJax.Callback.Queue(["initFont",MathJax.OutputJax["HTML-CSS"],"NeoEulerMathJax_Symbols"],["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Symbols/Regular/Main.js"]);
| kennynaoh/cdnjs | ajax/libs/mathjax/2.3/jax/output/HTML-CSS/fonts/Neo-Euler/Symbols/Regular/Main.js | JavaScript | mit | 1,771 |
"use strict";angular.module("ngLocale",[],["$provide",function(a){var d={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};function c(f){f=f+"";var e=f.indexOf(".");return(e==-1)?0:f.length-e-1}function b(j,e){var g=e;if(undefined===g){g=Math.min(c(j),3)}var i=Math.pow(10,g);var h=((j*i)|0)%i;return{v:g,f:h}}a.value("$locale",{DATETIME_FORMATS:{AMPMS:["am","pm"],DAY:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],ERANAMES:["Before Christ","Anno Domini"],ERAS:["BC","AD"],FIRSTDAYOFWEEK:0,MONTH:["January","February","March","April","May","June","July","August","September","October","November","December"],SHORTDAY:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],SHORTMONTH:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],WEEKENDRANGE:[5,6],fullDate:"EEEE, d MMMM y",longDate:"d MMMM y",medium:"d MMM y HH:mm:ss",mediumDate:"d MMM y",mediumTime:"HH:mm:ss","short":"dd/MM/y HH:mm",shortDate:"dd/MM/y",shortTime:"HH:mm"},NUMBER_FORMATS:{CURRENCY_SYM:"\u00a3",DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"\u00a4-",negSuf:"",posPre:"\u00a4",posSuf:""}]},id:"en-fk",pluralCat:function(h,f){var g=h|0;var e=b(h,f);if(g==1&&e.v==0){return d.ONE}return d.OTHER}})}]); | gaearon/cdnjs | ajax/libs/angular-i18n/1.4.0-rc.2/angular-locale_en-fk.min.js | JavaScript | mit | 1,368 |
"use strict";angular.module("ngLocale",[],["$provide",function(a){var d={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};function c(f){f=f+"";var e=f.indexOf(".");return(e==-1)?0:f.length-e-1}function b(j,e){var g=e;if(undefined===g){g=Math.min(c(j),3)}var i=Math.pow(10,g);var h=((j*i)|0)%i;return{v:g,f:h}}a.value("$locale",{DATETIME_FORMATS:{AMPMS:["AM","PM"],DAY:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],ERANAMES:["Before Christ","Anno Domini"],ERAS:["BC","AD"],FIRSTDAYOFWEEK:0,MONTH:["January","February","March","April","May","June","July","August","September","October","November","December"],SHORTDAY:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],SHORTMONTH:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],WEEKENDRANGE:[5,6],fullDate:"EEEE, MMMM d, y",longDate:"MMMM d, y",medium:"MMM d, y h:mm:ss a",mediumDate:"MMM d, y",mediumTime:"h:mm:ss a","short":"M/d/yy h:mm a",shortDate:"M/d/yy",shortTime:"h:mm a"},NUMBER_FORMATS:{CURRENCY_SYM:"$",DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"\u00a4-",negSuf:"",posPre:"\u00a4",posSuf:""}]},id:"en-ky",pluralCat:function(h,f){var g=h|0;var e=b(h,f);if(g==1&&e.v==0){return d.ONE}return d.OTHER}})}]); | joeyparrish/cdnjs | ajax/libs/angular-i18n/1.4.0-rc.0/angular-locale_en-ky.min.js | JavaScript | mit | 1,369 |
"use strict";angular.module("ngLocale",[],["$provide",function(a){var b={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};a.value("$locale",{DATETIME_FORMATS:{AMPMS:["PG","PTG"],DAY:["Ahad","Isnin","Selasa","Rabu","Khamis","Jumaat","Sabtu"],ERANAMES:["S.M.","TM"],ERAS:["S.M.","TM"],FIRSTDAYOFWEEK:0,MONTH:["Januari","Februari","Mac","April","Mei","Jun","Julai","Ogos","September","Oktober","November","Disember"],SHORTDAY:["Ahd","Isn","Sel","Rab","Kha","Jum","Sab"],SHORTMONTH:["Jan","Feb","Mac","Apr","Mei","Jun","Jul","Ogo","Sep","Okt","Nov","Dis"],WEEKENDRANGE:[5,6],fullDate:"EEEE, d MMMM y",longDate:"d MMMM y",medium:"d MMM y h:mm:ss a",mediumDate:"d MMM y",mediumTime:"h:mm:ss a","short":"d/MM/yy h:mm a",shortDate:"d/MM/yy",shortTime:"h:mm a"},NUMBER_FORMATS:{CURRENCY_SYM:"RM",DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"\u00a4-",negSuf:"",posPre:"\u00a4",posSuf:""}]},id:"ms-latn-my",pluralCat:function(d,c){return b.OTHER}})}]); | gaearon/cdnjs | ajax/libs/angular-i18n/1.4.0-beta.6/angular-locale_ms-latn-my.min.js | JavaScript | mit | 1,100 |
"use strict";angular.module("ngLocale",[],["$provide",function(a){var d={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};function c(f){f=f+"";var e=f.indexOf(".");return(e==-1)?0:f.length-e-1}function b(j,e){var g=e;if(undefined===g){g=Math.min(c(j),3)}var i=Math.pow(10,g);var h=((j*i)|0)%i;return{v:g,f:h}}a.value("$locale",{DATETIME_FORMATS:{AMPMS:["priek\u0161pusdien\u0101","p\u0113cpusdien\u0101"],DAY:["sv\u0113tdiena","pirmdiena","otrdiena","tre\u0161diena","ceturtdiena","piektdiena","sestdiena"],ERANAMES:["pirms m\u016bsu \u0113ras","m\u016bsu \u0113r\u0101"],ERAS:["p.m.\u0113.","m.\u0113."],FIRSTDAYOFWEEK:0,MONTH:["janv\u0101ris","febru\u0101ris","marts","apr\u012blis","maijs","j\u016bnijs","j\u016blijs","augusts","septembris","oktobris","novembris","decembris"],SHORTDAY:["Sv","Pr","Ot","Tr","Ce","Pk","Se"],SHORTMONTH:["janv.","febr.","marts","apr.","maijs","j\u016bn.","j\u016bl.","aug.","sept.","okt.","nov.","dec."],WEEKENDRANGE:[5,6],fullDate:"EEEE, y. 'gada' d. MMMM",longDate:"y. 'gada' d. MMMM",medium:"y. 'gada' d. MMM HH:mm:ss",mediumDate:"y. 'gada' d. MMM",mediumTime:"HH:mm:ss","short":"dd.MM.yy HH:mm",shortDate:"dd.MM.yy",shortTime:"HH:mm"},NUMBER_FORMATS:{CURRENCY_SYM:"\u20ac",DECIMAL_SEP:",",GROUP_SEP:"\u00a0",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:0,lgSize:0,maxFrac:2,minFrac:2,minInt:1,negPre:"\u00a4-",negSuf:"",posPre:"\u00a4",posSuf:""}]},id:"lv-lv",pluralCat:function(g,f){var e=b(g,f);if(g%10==0||g%100>=11&&g%100<=19||e.v==2&&e.f%100>=11&&e.f%100<=19){return d.ZERO}if(g%10==1&&g%100!=11||e.v==2&&e.f%10==1&&e.f%100!=11||e.v!=2&&e.f%10==1){return d.ONE}return d.OTHER}})}]); | sujonvidia/cdnjs | ajax/libs/angular-i18n/1.4.0-rc.1/angular-locale_lv-lv.min.js | JavaScript | mit | 1,706 |
"use strict";angular.module("ngLocale",[],["$provide",function(a){var d={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};function c(f){f=f+"";var e=f.indexOf(".");return(e==-1)?0:f.length-e-1}function b(j,e){var g=e;if(undefined===g){g=Math.min(c(j),3)}var i=Math.pow(10,g);var h=((j*i)|0)%i;return{v:g,f:h}}a.value("$locale",{DATETIME_FORMATS:{AMPMS:["\u042d\u0418","\u042d\u041a"],DAY:["\u0411\u0430\u0441\u043a\u044b\u04bb\u044b\u0430\u043d\u043d\u044c\u0430","\u0411\u044d\u043d\u0438\u0434\u0438\u044d\u043b\u0438\u043d\u043d\u044c\u0438\u043a","\u041e\u043f\u0442\u0443\u043e\u0440\u0443\u043d\u043d\u044c\u0443\u043a","\u0421\u044d\u0440\u044d\u0434\u044d","\u0427\u044d\u043f\u043f\u0438\u044d\u0440","\u0411\u044d\u044d\u0442\u0438\u04a5\u0441\u044d","\u0421\u0443\u0431\u0443\u043e\u0442\u0430"],ERANAMES:["\u0431. \u044d. \u0438.","\u0431. \u044d"],ERAS:["\u0431. \u044d. \u0438.","\u0431. \u044d"],FIRSTDAYOFWEEK:0,MONTH:["\u0422\u043e\u0445\u0441\u0443\u043d\u043d\u044c\u0443","\u041e\u043b\u0443\u043d\u043d\u044c\u0443","\u041a\u0443\u043b\u0443\u043d \u0442\u0443\u0442\u0430\u0440","\u041c\u0443\u0443\u0441 \u0443\u0441\u0442\u0430\u0440","\u042b\u0430\u043c \u044b\u0439\u044b\u043d","\u0411\u044d\u0441 \u044b\u0439\u044b\u043d","\u041e\u0442 \u044b\u0439\u044b\u043d","\u0410\u0442\u044b\u0440\u0434\u044c\u044b\u0445 \u044b\u0439\u044b\u043d","\u0411\u0430\u043b\u0430\u0495\u0430\u043d \u044b\u0439\u044b\u043d","\u0410\u043b\u0442\u044b\u043d\u043d\u044c\u044b","\u0421\u044d\u0442\u0438\u043d\u043d\u044c\u0438","\u0410\u0445\u0441\u044b\u043d\u043d\u044c\u044b"],SHORTDAY:["\u0411\u0441","\u0411\u043d","\u041e\u043f","\u0421\u044d","\u0427\u043f","\u0411\u044d","\u0421\u0431"],SHORTMONTH:["\u0422\u043e\u0445\u0441","\u041e\u043b\u0443\u043d","\u041a\u043b\u043d_\u0442\u0442\u0440","\u041c\u0443\u0441_\u0443\u0441\u0442","\u042b\u0430\u043c_\u0439\u043d","\u0411\u044d\u0441_\u0439\u043d","\u041e\u0442_\u0439\u043d","\u0410\u0442\u0440\u0434\u044c_\u0439\u043d","\u0411\u043b\u0495\u043d_\u0439\u043d","\u0410\u043b\u0442","\u0421\u044d\u0442","\u0410\u0445\u0441"],WEEKENDRANGE:[5,6],fullDate:"y '\u0441\u044b\u043b' MMMM d '\u043a\u04af\u043d\u044d', EEEE",longDate:"y, MMMM d",medium:"y, MMM d HH:mm:ss",mediumDate:"y, MMM d",mediumTime:"HH:mm:ss","short":"yy/M/d HH:mm",shortDate:"yy/M/d",shortTime:"HH:mm"},NUMBER_FORMATS:{CURRENCY_SYM:"\u0440\u0443\u0431.",DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"\u00a4\u00a0-",negSuf:"",posPre:"\u00a4\u00a0",posSuf:""}]},id:"sah-ru",pluralCat:function(h,f){var g=h|0;var e=b(h,f);if(g==1&&e.v==0){return d.ONE}return d.OTHER}})}]); | jackdoyle/cdnjs | ajax/libs/angular-i18n/1.4.2/angular-locale_sah-ru.min.js | JavaScript | mit | 2,770 |
/*
* /MathJax/jax/output/HTML-CSS/fonts/Asana-Math/Shapes/Regular/Main.js
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.AsanaMathJax_Shapes={directory:"Shapes/Regular",family:"AsanaMathJax_Shapes",testString:"\u2422\u2423\u25B7\u25BA\u25BB\u25C1\u25C4\u25C5\u25CB\u25CE\u25CF\u25E6\u25E7\u25E8\u25EB",32:[0,0,249,0,0],9250:[726,28,552,-27,508],9251:[262,0,726,35,691],9655:[578,1,667,45,622],9658:[515,-26,838,65,774],9659:[515,-26,838,65,774],9665:[578,1,667,45,622],9668:[515,-26,838,65,774],9669:[515,-26,838,65,774],9675:[705,164,906,18,889],9678:[705,164,906,18,889],9679:[705,164,906,18,889],9702:[466,-75,522,65,458],9703:[560,0,688,65,623],9704:[560,0,688,65,623],9707:[560,0,688,65,623],9723:[480,0,598,64,534],9724:[480,0,598,64,534],9733:[778,98,1013,46,968],9734:[778,98,1013,46,968],9828:[642,21,570,23,547],9829:[591,7,636,44,593],9830:[642,101,559,44,516],9831:[605,21,607,23,585],9833:[701,19,319,19,301],9834:[701,19,525,19,507],9856:[669,23,982,145,837],9857:[669,23,982,145,837],9858:[669,23,982,145,837],9859:[669,23,982,145,837],9860:[669,23,982,145,837],9861:[669,23,982,145,837],11008:[583,139,854,65,785],11009:[583,139,854,65,785],11010:[583,139,854,65,785],11011:[583,139,854,65,785],11012:[554,12,1128,64,1064],11013:[554,12,1013,64,950],11014:[713,172,678,56,622],11015:[713,172,678,56,622],11016:[583,139,852,65,785],11017:[583,139,852,65,785],11018:[583,139,852,65,785],11019:[583,139,852,65,785],11020:[554,12,1128,64,1064],11021:[751,209,694,63,629],11022:[425,-48,968,65,904],11023:[425,-48,968,65,904],11024:[425,-48,968,65,904],11025:[425,-48,968,65,904],11034:[674,6,800,60,740],11035:[703,0,843,70,773],11036:[703,0,843,70,773],11056:[504,-33,1089,27,1063],11057:[845,305,1013,65,949],11058:[524,-17,1013,65,949],11059:[486,-55,1513,38,1476],11060:[486,-55,1013,65,949],11061:[486,-55,1013,65,949],11062:[486,-55,1013,65,949],11063:[486,-55,1150,27,1124],11064:[486,-55,1211,63,1147],11065:[489,-58,1150,28,1123],11066:[486,-55,1150,86,1066],11067:[486,-55,1150,28,1122],11068:[486,-55,1150,28,1123],11069:[486,-55,1150,28,1123],11070:[486,-55,1013,65,949],11071:[484,-53,961,-3,902],11072:[613,-41,1013,65,949],11073:[486,-55,1013,65,949],11074:[564,22,1013,65,949],11075:[535,-7,1013,65,960],11076:[535,-10,1013,65,957],11077:[647,107,1013,64,950],11078:[647,107,1013,64,950],11079:[486,-55,1013,65,949],11080:[486,136,1013,65,949],11081:[486,-55,1013,65,949],11082:[486,136,1013,65,949],11083:[486,-55,1013,65,949],11084:[486,-55,1013,65,949],11088:[577,37,708,32,678],11089:[458,2,554,35,519],11090:[458,2,554,35,519]};MathJax.Callback.Queue(["initFont",MathJax.OutputJax["HTML-CSS"],"AsanaMathJax_Shapes"],["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Shapes/Regular/Main.js"]);
| dryajov/cdnjs | ajax/libs/mathjax/2.3.0/jax/output/HTML-CSS/fonts/Asana-Math/Shapes/Regular/Main.js | JavaScript | mit | 3,371 |
/*!
* typeahead.js 0.10.3
* https://github.com/twitter/typeahead.js
* Copyright 2013-2014 Twitter, Inc. and other contributors; Licensed MIT
*/
(function($) {
var _ = function() {
"use strict";
return {
isMsie: function() {
return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
},
isBlankString: function(str) {
return !str || /^\s*$/.test(str);
},
escapeRegExChars: function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
isString: function(obj) {
return typeof obj === "string";
},
isNumber: function(obj) {
return typeof obj === "number";
},
isArray: $.isArray,
isFunction: $.isFunction,
isObject: $.isPlainObject,
isUndefined: function(obj) {
return typeof obj === "undefined";
},
toStr: function toStr(s) {
return _.isUndefined(s) || s === null ? "" : s + "";
},
bind: $.proxy,
each: function(collection, cb) {
$.each(collection, reverseArgs);
function reverseArgs(index, value) {
return cb(value, index);
}
},
map: $.map,
filter: $.grep,
every: function(obj, test) {
var result = true;
if (!obj) {
return result;
}
$.each(obj, function(key, val) {
if (!(result = test.call(null, val, key, obj))) {
return false;
}
});
return !!result;
},
some: function(obj, test) {
var result = false;
if (!obj) {
return result;
}
$.each(obj, function(key, val) {
if (result = test.call(null, val, key, obj)) {
return false;
}
});
return !!result;
},
mixin: $.extend,
getUniqueId: function() {
var counter = 0;
return function() {
return counter++;
};
}(),
templatify: function templatify(obj) {
return $.isFunction(obj) ? obj : template;
function template() {
return String(obj);
}
},
defer: function(fn) {
setTimeout(fn, 0);
},
debounce: function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments, later, callNow;
later = function() {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
},
throttle: function(func, wait) {
var context, args, timeout, result, previous, later;
previous = 0;
later = function() {
previous = new Date();
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date(), remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
},
noop: function() {}
};
}();
var html = function() {
return {
wrapper: '<span class="twitter-typeahead"></span>',
dropdown: '<span class="tt-dropdown-menu"></span>',
dataset: '<div class="tt-dataset-%CLASS%"></div>',
suggestions: '<span class="tt-suggestions"></span>',
suggestion: '<div class="tt-suggestion"></div>'
};
}();
var css = function() {
"use strict";
var css = {
wrapper: {
position: "relative",
display: "inline-block"
},
hint: {
position: "absolute",
top: "0",
left: "0",
borderColor: "transparent",
boxShadow: "none",
opacity: "1"
},
input: {
position: "relative",
verticalAlign: "top",
backgroundColor: "transparent"
},
inputWithNoHint: {
position: "relative",
verticalAlign: "top"
},
dropdown: {
position: "absolute",
top: "100%",
left: "0",
zIndex: "100",
display: "none"
},
suggestions: {
display: "block"
},
suggestion: {
whiteSpace: "nowrap",
cursor: "pointer"
},
suggestionChild: {
whiteSpace: "normal"
},
ltr: {
left: "0",
right: "auto"
},
rtl: {
left: "auto",
right: " 0"
}
};
if (_.isMsie()) {
_.mixin(css.input, {
backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
});
}
if (_.isMsie() && _.isMsie() <= 7) {
_.mixin(css.input, {
marginTop: "-1px"
});
}
return css;
}();
var EventBus = function() {
"use strict";
var namespace = "typeahead:";
function EventBus(o) {
if (!o || !o.el) {
$.error("EventBus initialized without el");
}
this.$el = $(o.el);
}
_.mixin(EventBus.prototype, {
trigger: function(type) {
var args = [].slice.call(arguments, 1);
this.$el.trigger(namespace + type, args);
}
});
return EventBus;
}();
var EventEmitter = function() {
"use strict";
var splitter = /\s+/, nextTick = getNextTick();
return {
onSync: onSync,
onAsync: onAsync,
off: off,
trigger: trigger
};
function on(method, types, cb, context) {
var type;
if (!cb) {
return this;
}
types = types.split(splitter);
cb = context ? bindContext(cb, context) : cb;
this._callbacks = this._callbacks || {};
while (type = types.shift()) {
this._callbacks[type] = this._callbacks[type] || {
sync: [],
async: []
};
this._callbacks[type][method].push(cb);
}
return this;
}
function onAsync(types, cb, context) {
return on.call(this, "async", types, cb, context);
}
function onSync(types, cb, context) {
return on.call(this, "sync", types, cb, context);
}
function off(types) {
var type;
if (!this._callbacks) {
return this;
}
types = types.split(splitter);
while (type = types.shift()) {
delete this._callbacks[type];
}
return this;
}
function trigger(types) {
var type, callbacks, args, syncFlush, asyncFlush;
if (!this._callbacks) {
return this;
}
types = types.split(splitter);
args = [].slice.call(arguments, 1);
while ((type = types.shift()) && (callbacks = this._callbacks[type])) {
syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args));
asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args));
syncFlush() && nextTick(asyncFlush);
}
return this;
}
function getFlush(callbacks, context, args) {
return flush;
function flush() {
var cancelled;
for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) {
cancelled = callbacks[i].apply(context, args) === false;
}
return !cancelled;
}
}
function getNextTick() {
var nextTickFn;
if (window.setImmediate) {
nextTickFn = function nextTickSetImmediate(fn) {
setImmediate(function() {
fn();
});
};
} else {
nextTickFn = function nextTickSetTimeout(fn) {
setTimeout(function() {
fn();
}, 0);
};
}
return nextTickFn;
}
function bindContext(fn, context) {
return fn.bind ? fn.bind(context) : function() {
fn.apply(context, [].slice.call(arguments, 0));
};
}
}();
var highlight = function(doc) {
"use strict";
var defaults = {
node: null,
pattern: null,
tagName: "strong",
className: null,
wordsOnly: false,
caseSensitive: false
};
return function hightlight(o) {
var regex;
o = _.mixin({}, defaults, o);
if (!o.node || !o.pattern) {
return;
}
o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ];
regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly);
traverse(o.node, hightlightTextNode);
function hightlightTextNode(textNode) {
var match, patternNode, wrapperNode;
if (match = regex.exec(textNode.data)) {
wrapperNode = doc.createElement(o.tagName);
o.className && (wrapperNode.className = o.className);
patternNode = textNode.splitText(match.index);
patternNode.splitText(match[0].length);
wrapperNode.appendChild(patternNode.cloneNode(true));
textNode.parentNode.replaceChild(wrapperNode, patternNode);
}
return !!match;
}
function traverse(el, hightlightTextNode) {
var childNode, TEXT_NODE_TYPE = 3;
for (var i = 0; i < el.childNodes.length; i++) {
childNode = el.childNodes[i];
if (childNode.nodeType === TEXT_NODE_TYPE) {
i += hightlightTextNode(childNode) ? 1 : 0;
} else {
traverse(childNode, hightlightTextNode);
}
}
}
};
function getRegex(patterns, caseSensitive, wordsOnly) {
var escapedPatterns = [], regexStr;
for (var i = 0, len = patterns.length; i < len; i++) {
escapedPatterns.push(_.escapeRegExChars(patterns[i]));
}
regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")";
return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i");
}
}(window.document);
var Input = function() {
"use strict";
var specialKeyCodeMap;
specialKeyCodeMap = {
9: "tab",
27: "esc",
37: "left",
39: "right",
13: "enter",
38: "up",
40: "down"
};
function Input(o) {
var that = this, onBlur, onFocus, onKeydown, onInput;
o = o || {};
if (!o.input) {
$.error("input is missing");
}
onBlur = _.bind(this._onBlur, this);
onFocus = _.bind(this._onFocus, this);
onKeydown = _.bind(this._onKeydown, this);
onInput = _.bind(this._onInput, this);
this.$hint = $(o.hint);
this.$input = $(o.input).on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
if (this.$hint.length === 0) {
this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
}
if (!_.isMsie()) {
this.$input.on("input.tt", onInput);
} else {
this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
if (specialKeyCodeMap[$e.which || $e.keyCode]) {
return;
}
_.defer(_.bind(that._onInput, that, $e));
});
}
this.query = this.$input.val();
this.$overflowHelper = buildOverflowHelper(this.$input);
}
Input.normalizeQuery = function(str) {
return (str || "").replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
};
_.mixin(Input.prototype, EventEmitter, {
_onBlur: function onBlur() {
this.resetInputValue();
this.trigger("blurred");
},
_onFocus: function onFocus() {
this.trigger("focused");
},
_onKeydown: function onKeydown($e) {
var keyName = specialKeyCodeMap[$e.which || $e.keyCode];
this._managePreventDefault(keyName, $e);
if (keyName && this._shouldTrigger(keyName, $e)) {
this.trigger(keyName + "Keyed", $e);
}
},
_onInput: function onInput() {
this._checkInputValue();
},
_managePreventDefault: function managePreventDefault(keyName, $e) {
var preventDefault, hintValue, inputValue;
switch (keyName) {
case "tab":
hintValue = this.getHint();
inputValue = this.getInputValue();
preventDefault = hintValue && hintValue !== inputValue && !withModifier($e);
break;
case "up":
case "down":
preventDefault = !withModifier($e);
break;
default:
preventDefault = false;
}
preventDefault && $e.preventDefault();
},
_shouldTrigger: function shouldTrigger(keyName, $e) {
var trigger;
switch (keyName) {
case "tab":
trigger = !withModifier($e);
break;
default:
trigger = true;
}
return trigger;
},
_checkInputValue: function checkInputValue() {
var inputValue, areEquivalent, hasDifferentWhitespace;
inputValue = this.getInputValue();
areEquivalent = areQueriesEquivalent(inputValue, this.query);
hasDifferentWhitespace = areEquivalent ? this.query.length !== inputValue.length : false;
this.query = inputValue;
if (!areEquivalent) {
this.trigger("queryChanged", this.query);
} else if (hasDifferentWhitespace) {
this.trigger("whitespaceChanged", this.query);
}
},
focus: function focus() {
this.$input.focus();
},
blur: function blur() {
this.$input.blur();
},
getQuery: function getQuery() {
return this.query;
},
setQuery: function setQuery(query) {
this.query = query;
},
getInputValue: function getInputValue() {
return this.$input.val();
},
setInputValue: function setInputValue(value, silent) {
this.$input.val(value);
silent ? this.clearHint() : this._checkInputValue();
},
resetInputValue: function resetInputValue() {
this.setInputValue(this.query, true);
},
getHint: function getHint() {
return this.$hint.val();
},
setHint: function setHint(value) {
this.$hint.val(value);
},
clearHint: function clearHint() {
this.setHint("");
},
clearHintIfInvalid: function clearHintIfInvalid() {
var val, hint, valIsPrefixOfHint, isValid;
val = this.getInputValue();
hint = this.getHint();
valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0;
isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow();
!isValid && this.clearHint();
},
getLanguageDirection: function getLanguageDirection() {
return (this.$input.css("direction") || "ltr").toLowerCase();
},
hasOverflow: function hasOverflow() {
var constraint = this.$input.width() - 2;
this.$overflowHelper.text(this.getInputValue());
return this.$overflowHelper.width() >= constraint;
},
isCursorAtEnd: function() {
var valueLength, selectionStart, range;
valueLength = this.$input.val().length;
selectionStart = this.$input[0].selectionStart;
if (_.isNumber(selectionStart)) {
return selectionStart === valueLength;
} else if (document.selection) {
range = document.selection.createRange();
range.moveStart("character", -valueLength);
return valueLength === range.text.length;
}
return true;
},
destroy: function destroy() {
this.$hint.off(".tt");
this.$input.off(".tt");
this.$hint = this.$input = this.$overflowHelper = null;
}
});
return Input;
function buildOverflowHelper($input) {
return $('<pre aria-hidden="true"></pre>').css({
position: "absolute",
visibility: "hidden",
whiteSpace: "pre",
fontFamily: $input.css("font-family"),
fontSize: $input.css("font-size"),
fontStyle: $input.css("font-style"),
fontVariant: $input.css("font-variant"),
fontWeight: $input.css("font-weight"),
wordSpacing: $input.css("word-spacing"),
letterSpacing: $input.css("letter-spacing"),
textIndent: $input.css("text-indent"),
textRendering: $input.css("text-rendering"),
textTransform: $input.css("text-transform")
}).insertAfter($input);
}
function areQueriesEquivalent(a, b) {
return Input.normalizeQuery(a) === Input.normalizeQuery(b);
}
function withModifier($e) {
return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey;
}
}();
var Dataset = function() {
"use strict";
var datasetKey = "ttDataset", valueKey = "ttValue", datumKey = "ttDatum";
function Dataset(o) {
o = o || {};
o.templates = o.templates || {};
if (!o.source) {
$.error("missing source");
}
if (o.name && !isValidName(o.name)) {
$.error("invalid dataset name: " + o.name);
}
this.query = null;
this.highlight = !!o.highlight;
this.name = o.name || _.getUniqueId();
this.source = o.source;
this.displayFn = getDisplayFn(o.display || o.displayKey);
this.templates = getTemplates(o.templates, this.displayFn);
this.$el = $(html.dataset.replace("%CLASS%", this.name));
}
Dataset.extractDatasetName = function extractDatasetName(el) {
return $(el).data(datasetKey);
};
Dataset.extractValue = function extractDatum(el) {
return $(el).data(valueKey);
};
Dataset.extractDatum = function extractDatum(el) {
return $(el).data(datumKey);
};
_.mixin(Dataset.prototype, EventEmitter, {
_render: function render(query, suggestions) {
if (!this.$el) {
return;
}
var that = this, hasSuggestions;
this.$el.empty();
hasSuggestions = suggestions && suggestions.length;
if (!hasSuggestions && this.templates.empty) {
this.$el.html(getEmptyHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
} else if (hasSuggestions) {
this.$el.html(getSuggestionsHtml()).prepend(that.templates.header ? getHeaderHtml() : null).append(that.templates.footer ? getFooterHtml() : null);
}
this.trigger("rendered");
function getEmptyHtml() {
return that.templates.empty({
query: query,
isEmpty: true
});
}
function getSuggestionsHtml() {
var $suggestions, nodes;
$suggestions = $(html.suggestions).css(css.suggestions);
nodes = _.map(suggestions, getSuggestionNode);
$suggestions.append.apply($suggestions, nodes);
that.highlight && highlight({
className: "tt-highlight",
node: $suggestions[0],
pattern: query
});
return $suggestions;
function getSuggestionNode(suggestion) {
var $el;
$el = $(html.suggestion).append(that.templates.suggestion(suggestion)).data(datasetKey, that.name).data(valueKey, that.displayFn(suggestion)).data(datumKey, suggestion);
$el.children().each(function() {
$(this).css(css.suggestionChild);
});
return $el;
}
}
function getHeaderHtml() {
return that.templates.header({
query: query,
isEmpty: !hasSuggestions
});
}
function getFooterHtml() {
return that.templates.footer({
query: query,
isEmpty: !hasSuggestions
});
}
},
getRoot: function getRoot() {
return this.$el;
},
update: function update(query) {
var that = this;
this.query = query;
this.canceled = false;
this.source(query, render);
function render(suggestions) {
if (!that.canceled && query === that.query) {
that._render(query, suggestions);
}
}
},
cancel: function cancel() {
this.canceled = true;
},
clear: function clear() {
this.cancel();
this.$el.empty();
this.trigger("rendered");
},
isEmpty: function isEmpty() {
return this.$el.is(":empty");
},
destroy: function destroy() {
this.$el = null;
}
});
return Dataset;
function getDisplayFn(display) {
display = display || "value";
return _.isFunction(display) ? display : displayFn;
function displayFn(obj) {
return obj[display];
}
}
function getTemplates(templates, displayFn) {
return {
empty: templates.empty && _.templatify(templates.empty),
header: templates.header && _.templatify(templates.header),
footer: templates.footer && _.templatify(templates.footer),
suggestion: templates.suggestion || suggestionTemplate
};
function suggestionTemplate(context) {
return "<p>" + displayFn(context) + "</p>";
}
}
function isValidName(str) {
return /^[_a-zA-Z0-9-]+$/.test(str);
}
}();
var Dropdown = function() {
"use strict";
function Dropdown(o) {
var that = this, onSuggestionClick, onSuggestionMouseEnter, onSuggestionMouseLeave;
o = o || {};
if (!o.menu) {
$.error("menu is required");
}
this.isOpen = false;
this.isEmpty = true;
this.datasets = _.map(o.datasets, initializeDataset);
onSuggestionClick = _.bind(this._onSuggestionClick, this);
onSuggestionMouseEnter = _.bind(this._onSuggestionMouseEnter, this);
onSuggestionMouseLeave = _.bind(this._onSuggestionMouseLeave, this);
this.$menu = $(o.menu).on("click.tt", ".tt-suggestion", onSuggestionClick).on("mouseenter.tt", ".tt-suggestion", onSuggestionMouseEnter).on("mouseleave.tt", ".tt-suggestion", onSuggestionMouseLeave);
_.each(this.datasets, function(dataset) {
that.$menu.append(dataset.getRoot());
dataset.onSync("rendered", that._onRendered, that);
});
}
_.mixin(Dropdown.prototype, EventEmitter, {
_onSuggestionClick: function onSuggestionClick($e) {
this.trigger("suggestionClicked", $($e.currentTarget));
},
_onSuggestionMouseEnter: function onSuggestionMouseEnter($e) {
this._removeCursor();
this._setCursor($($e.currentTarget), true);
},
_onSuggestionMouseLeave: function onSuggestionMouseLeave() {
this._removeCursor();
},
_onRendered: function onRendered() {
this.isEmpty = _.every(this.datasets, isDatasetEmpty);
this.isEmpty ? this._hide() : this.isOpen && this._show();
this.trigger("datasetRendered");
function isDatasetEmpty(dataset) {
return dataset.isEmpty();
}
},
_hide: function() {
this.$menu.hide();
},
_show: function() {
this.$menu.css("display", "block");
},
_getSuggestions: function getSuggestions() {
return this.$menu.find(".tt-suggestion");
},
_getCursor: function getCursor() {
return this.$menu.find(".tt-cursor").first();
},
_setCursor: function setCursor($el, silent) {
$el.first().addClass("tt-cursor");
!silent && this.trigger("cursorMoved");
},
_removeCursor: function removeCursor() {
this._getCursor().removeClass("tt-cursor");
},
_moveCursor: function moveCursor(increment) {
var $suggestions, $oldCursor, newCursorIndex, $newCursor;
if (!this.isOpen) {
return;
}
$oldCursor = this._getCursor();
$suggestions = this._getSuggestions();
this._removeCursor();
newCursorIndex = $suggestions.index($oldCursor) + increment;
newCursorIndex = (newCursorIndex + 1) % ($suggestions.length + 1) - 1;
if (newCursorIndex === -1) {
this.trigger("cursorRemoved");
return;
} else if (newCursorIndex < -1) {
newCursorIndex = $suggestions.length - 1;
}
this._setCursor($newCursor = $suggestions.eq(newCursorIndex));
this._ensureVisible($newCursor);
},
_ensureVisible: function ensureVisible($el) {
var elTop, elBottom, menuScrollTop, menuHeight;
elTop = $el.position().top;
elBottom = elTop + $el.outerHeight(true);
menuScrollTop = this.$menu.scrollTop();
menuHeight = this.$menu.height() + parseInt(this.$menu.css("paddingTop"), 10) + parseInt(this.$menu.css("paddingBottom"), 10);
if (elTop < 0) {
this.$menu.scrollTop(menuScrollTop + elTop);
} else if (menuHeight < elBottom) {
this.$menu.scrollTop(menuScrollTop + (elBottom - menuHeight));
}
},
close: function close() {
if (this.isOpen) {
this.isOpen = false;
this._removeCursor();
this._hide();
this.trigger("closed");
}
},
open: function open() {
if (!this.isOpen) {
this.isOpen = true;
!this.isEmpty && this._show();
this.trigger("opened");
}
},
setLanguageDirection: function setLanguageDirection(dir) {
this.$menu.css(dir === "ltr" ? css.ltr : css.rtl);
},
moveCursorUp: function moveCursorUp() {
this._moveCursor(-1);
},
moveCursorDown: function moveCursorDown() {
this._moveCursor(+1);
},
getDatumForSuggestion: function getDatumForSuggestion($el) {
var datum = null;
if ($el.length) {
datum = {
raw: Dataset.extractDatum($el),
value: Dataset.extractValue($el),
datasetName: Dataset.extractDatasetName($el)
};
}
return datum;
},
getDatumForCursor: function getDatumForCursor() {
return this.getDatumForSuggestion(this._getCursor().first());
},
getDatumForTopSuggestion: function getDatumForTopSuggestion() {
return this.getDatumForSuggestion(this._getSuggestions().first());
},
update: function update(query) {
_.each(this.datasets, updateDataset);
function updateDataset(dataset) {
dataset.update(query);
}
},
empty: function empty() {
_.each(this.datasets, clearDataset);
this.isEmpty = true;
function clearDataset(dataset) {
dataset.clear();
}
},
isVisible: function isVisible() {
return this.isOpen && !this.isEmpty;
},
destroy: function destroy() {
this.$menu.off(".tt");
this.$menu = null;
_.each(this.datasets, destroyDataset);
function destroyDataset(dataset) {
dataset.destroy();
}
}
});
return Dropdown;
function initializeDataset(oDataset) {
return new Dataset(oDataset);
}
}();
var Typeahead = function() {
"use strict";
var attrsKey = "ttAttrs";
function Typeahead(o) {
var $menu, $input, $hint;
o = o || {};
if (!o.input) {
$.error("missing input");
}
this.isActivated = false;
this.autoselect = !!o.autoselect;
this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
this.$node = buildDom(o.input, o.withHint);
$menu = this.$node.find(".tt-dropdown-menu");
$input = this.$node.find(".tt-input");
$hint = this.$node.find(".tt-hint");
$input.on("blur.tt", function($e) {
var active, isActive, hasActive;
active = document.activeElement;
isActive = $menu.is(active);
hasActive = $menu.has(active).length > 0;
if (_.isMsie() && (isActive || hasActive)) {
$e.preventDefault();
$e.stopImmediatePropagation();
_.defer(function() {
$input.focus();
});
}
});
$menu.on("mousedown.tt", function($e) {
$e.preventDefault();
});
this.eventBus = o.eventBus || new EventBus({
el: $input
});
this.dropdown = new Dropdown({
menu: $menu,
datasets: o.datasets
}).onSync("suggestionClicked", this._onSuggestionClicked, this).onSync("cursorMoved", this._onCursorMoved, this).onSync("cursorRemoved", this._onCursorRemoved, this).onSync("opened", this._onOpened, this).onSync("closed", this._onClosed, this).onAsync("datasetRendered", this._onDatasetRendered, this);
this.input = new Input({
input: $input,
hint: $hint
}).onSync("focused", this._onFocused, this).onSync("blurred", this._onBlurred, this).onSync("enterKeyed", this._onEnterKeyed, this).onSync("tabKeyed", this._onTabKeyed, this).onSync("escKeyed", this._onEscKeyed, this).onSync("upKeyed", this._onUpKeyed, this).onSync("downKeyed", this._onDownKeyed, this).onSync("leftKeyed", this._onLeftKeyed, this).onSync("rightKeyed", this._onRightKeyed, this).onSync("queryChanged", this._onQueryChanged, this).onSync("whitespaceChanged", this._onWhitespaceChanged, this);
this._setLanguageDirection();
}
_.mixin(Typeahead.prototype, {
_onSuggestionClicked: function onSuggestionClicked(type, $el) {
var datum;
if (datum = this.dropdown.getDatumForSuggestion($el)) {
this._select(datum);
}
},
_onCursorMoved: function onCursorMoved() {
var datum = this.dropdown.getDatumForCursor();
this.input.setInputValue(datum.value, true);
this.eventBus.trigger("cursorchanged", datum.raw, datum.datasetName);
},
_onCursorRemoved: function onCursorRemoved() {
this.input.resetInputValue();
this._updateHint();
},
_onDatasetRendered: function onDatasetRendered() {
this._updateHint();
},
_onOpened: function onOpened() {
this._updateHint();
this.eventBus.trigger("opened");
},
_onClosed: function onClosed() {
this.input.clearHint();
this.eventBus.trigger("closed");
},
_onFocused: function onFocused() {
this.isActivated = true;
this.dropdown.open();
},
_onBlurred: function onBlurred() {
this.isActivated = false;
this.dropdown.empty();
this.dropdown.close();
},
_onEnterKeyed: function onEnterKeyed(type, $e) {
var cursorDatum, topSuggestionDatum;
cursorDatum = this.dropdown.getDatumForCursor();
topSuggestionDatum = this.dropdown.getDatumForTopSuggestion();
if (cursorDatum) {
this._select(cursorDatum);
$e.preventDefault();
} else if (this.autoselect && topSuggestionDatum) {
this._select(topSuggestionDatum);
$e.preventDefault();
}
},
_onTabKeyed: function onTabKeyed(type, $e) {
var datum;
if (datum = this.dropdown.getDatumForCursor()) {
this._select(datum);
$e.preventDefault();
} else {
this._autocomplete(true);
}
},
_onEscKeyed: function onEscKeyed() {
this.dropdown.close();
this.input.resetInputValue();
},
_onUpKeyed: function onUpKeyed() {
var query = this.input.getQuery();
this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorUp();
this.dropdown.open();
},
_onDownKeyed: function onDownKeyed() {
var query = this.input.getQuery();
this.dropdown.isEmpty && query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.moveCursorDown();
this.dropdown.open();
},
_onLeftKeyed: function onLeftKeyed() {
this.dir === "rtl" && this._autocomplete();
},
_onRightKeyed: function onRightKeyed() {
this.dir === "ltr" && this._autocomplete();
},
_onQueryChanged: function onQueryChanged(e, query) {
this.input.clearHintIfInvalid();
query.length >= this.minLength ? this.dropdown.update(query) : this.dropdown.empty();
this.dropdown.open();
this._setLanguageDirection();
},
_onWhitespaceChanged: function onWhitespaceChanged() {
this._updateHint();
this.dropdown.open();
},
_setLanguageDirection: function setLanguageDirection() {
var dir;
if (this.dir !== (dir = this.input.getLanguageDirection())) {
this.dir = dir;
this.$node.css("direction", dir);
this.dropdown.setLanguageDirection(dir);
}
},
_updateHint: function updateHint() {
var datum, val, query, escapedQuery, frontMatchRegEx, match;
datum = this.dropdown.getDatumForTopSuggestion();
if (datum && this.dropdown.isVisible() && !this.input.hasOverflow()) {
val = this.input.getInputValue();
query = Input.normalizeQuery(val);
escapedQuery = _.escapeRegExChars(query);
frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
match = frontMatchRegEx.exec(datum.value);
match ? this.input.setHint(val + match[1]) : this.input.clearHint();
} else {
this.input.clearHint();
}
},
_autocomplete: function autocomplete(laxCursor) {
var hint, query, isCursorAtEnd, datum;
hint = this.input.getHint();
query = this.input.getQuery();
isCursorAtEnd = laxCursor || this.input.isCursorAtEnd();
if (hint && query !== hint && isCursorAtEnd) {
datum = this.dropdown.getDatumForTopSuggestion();
datum && this.input.setInputValue(datum.value);
this.eventBus.trigger("autocompleted", datum.raw, datum.datasetName);
}
},
_select: function select(datum) {
this.input.setQuery(datum.value);
this.input.setInputValue(datum.value, true);
this._setLanguageDirection();
this.eventBus.trigger("selected", datum.raw, datum.datasetName);
this.dropdown.close();
_.defer(_.bind(this.dropdown.empty, this.dropdown));
},
open: function open() {
this.dropdown.open();
},
close: function close() {
this.dropdown.close();
},
setVal: function setVal(val) {
val = _.toStr(val);
if (this.isActivated) {
this.input.setInputValue(val);
} else {
this.input.setQuery(val);
this.input.setInputValue(val, true);
}
this._setLanguageDirection();
},
getVal: function getVal() {
return this.input.getQuery();
},
destroy: function destroy() {
this.input.destroy();
this.dropdown.destroy();
destroyDomStructure(this.$node);
this.$node = null;
}
});
return Typeahead;
function buildDom(input, withHint) {
var $input, $wrapper, $dropdown, $hint;
$input = $(input);
$wrapper = $(html.wrapper).css(css.wrapper);
$dropdown = $(html.dropdown).css(css.dropdown);
$hint = $input.clone().css(css.hint).css(getBackgroundStyles($input));
$hint.val("").removeData().addClass("tt-hint").removeAttr("id name placeholder required").prop("readonly", true).attr({
autocomplete: "off",
spellcheck: "false",
tabindex: -1
});
$input.data(attrsKey, {
dir: $input.attr("dir"),
autocomplete: $input.attr("autocomplete"),
spellcheck: $input.attr("spellcheck"),
style: $input.attr("style")
});
$input.addClass("tt-input").attr({
autocomplete: "off",
spellcheck: false
}).css(withHint ? css.input : css.inputWithNoHint);
try {
!$input.attr("dir") && $input.attr("dir", "auto");
} catch (e) {}
return $input.wrap($wrapper).parent().prepend(withHint ? $hint : null).append($dropdown);
}
function getBackgroundStyles($el) {
return {
backgroundAttachment: $el.css("background-attachment"),
backgroundClip: $el.css("background-clip"),
backgroundColor: $el.css("background-color"),
backgroundImage: $el.css("background-image"),
backgroundOrigin: $el.css("background-origin"),
backgroundPosition: $el.css("background-position"),
backgroundRepeat: $el.css("background-repeat"),
backgroundSize: $el.css("background-size")
};
}
function destroyDomStructure($node) {
var $input = $node.find(".tt-input");
_.each($input.data(attrsKey), function(val, key) {
_.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
});
$input.detach().removeData(attrsKey).removeClass("tt-input").insertAfter($node);
$node.remove();
}
}();
(function() {
"use strict";
var old, typeaheadKey, methods;
old = $.fn.typeahead;
typeaheadKey = "ttTypeahead";
methods = {
initialize: function initialize(o, datasets) {
datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1);
o = o || {};
return this.each(attach);
function attach() {
var $input = $(this), eventBus, typeahead;
_.each(datasets, function(d) {
d.highlight = !!o.highlight;
});
typeahead = new Typeahead({
input: $input,
eventBus: eventBus = new EventBus({
el: $input
}),
withHint: _.isUndefined(o.hint) ? true : !!o.hint,
minLength: o.minLength,
autoselect: o.autoselect,
datasets: datasets
});
$input.data(typeaheadKey, typeahead);
}
},
open: function open() {
return this.each(openTypeahead);
function openTypeahead() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.open();
}
}
},
close: function close() {
return this.each(closeTypeahead);
function closeTypeahead() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.close();
}
}
},
val: function val(newVal) {
return !arguments.length ? getVal(this.first()) : this.each(setVal);
function setVal() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.setVal(newVal);
}
}
function getVal($input) {
var typeahead, query;
if (typeahead = $input.data(typeaheadKey)) {
query = typeahead.getVal();
}
return query;
}
},
destroy: function destroy() {
return this.each(unattach);
function unattach() {
var $input = $(this), typeahead;
if (typeahead = $input.data(typeaheadKey)) {
typeahead.destroy();
$input.removeData(typeaheadKey);
}
}
}
};
$.fn.typeahead = function(method) {
var tts;
if (methods[method] && method !== "initialize") {
tts = this.filter(function() {
return !!$(this).data(typeaheadKey);
});
return methods[method].apply(tts, [].slice.call(arguments, 1));
} else {
return methods.initialize.apply(this, arguments);
}
};
$.fn.typeahead.noConflict = function noConflict() {
$.fn.typeahead = old;
return this;
};
})();
})(window.jQuery); | ljharb/cdnjs | ajax/libs/typeahead.js/0.10.3/typeahead.jquery.js | JavaScript | mit | 48,446 |
/*
* /MathJax/jax/output/HTML-CSS/fonts/Neo-Euler/NonUnicode/Regular/Main.js
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.NeoEulerMathJax_NonUnicode={directory:"NonUnicode/Regular",family:"NeoEulerMathJax_NonUnicode",testString:"\u00A0\uE000\uE001\uE002\uE003\uE004\uE005\uE006\uE007\uE008\uE009\uE00A\uE00B\uE00C\uE00D",32:[0,0,333,0,0],160:[0,0,333,0,0],57344:[631,28,587,64,512],57345:[691,242,393,37,408],57346:[688,242,388,37,387],57347:[474,212,592,67,531],57348:[684,27,393,29,387],57349:[586,33,397,47,411],57350:[681,221,980,25,875],57351:[678,148,710,-5,624],57352:[502,11,592,41,533],57353:[489,0,592,54,548],57354:[491,0,592,44,564],57355:[488,193,592,36,523],57356:[495,198,592,13,565],57357:[481,191,592,18,518],57358:[704,12,592,48,548],57359:[479,198,592,54,591],57360:[715,5,592,45,542],57361:[488,195,592,29,549],57362:[704,10,378,54,254],57363:[684,34,497,73,430],57364:[616,30,498,35,433],57365:[681,257,333,30,339],57366:[681,242,326,30,324],57367:[470,214,503,51,444],57368:[687,20,333,25,315],57369:[578,21,334,29,348],57370:[474,26,500,8,514],57371:[493,13,367,10,365],57372:[493,246,367,-18,251],57373:[489,202,674,49,633],57374:[713,9,542,74,383],57375:[999,200,662,127,533],57376:[999,200,662,128,533],57377:[1599,200,754,137,616],57378:[1599,200,754,137,616],57379:[2199,200,846,151,694],57380:[2199,200,846,151,694],57381:[2799,200,908,165,742],57382:[2799,200,908,165,742],57383:[500,-226,1123,69,1053],57384:[275,-1,1123,69,1053],57385:[500,-226,1123,69,1053],57386:[275,-1,1123,69,1053],57387:[500,-1,1123,69,1053],57388:[500,-1,1123,69,1053],57389:[694,194,569,39,530],57390:[694,194,569,39,530],57391:[500,-1,1123,69,1053],57392:[773,194,1123,69,1101],57393:[694,273,1123,69,1101],57394:[612,112,1123,69,1026],57395:[612,112,1123,94,1051],57396:[694,170,754,19,732],57397:[670,194,754,19,732],57398:[612,112,1123,49,1071],57399:[773,194,1123,21,1053],57400:[694,273,1123,21,1053],57401:[441,10,1123,69,1053],57402:[911,0,1000,448,804],57403:[911,200,630,59,570],57404:[2022,200,631,21,623],57405:[800,200,1185,69,1084],57406:[1200,200,1615,69,1514],57407:[800,200,1185,85,1099],57408:[1200,200,1578,69,1508],57409:[911,200,630,59,570],57410:[2022,200,631,49,581],57411:[800,200,1185,85,1099],57412:[1200,200,1578,69,1508],57413:[770,270,569,39,528],57414:[770,270,754,19,732],57415:[103,252,466,-20,470],57416:[103,252,466,-4,486],57417:[356,0,466,-20,470],57418:[356,0,466,-4,486],57419:[631,28,662,97,555],57420:[691,242,464,70,448],57421:[688,242,459,70,427],57422:[474,212,667,100,574],57423:[684,27,464,62,427],57424:[692,-448,373,75,305],57425:[586,74,872,72,795],57426:[138,210,373,117,277],57427:[276,-236,874,72,796],57428:[119,15,372,127,273],57429:[720,192,607,76,538],57430:[713,9,616,107,423],57431:[1007,0,938,86,970],57432:[455,12,309,101,226],57433:[457,190,309,99,241],57434:[369,-132,873,80,808],57435:[693,11,460,87,428],57436:[688,31,927,62,876],57437:[685,31,1127,89,1014],57438:[677,32,801,104,776],57439:[685,29,1064,63,946],57440:[687,29,861,106,780],57441:[684,147,799,49,781],57442:[692,27,1009,107,893],57443:[684,127,931,32,800],57444:[683,25,731,64,667],57445:[681,142,729,24,659],57446:[682,26,868,52,861],57447:[684,28,865,63,811],57448:[686,33,1327,59,1289],57449:[681,33,1065,59,1019],57450:[726,29,1059,43,931],57451:[685,223,1060,51,995],57452:[726,82,1059,43,967],57453:[689,29,1060,51,1029],57454:[685,31,1061,116,956],57455:[691,30,868,63,846],57456:[689,39,931,48,920],57457:[687,29,1064,58,1017],57458:[682,30,1323,64,1296],57459:[682,35,929,65,884],57460:[689,214,1066,65,929],57461:[718,137,804,49,678],57462:[741,125,367,169,342],57463:[741,125,378,48,221],57464:[735,-452,605,34,573],57465:[472,32,678,113,631],57466:[691,32,664,120,546],57467:[473,26,536,121,464],57468:[632,29,663,31,553],57469:[471,28,544,114,470],57470:[681,242,458,70,427],57471:[473,208,669,48,584],57472:[687,203,691,122,549],57473:[686,26,401,34,366],57474:[683,207,401,13,275],57475:[683,25,537,66,473],57476:[682,24,406,134,353],57477:[476,31,1003,48,950],57478:[474,28,730,35,652],57479:[482,34,685,141,558],57480:[558,208,679,30,561],57481:[485,212,670,121,557],57482:[473,26,532,44,494],57483:[480,35,596,8,524],57484:[654,27,464,80,447],57485:[473,35,663,41,648],57486:[546,28,680,89,549],57487:[549,33,999,88,863],57488:[471,188,531,41,490],57489:[559,222,664,93,558],57490:[472,215,534,24,417],57491:[695,-432,308,57,260],57492:[704,10,482,101,319],57493:[684,34,603,113,503],57494:[616,30,605,73,507],57495:[681,257,430,72,409],57496:[681,242,423,73,393],57497:[470,214,610,89,517],57498:[687,20,431,68,384],57499:[578,21,431,71,418],57500:[474,26,605,41,593],57501:[493,13,607,78,531],57502:[469,1,607,83,535],57503:[474,-1,605,96,560],57504:[474,182,609,76,504],57505:[476,192,607,45,559],57506:[458,184,608,85,515],57507:[700,13,606,82,546],57508:[468,181,606,72,575],57509:[706,10,607,77,536],57510:[470,182,607,63,544],57511:[697,27,832,47,796],57512:[691,27,1030,71,905],57513:[686,24,720,90,694],57514:[690,27,955,51,834],57515:[686,24,772,117,722],57516:[686,155,721,40,705],57517:[692,25,904,93,796],57518:[667,133,840,18,730],57519:[686,27,662,61,612],57520:[686,139,663,14,602],57521:[681,27,780,42,776],57522:[686,27,779,60,729],57523:[692,27,1178,37,1151],57524:[686,29,952,49,922],57525:[729,27,952,34,835],57526:[692,219,944,26,896],57527:[729,69,950,32,874],57528:[686,27,948,47,918],57529:[689,27,949,80,844],57530:[703,27,781,51,761],57531:[697,27,758,-1,753],57532:[686,27,951,49,918],57533:[686,28,1175,30,1158],57534:[689,27,834,52,796],57535:[686,219,958,50,829],57536:[729,139,715,44,612],57537:[471,36,603,101,572],57538:[686,31,619,126,516],57539:[466,29,488,115,428],57540:[612,34,606,50,505],57541:[467,31,500,112,433],57542:[679,238,426,73,393],57543:[470,209,611,52,531],57544:[689,198,628,116,507],57545:[675,21,375,59,335],57546:[673,202,380,38,261],57547:[686,26,490,65,434],57548:[686,20,371,145,341],57549:[475,26,884,29,847],57550:[475,23,633,51,599],57551:[481,28,594,106,485],57552:[538,214,609,49,505],57553:[480,224,595,99,490],57554:[474,21,489,54,468],57555:[479,30,548,8,483],57556:[641,21,430,67,420],57557:[474,26,624,41,593],57558:[533,28,618,90,512],57559:[533,28,893,71,778],57560:[473,188,489,50,443],57561:[524,219,605,84,511],57562:[471,215,495,35,384],57563:[692,9,648,91,663],57564:[699,7,916,57,851],57565:[699,14,1119,116,982],57566:[694,13,987,52,921],57567:[700,14,774,60,711],57568:[690,14,983,64,918],57569:[699,1,840,63,750],57570:[707,6,929,64,864],57571:[685,0,1124,117,996],57572:[703,1,915,-1,871],57573:[700,5,1109,60,1044],57574:[476,18,842,130,819],57575:[676,194,827,149,702],57576:[475,201,767,29,713],57577:[672,11,700,120,582],57578:[471,7,703,124,620],57579:[674,129,634,118,589],57580:[470,197,773,44,621],57581:[677,14,770,124,646],57582:[469,11,449,156,411],57583:[471,12,699,153,645],57584:[679,8,713,64,648],57585:[474,196,768,136,731],57586:[473,6,759,60,689],57587:[689,126,703,112,660],57588:[523,4,787,52,778],57589:[474,196,728,145,649],57590:[475,11,827,126,774],57591:[497,7,696,66,668],57592:[472,2,740,35,653],57593:[672,196,1015,126,893],57594:[470,197,703,22,684],57595:[672,196,958,29,841],57596:[499,9,1123,117,999],57597:[472,16,643,146,575],57598:[676,8,760,32,699],57599:[547,11,1079,124,975],57600:[472,201,953,125,835],57601:[716,15,663,76,591],57602:[715,9,663,108,421],57603:[715,-5,663,48,609],57604:[708,8,663,59,573],57605:[708,12,663,34,597],57606:[694,12,663,52,572],57607:[704,12,663,80,599],57608:[696,15,663,86,628],57609:[720,5,663,78,582],57610:[707,10,663,84,592],57611:[531,36,914,97,800],57612:[531,36,914,117,820],57613:[696,18,764,127,640],57614:[687,14,967,35,927],57615:[703,2,855,76,731],57616:[711,18,924,126,851],57617:[698,1,1043,80,935],57618:[709,8,761,44,691],57619:[706,12,636,45,570],57620:[709,14,985,130,859],57621:[711,7,997,76,930],57622:[696,-1,566,84,454],57623:[705,192,562,81,481],57624:[702,12,878,82,826],57625:[702,5,739,78,673],57626:[701,16,1325,127,1258],57627:[713,3,1068,89,895],57628:[720,15,1024,110,928],57629:[699,6,787,85,705],57630:[714,197,1064,126,942],57631:[701,10,842,84,756],57632:[723,14,776,120,676],57633:[714,11,655,56,717],57634:[717,10,999,63,945],57635:[712,5,876,61,912],57636:[701,16,1290,47,1316],57637:[705,13,867,64,800],57638:[707,4,699,63,775],57639:[709,11,862,64,798],57640:[704,9,498,65,432],57641:[498,15,787,139,758],57642:[705,14,797,64,674],57643:[496,10,662,130,611],57644:[699,11,797,124,760],57645:[495,16,732,127,640],57646:[686,10,532,57,528],57647:[495,242,781,125,626],57648:[696,8,787,65,755],57649:[687,13,464,43,430],57650:[687,246,459,12,314],57651:[698,6,729,65,700],57652:[697,7,465,63,433],57653:[495,9,1140,37,1105],57654:[497,10,794,32,763],57655:[486,11,796,118,675],57656:[488,247,785,52,678],57657:[538,247,795,143,639],57658:[489,6,604,47,554],57659:[494,15,606,70,495],57660:[624,11,540,56,479],57661:[500,8,794,34,759],57662:[490,12,659,4,597],57663:[496,13,1065,23,1002],57664:[491,12,663,7,611],57665:[491,232,794,44,634],57666:[492,14,656,51,603],57667:[493,13,464,43,430],57668:[493,246,464,12,306],57669:[489,202,798,85,722],57670:[697,7,543,115,606],57671:[696,4,865,65,810],57672:[701,12,915,64,851],57673:[698,7,930,63,902],57674:[695,6,733,62,674],57675:[690,14,875,60,814],57676:[695,-2,789,86,709],57677:[697,11,869,54,805],57678:[686,-2,1001,113,876],57679:[694,1,854,-1,820],57680:[689,2,1048,59,985],57681:[468,20,803,126,791],57682:[698,202,808,159,674],57683:[470,198,747,3,689],57684:[694,9,626,94,526],57685:[471,11,681,130,585],57686:[695,136,638,126,586],57687:[466,199,692,-5,572],57688:[695,11,686,98,580],57689:[474,9,437,145,406],57690:[472,4,687,158,614],57691:[690,11,671,55,608],57692:[466,199,757,139,749],57693:[471,8,736,48,665],57694:[694,137,684,115,647],57695:[488,5,748,55,741],57696:[477,189,679,133,595],57697:[476,5,743,124,718],57698:[484,9,639,48,617],57699:[472,12,723,17,617],57700:[467,197,922,134,805],57701:[466,197,710,11,668],57702:[695,189,974,24,804],57703:[472,13,1021,107,914],57704:[471,15,609,119,517],57705:[698,14,683,13,621],57706:[541,12,1048,115,924],57707:[694,192,881,106,776],57708:[704,14,623,69,551],57709:[712,5,623,135,386],57710:[708,-2,623,45,564],57711:[702,17,623,51,535],57712:[704,5,623,30,565],57713:[687,11,623,45,537],57714:[700,13,623,82,563],57715:[694,8,623,86,589],57716:[706,10,623,76,552],57717:[702,9,623,76,553],57718:[699,7,692,120,579],57719:[680,10,930,59,871],57720:[686,1,800,88,680],57721:[699,15,866,129,790],57722:[686,-2,995,89,865],57723:[688,0,742,83,663],57724:[690,2,623,75,559],57725:[699,17,924,133,795],57726:[690,2,944,89,872],57727:[683,1,505,119,424],57728:[690,234,514,88,427],57729:[683,7,814,86,745],57730:[690,5,691,88,634],57731:[690,6,1239,120,1172],57732:[694,5,996,86,833],57733:[700,18,967,112,851],57734:[679,6,710,93,652],57735:[698,235,995,127,905],57736:[679,8,748,92,689],57737:[702,15,689,82,577],57738:[697,10,615,60,680],57739:[694,9,934,70,874],57740:[698,16,789,57,855],57741:[690,11,1174,46,1229],57742:[688,11,812,62,750],57743:[693,11,687,57,726],57744:[695,12,812,83,754],57745:[466,12,748,129,704],57746:[684,10,724,62,622],57747:[475,19,609,86,535],57748:[684,19,741,128,706],57749:[478,12,623,109,554],57750:[669,12,533,72,507],57751:[465,233,701,125,590],57752:[681,10,761,62,751],57753:[683,8,466,47,434],57754:[683,231,434,30,286],57755:[686,7,687,62,669],57756:[686,11,472,77,438],57757:[471,18,1093,64,1073],57758:[471,10,810,37,772],57759:[465,14,696,94,593],57760:[470,237,725,17,616],57761:[504,243,743,131,598],57762:[473,3,548,41,500],57763:[466,17,574,90,468],57764:[611,9,530,51,482],57765:[470,10,785,30,771],57766:[469,11,619,7,558],57767:[469,8,977,16,915],57768:[464,12,654,33,610],57769:[468,233,730,12,586],57770:[462,27,591,44,572],57771:[471,8,436,29,416],57772:[468,231,434,30,283],57773:[472,196,742,99,671],57774:[347,-178,684,56,630],57775:[409,-206,834,59,741],57776:[689,-1,936,119,810],57777:[711,17,1013,43,952],57778:[727,1,988,73,882],57779:[709,15,791,95,721],57780:[727,1,1067,62,975],57781:[708,12,799,97,704],57782:[731,14,871,65,890],57783:[705,138,794,88,675],57784:[699,12,1132,63,1091],57785:[703,18,666,62,573],57786:[701,137,674,65,610],57787:[709,9,1060,61,998],57788:[710,12,928,60,825],57789:[710,17,1252,61,1189],57790:[712,13,999,59,983],57791:[707,20,918,80,822],57792:[726,13,862,63,794],57793:[705,42,882,77,808],57794:[732,12,937,63,933],57795:[715,18,703,39,625],57796:[697,11,763,60,818],57797:[709,13,918,42,885],57798:[702,16,867,61,796],57799:[710,8,1261,61,1189],57800:[712,11,931,61,860],57801:[709,135,791,28,673],57802:[705,14,857,93,796],57803:[714,4,937,43,899],57804:[688,12,937,38,885],57805:[730,178,423,28,361],57806:[733,175,423,57,390],57807:[738,167,302,128,173],57808:[722,192,628,75,554],57809:[701,107,643,94,541],57810:[694,15,932,22,863],57811:[712,1,921,78,803],57812:[697,15,742,110,665],57813:[716,-4,999,90,894],57814:[702,12,749,109,628],57815:[699,15,795,74,833],57816:[697,130,744,112,623],57817:[690,8,1060,68,1017],57818:[685,14,547,62,497],57819:[692,129,633,63,560],57820:[690,12,993,64,928],57821:[685,7,869,60,724],57822:[699,13,1171,62,1117],57823:[706,7,936,63,937],57824:[686,18,860,111,746],57825:[710,11,807,81,752],57826:[694,24,810,112,727],57827:[712,6,877,68,834],57828:[702,12,674,63,575],57829:[693,6,724,60,777],57830:[699,16,868,59,812],57831:[709,9,812,62,752],57832:[702,5,1179,65,1119],57833:[706,9,871,88,814],57834:[702,136,734,59,598],57835:[696,11,803,97,745],57836:[502,11,667,74,576],57837:[489,0,667,87,591],57838:[491,0,667,77,607],57839:[488,193,667,69,565],57840:[495,198,667,45,608],57841:[481,191,667,50,560],57842:[704,12,667,81,591],57843:[479,198,667,87,635],57844:[715,5,667,78,585],57845:[488,195,667,62,592],57846:[465,-33,999,122,877],57847:[648,152,973,121,824],57848:[648,153,973,146,850],57849:[631,28,855,175,669],57850:[691,242,642,146,554],57851:[688,242,636,146,531],57852:[474,212,861,179,689],57853:[684,27,642,137,531],57854:[586,33,646,157,557],57855:[681,221,1288,132,1068],57856:[678,148,991,100,791],57857:[709,-406,450,151,297],57858:[695,-395,450,150,293],57859:[722,182,860,119,740],57860:[713,9,806,186,526],57861:[1008,0,1127,135,1137],57862:[455,12,453,158,294],57863:[457,190,453,155,312],57864:[369,-132,1101,162,963],57865:[693,11,628,151,527],57866:[688,31,1141,137,1015],57867:[685,31,1357,167,1164],57868:[677,32,1005,183,907],57869:[685,29,1289,138,1091],57870:[687,29,1070,185,911],57871:[684,147,1003,124,912],57872:[692,27,1229,186,1033],57873:[684,127,1145,105,933],57874:[683,25,929,139,790],57875:[681,142,927,96,782],57876:[682,26,1077,127,999],57877:[684,28,1074,138,945],57878:[686,33,1572,134,1460],57879:[681,33,1290,134,1170],57880:[726,29,1283,117,1074],57881:[685,223,1284,126,1143],57882:[726,82,1283,117,1114],57883:[689,29,1284,126,1180],57884:[685,31,1285,195,1102],57885:[691,30,1077,138,983],57886:[689,39,1145,123,1063],57887:[687,29,1289,132,1168],57888:[682,30,1568,139,1469],57889:[682,35,1143,140,1024],57890:[689,214,1291,140,1072],57891:[718,137,1008,124,801],57892:[741,130,491,145,354],57893:[739,132,491,120,334],57894:[735,-452,857,105,747],57895:[472,32,872,192,751],57896:[691,32,857,200,659],57897:[473,26,719,201,571],57898:[632,29,856,104,667],57899:[471,28,728,193,577],57900:[681,242,635,146,531],57901:[473,208,863,123,700],57902:[687,203,886,202,662],57903:[686,26,574,107,465],57904:[683,207,574,84,367],57905:[683,25,720,141,580],57906:[682,24,579,215,451],57907:[476,31,1223,123,1095],57908:[474,28,928,108,774],57909:[482,34,879,222,672],57910:[558,208,873,103,676],57911:[485,212,864,201,672],57912:[473,26,714,118,603],57913:[480,35,784,79,635],57914:[654,27,642,157,553],57915:[473,35,856,115,769],57916:[546,28,874,167,663],57917:[549,33,1218,166,1002],57918:[471,188,713,114,599],57919:[559,222,857,171,672],57920:[472,215,717,96,520],57921:[695,-432,488,116,359],57922:[704,10,647,162,402],57923:[684,34,790,185,614],57924:[616,30,791,139,616],57925:[681,257,593,133,504],57926:[681,242,585,133,486],57927:[470,214,797,158,629],57928:[687,20,593,127,475],57929:[578,21,594,132,515],57930:[474,26,794,107,714],57931:[493,13,795,146,644],57932:[469,1,795,152,649],57933:[474,-1,795,168,679],57934:[474,182,795,143,613],57935:[476,192,795,109,675],57936:[458,184,795,153,626],57937:[700,13,795,151,662],57938:[468,181,795,141,695],57939:[706,10,795,145,650],57940:[470,182,795,129,659],57941:[697,27,1054,123,948],57942:[691,27,1278,156,1075],57943:[686,24,928,168,833],57944:[690,27,1191,129,992],57945:[686,24,988,200,866],57946:[686,155,927,110,843],57947:[692,25,1136,176,950],57948:[667,133,1058,87,871],57949:[686,27,858,131,737],57950:[686,139,856,75,723],57951:[681,27,995,116,925],57952:[686,27,993,135,871],57953:[692,27,1452,129,1356],57954:[686,29,1192,132,1093],57955:[729,27,1187,110,992],57956:[692,219,1181,104,1062],57957:[729,69,1187,110,1037],57958:[686,27,1187,129,1088],57959:[689,27,1187,164,1004],57960:[703,27,996,126,908],57961:[697,27,968,66,896],57962:[686,27,1191,132,1088],57963:[686,28,1449,122,1363],57964:[689,27,1056,129,948],57965:[686,219,1194,129,986],57966:[729,139,916,110,737],57967:[471,36,794,174,693],57968:[686,31,809,200,629],57969:[466,29,660,183,528],57970:[612,34,791,113,614],57971:[467,31,674,181,534],57972:[679,238,588,133,486],57973:[470,209,797,116,643],57974:[689,198,819,188,619],57975:[675,21,528,114,419],57976:[673,202,530,86,332],57977:[686,26,660,126,533],57978:[686,20,528,213,429],57979:[475,26,1113,105,1006],57980:[475,23,825,119,722],57981:[481,28,779,176,593],57982:[538,214,794,111,613],57983:[480,224,780,168,599],57984:[474,21,660,115,570],57985:[479,30,724,63,585],57986:[641,21,593,128,516],57987:[474,26,814,107,714],57988:[533,28,807,158,624],57989:[533,28,1121,150,929],57990:[473,188,659,109,541],57991:[524,219,791,151,621],57992:[471,215,662,89,474],57993:[692,9,831,168,777],57994:[699,7,1117,132,976],57995:[699,14,1332,194,1117],57996:[694,13,1192,126,1052],57997:[700,14,966,135,828],57998:[690,14,1189,139,1048],57999:[699,1,1035,137,869],58000:[707,6,1131,139,990],58001:[685,0,1338,195,1130],58002:[703,1,1115,70,998],58003:[700,5,1322,135,1181],58004:[476,18,1038,209,943],58005:[676,194,1022,229,818],58006:[475,201,958,102,830],58007:[672,11,887,199,691],58008:[471,7,890,202,730],58009:[674,129,816,197,698],58010:[470,197,965,118,731],58011:[677,14,961,202,758],58012:[469,11,620,237,509],58013:[471,12,886,234,757],58014:[679,8,901,139,761],58015:[474,196,959,215,849],58016:[473,6,950,135,804],58017:[689,126,890,190,773],58018:[523,4,980,126,899],58019:[474,196,917,226,762],58020:[475,11,1022,205,895],58021:[497,7,882,141,782],58022:[472,2,930,108,766],58023:[672,196,1222,205,1021],58024:[470,197,890,95,799],58025:[672,196,1162,102,966],58026:[499,9,1337,195,1134],58027:[472,16,827,227,683],58028:[676,8,951,105,815],58029:[547,11,1291,202,1108],58030:[472,201,1156,204,960],58031:[716,15,848,151,700],58032:[715,9,848,186,519],58033:[715,-5,848,122,719],58034:[708,8,848,134,680],58035:[708,12,848,107,707],58036:[694,12,848,126,679],58037:[704,12,848,156,708],58038:[696,15,848,163,740],58039:[720,5,848,154,691],58040:[707,10,848,161,701],58041:[531,36,1101,168,914],58042:[531,36,1101,189,935],58043:[696,18,955,206,752],58044:[687,14,1171,108,1057],58045:[703,2,1052,151,849],58046:[711,18,1125,205,976],58047:[698,1,1252,156,1065],58048:[709,8,952,118,807],58049:[706,12,819,119,678],58050:[709,14,1190,209,985],58051:[711,7,1202,151,1061],58052:[696,-1,744,161,554],58053:[705,192,740,157,583],58054:[702,12,1076,158,949],58055:[702,5,929,154,787],58056:[701,16,1552,206,1410],58057:[713,3,1279,165,1024],58058:[720,15,1231,189,1059],58059:[699,6,980,162,821],58060:[714,197,1274,205,1074],58061:[701,10,1038,161,875],58062:[723,14,968,199,791],58063:[714,11,839,131,833],58064:[717,10,1205,137,1076],58065:[712,5,1074,136,1041],58066:[701,16,1515,121,1471],58067:[705,13,1064,139,923],58068:[707,4,886,137,896],58069:[709,11,1060,139,920],58070:[704,9,659,133,523],58071:[498,15,980,219,878],58072:[705,14,990,139,788],58073:[496,10,846,209,721],58074:[699,11,990,202,880],58075:[495,16,921,206,752],58076:[686,10,708,132,632],58077:[495,242,973,204,737],58078:[696,8,980,140,875],58079:[687,13,635,117,528],58080:[687,246,631,84,405],58081:[698,6,918,140,816],58082:[697,7,636,137,532],58083:[495,9,1356,111,1247],58084:[497,10,987,105,883],58085:[486,11,989,197,789],58086:[488,247,977,126,793],58087:[538,247,988,223,751],58088:[489,6,785,121,661],58089:[494,15,787,146,598],58090:[624,11,716,131,581],58091:[500,8,987,107,879],58092:[490,12,843,75,706],58093:[496,13,1276,96,1137],58094:[491,12,848,78,721],58095:[491,232,987,118,745],58096:[492,14,841,125,713],58097:[493,13,635,117,528],58098:[493,246,635,84,396],58099:[489,202,991,162,839],58100:[697,7,707,186,708],58101:[696,4,1049,133,924],58102:[701,12,1102,132,968],58103:[698,7,1118,131,1022],58104:[695,6,909,129,780],58105:[690,14,1060,128,929],58106:[695,-2,969,156,817],58107:[697,11,1053,121,919],58108:[686,-2,1193,185,995],58109:[694,1,1037,63,935],58110:[689,2,1244,127,1110],58111:[468,20,983,198,905],58112:[698,202,988,233,780],58113:[470,198,923,67,795],58114:[694,9,795,164,623],58115:[471,11,854,203,685],58116:[695,136,808,198,686],58117:[466,199,866,59,672],58118:[695,11,858,168,680],58119:[474,9,594,218,495],58120:[472,4,860,231,716],58121:[690,11,843,122,709],58122:[466,199,934,212,859],58123:[471,8,912,115,770],58124:[694,137,857,186,751],58125:[488,5,924,122,851],58126:[477,189,851,205,696],58127:[476,5,920,195,827],58128:[484,9,809,115,720],58129:[472,12,898,83,720],58130:[467,197,1109,206,919],58131:[466,197,885,75,774],58132:[695,189,1098,89,918],58133:[472,13,1215,177,1034],58134:[471,15,777,191,613],58135:[698,14,856,78,723],58136:[541,12,1244,186,1045],58137:[694,192,1066,176,888],58138:[704,14,792,138,649],58139:[712,5,792,207,474],58140:[708,-2,792,111,663],58141:[702,17,792,119,632],58142:[704,5,792,96,665],58143:[687,11,792,111,635],58144:[700,13,792,151,662],58145:[694,8,792,156,690],58146:[706,10,792,145,650],58147:[702,9,792,145,651],58148:[699,7,866,192,679],58149:[680,10,1118,127,989],58150:[686,1,980,157,786],58151:[699,15,1050,201,903],58152:[686,-2,1187,158,983],58153:[688,0,918,152,768],58154:[690,2,792,144,657],58155:[699,17,1112,205,908],58156:[690,2,1133,159,990],58157:[683,1,666,191,515],58158:[690,234,676,157,518],58159:[683,7,995,156,855],58160:[690,5,864,157,738],58161:[690,6,1446,192,1309],58162:[694,5,1188,156,949],58163:[700,18,1157,183,968],58164:[679,6,885,163,757],58165:[698,235,1187,199,1025],58166:[679,8,924,162,795],58167:[702,15,862,151,677],58168:[697,10,784,128,787],58169:[694,9,1122,138,993],58170:[698,16,969,125,972],58171:[690,11,1377,113,1369],58172:[688,11,993,129,860],58173:[693,11,860,125,835],58174:[695,12,993,152,865],58175:[466,12,924,202,812],58176:[684,10,899,129,725],58177:[475,19,777,156,632],58178:[684,19,917,200,813],58179:[478,12,792,180,653],58180:[669,12,696,140,603],58181:[465,233,875,197,690],58182:[681,10,939,129,862],58183:[683,8,626,114,525],58184:[683,231,591,96,368],58185:[686,7,860,129,775],58186:[686,11,632,146,529],58187:[471,18,1292,132,1203],58188:[471,10,990,103,884],58189:[465,14,869,164,693],58190:[470,237,900,83,718],58191:[504,243,920,203,699],58192:[473,3,712,108,595],58193:[466,17,740,159,561],58194:[611,9,693,118,576],58195:[470,10,964,96,883],58196:[469,11,788,72,656],58197:[469,8,1168,81,1035],58198:[464,12,825,99,711],58199:[468,233,905,77,686],58200:[462,27,758,111,672],58201:[471,8,593,95,506],58202:[468,231,591,96,365],58203:[472,196,918,169,776],58204:[347,-178,855,123,733],58205:[409,-206,1014,127,851],58206:[689,-1,1122,191,924],58207:[711,17,1212,116,1077],58208:[727,1,1186,148,1002],58209:[709,15,978,172,833],58210:[727,1,1269,137,1101],58211:[708,12,986,174,815],58212:[731,14,1063,140,1011],58213:[705,138,981,164,784],58214:[699,12,1338,138,1224],58215:[703,18,846,137,677],58216:[701,137,855,140,715],58217:[709,9,1262,136,1125],58218:[710,12,1123,134,942],58219:[710,17,1465,136,1327],58220:[712,13,1197,133,1110],58221:[707,20,1112,156,939],58222:[726,13,1052,138,910],58223:[705,42,1074,152,924],58224:[732,12,1132,138,1056],58225:[715,18,885,113,731],58226:[697,11,949,134,935],58227:[709,13,1112,115,1006],58228:[702,16,1058,136,912],58229:[710,8,1474,136,1327],58230:[712,11,1126,136,980],58231:[709,135,978,100,782],58232:[705,14,1048,169,912],58233:[714,4,1124,110,1019],58234:[688,12,1124,104,1004],58235:[730,178,578,93,447],58236:[733,175,578,125,479],58237:[738,167,449,200,248],58238:[722,192,795,144,653],58239:[701,107,812,164,638],58240:[694,15,1118,87,981],58241:[712,1,1107,147,917],58242:[697,15,916,181,770],58243:[716,-4,1190,159,1014],58244:[702,12,923,180,731],58245:[699,15,972,143,949],58246:[697,130,918,183,726],58247:[690,8,1254,137,1144],58248:[685,14,710,129,591],58249:[692,129,801,131,659],58250:[690,12,1182,132,1050],58251:[685,7,1052,128,833],58252:[699,13,1372,129,1250],58253:[706,7,1122,131,1059],58254:[686,18,1042,182,857],58255:[710,11,986,150,863],58256:[694,24,988,183,836],58257:[712,6,1060,137,950],58258:[702,12,844,131,674],58259:[693,6,897,128,889],58260:[699,16,1050,127,926],58261:[709,9,990,129,863],58262:[702,5,1380,133,1253],58263:[706,9,1053,157,929],58264:[702,136,908,127,699],58265:[696,11,981,167,855],58266:[502,11,861,150,691],58267:[489,0,861,164,708],58268:[491,0,861,153,725],58269:[488,193,861,145,680],58270:[495,198,861,119,726],58271:[481,191,861,125,675],58272:[704,12,861,158,708],58273:[586,33,468,80,451],58274:[690,11,548,206,342],58275:[681,221,1063,58,924],58276:[698,11,1078,156,978],58277:[678,148,788,27,668],58278:[709,-406,307,96,228],58279:[695,-395,307,95,224],58280:[690,11,392,141,266],58281:[698,11,852,74,821],58282:[695,-436,305,121,193],58283:[738,187,488,161,365],58284:[736,189,490,133,341],58285:[695,-436,448,179,258],58286:[738,186,697,233,493],58287:[735,187,697,198,468],58288:[107,192,537,212,378],58289:[275,-236,1227,135,1087],58290:[102,15,537,195,359],58291:[479,198,861,164,755],58292:[715,5,861,154,701],58293:[488,195,861,137,709],58294:[467,-33,1187,193,994],58295:[648,152,1161,198,944],58296:[648,150,1125,219,967],58297:[692,-449,537,117,408],58298:[598,83,1227,138,1092],58299:[598,84,1227,135,1092],58300:[599,83,1227,135,1092],58301:[586,74,872,72,796],58302:[586,74,872,72,796],58303:[119,15,925,99,826],58304:[102,15,1136,178,958],58305:[911,0,1000,195,551],58306:[911,0,1000,448,804],58307:[912,-1,1000,195,551],58308:[1824,0,1000,195,551],58309:[1824,0,1000,448,804],58310:[324,0,1000,448,551],58311:[694,194,348,39,310],58312:[694,194,348,39,310],58313:[694,194,348,39,310],58314:[694,194,348,39,310],58315:[610,109,1123,69,1053],58316:[610,109,1123,69,1053],58317:[689,2,1244,127,1110],58318:[696,4,1049,133,924],58319:[689,2,1048,59,985],58320:[696,4,865,65,810],58321:[347,-178,855,123,733],58322:[347,-178,684,56,630],58323:[559,-38,440,93,370],58324:[559,-38,857,93,787],58325:[559,-38,1274,93,1204],58326:[559,-38,1691,93,1621],58327:[559,-38,440,93,370],58328:[559,-38,857,93,787],58329:[559,-38,1274,93,1204],58330:[578,78,769,108,635],58331:[720,192,769,108,635],58332:[578,78,769,132,659],58333:[720,192,769,132,659],58334:[603,103,944,159,753],58335:[722,182,944,159,781],58336:[603,103,944,187,781],58337:[722,182,944,160,781],58338:[722,182,1101,162,963],58339:[720,192,873,80,808],58340:[720,192,999,122,877],58341:[722,182,1187,193,994],58342:[599,-5,769,78,689],58343:[575,19,769,78,689],58344:[606,-6,944,125,816],58345:[578,22,944,125,816],58346:[578,78,892,108,758],58347:[578,78,892,132,782],58348:[685,195,892,108,758],58349:[685,195,892,132,782],58350:[720,192,892,108,758],58351:[720,192,892,132,782],58352:[746,244,892,108,758],58353:[746,244,892,132,782],58354:[685,249,892,108,758],58355:[685,249,892,132,782],58356:[603,103,1083,159,892],58357:[603,103,1083,187,920],58358:[719,228,1083,159,892],58359:[719,228,1083,187,920],58360:[722,182,1083,159,892],58361:[722,182,1083,187,920],58362:[782,269,1083,159,892],58363:[782,269,1083,187,920],58364:[719,299,1083,159,892],58365:[719,299,1083,187,920],58366:[302,-185,1136,178,958],58367:[319,-185,925,99,826],58368:[607,-64,749,93,653],58369:[624,-71,934,170,768],58370:[607,-64,749,93,653],58371:[624,-71,934,170,768],58372:[362,-245,537,186,350],58373:[379,-245,372,113,259],58374:[698,97,449,200,248],58375:[698,97,302,128,173],58376:[735,235,462,134,380],58377:[735,235,462,79,326],58378:[734,234,597,186,466],58379:[734,234,597,127,407],58380:[738,167,676,200,476],58381:[738,167,517,128,389],58382:[911,200,990,59,960],58383:[911,200,1380,59,1350],58384:[911,200,1770,59,1740],58385:[679,5,646,18,626],58386:[694,0,646,101,566],58387:[507,3,892,193,701],58388:[562,61,874,72,796],58389:[522,22,585,19,563],58390:[619,118,892,77,815],58391:[619,118,892,77,815],58392:[619,118,892,77,815],58393:[619,118,892,77,815],58394:[619,118,892,77,815],58395:[714,214,1138,77,1061],58396:[465,-36,585,77,507],58397:[465,-36,585,77,507],58398:[678,6,805,58,743],58399:[694,0,805,153,677],58400:[538,38,1083,255,831],58401:[584,84,1232,135,1087],58402:[557,57,736,59,673],58403:[667,167,1083,125,958],58404:[667,167,1083,125,958],58405:[667,167,1083,125,958],58406:[667,167,1083,125,958],58407:[667,167,1083,125,958],58408:[716,216,1361,125,1236],58409:[493,-7,736,125,611],58410:[493,-7,736,125,611],58411:[802,110,646,93,566],58412:[800,104,805,97,718],58413:[575,19,769,78,689],58414:[578,22,943,125,816],58415:[685,195,1000,118,782],58416:[685,195,1000,108,772],58417:[719,228,1000,171,920],58418:[719,228,1000,159,909],58419:[681,10,761,55,751],58420:[681,10,939,115,862],58421:[699,7,916,57,851],58422:[699,7,1117,132,976],58423:[500,-1,1123,69,1053],58424:[500,-1,1123,70,1054],58425:[588,-1,1123,70,1053],58426:[588,-1,1123,70,1053]};MathJax.Callback.Queue(["initFont",MathJax.OutputJax["HTML-CSS"],"NeoEulerMathJax_NonUnicode"],["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/NonUnicode/Regular/Main.js"]);
| vanderlee/cdnjs | ajax/libs/mathjax/2.3/jax/output/HTML-CSS/fonts/Neo-Euler/NonUnicode/Regular/Main.js | JavaScript | mit | 30,551 |
/*
* /MathJax/jax/output/HTML-CSS/fonts/Gyre-Termes/Normal/Regular/Main.js
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
MathJax.OutputJax["HTML-CSS"].FONTDATA.FONTS.GyreTermesMathJax_Normal={directory:"Normal/Regular",family:"GyreTermesMathJax_Normal",testString:"\u00A0\u210E\uD835\uDC00\uD835\uDC01\uD835\uDC02\uD835\uDC03\uD835\uDC04\uD835\uDC05\uD835\uDC06\uD835\uDC07\uD835\uDC08\uD835\uDC09\uD835\uDC0A\uD835\uDC0B\uD835\uDC0C",32:[0,0,250,0,0],160:[0,0,250,0,0],8462:[683,9,500,19,478],119808:[690,0,722,9,689],119809:[676,0,667,16,619],119810:[691,19,722,49,687],119811:[676,0,722,14,690],119812:[676,0,667,16,641],119813:[676,0,611,16,583],119814:[691,19,778,37,755],119815:[676,0,778,21,759],119816:[676,0,389,20,370],119817:[676,96,500,3,479],119818:[676,0,778,30,769],119819:[676,0,667,19,638],119820:[676,0,944,14,921],119821:[676,18,722,16,701],119822:[691,19,778,35,743],119823:[676,0,611,16,600],119824:[691,176,778,35,743],119825:[676,0,722,26,715],119826:[692,19,556,35,513],119827:[676,0,667,31,636],119828:[676,19,722,16,701],119829:[676,18,722,16,701],119830:[676,15,1000,19,981],119831:[676,0,722,16,699],119832:[676,0,722,15,699],119833:[676,0,667,28,634],119834:[473,14,500,25,488],119835:[676,14,556,17,521],119836:[473,14,444,25,430],119837:[676,14,556,25,534],119838:[473,14,444,25,426],119839:[691,0,333,14,389],119840:[473,206,500,28,483],119841:[676,0,556,16,534],119842:[687,0,278,16,255],119843:[687,203,333,-57,266],119844:[676,0,556,22,543],119845:[676,0,278,16,255],119846:[473,0,833,16,814],119847:[473,0,556,21,539],119848:[473,14,500,25,476],119849:[473,205,556,19,524],119850:[473,205,556,34,536],119851:[473,0,444,29,434],119852:[473,14,389,25,361],119853:[630,12,333,20,332],119854:[461,14,556,16,537],119855:[461,14,500,21,485],119856:[461,14,722,23,707],119857:[461,0,500,12,484],119858:[461,205,500,16,480],119859:[461,0,444,21,420],119860:[668,0,611,-51,564],119861:[653,0,611,-8,588],119862:[666,18,667,66,689],119863:[653,0,722,-8,700],119864:[653,0,611,-1,634],119865:[653,0,611,8,645],119866:[666,18,722,52,722],119867:[653,0,722,-8,767],119868:[653,0,333,-8,384],119869:[653,18,444,-6,491],119870:[653,0,667,7,722],119871:[653,0,556,-8,559],119872:[653,0,833,-18,873],119873:[653,15,667,-20,727],119874:[666,18,722,60,699],119875:[653,0,611,0,605],119876:[666,182,722,59,699],119877:[653,0,611,-13,588],119878:[667,18,500,17,508],119879:[653,0,556,59,633],119880:[653,18,722,102,765],119881:[653,18,611,76,688],119882:[653,18,833,71,906],119883:[653,0,611,-29,655],119884:[653,0,556,78,633],119885:[653,0,556,-6,606],119886:[441,11,500,17,476],119887:[683,11,500,23,473],119888:[441,11,444,30,425],119889:[683,13,500,15,527],119890:[441,11,444,31,412],119891:[678,207,278,-147,424],119892:[441,206,500,8,469],119894:[643,11,278,49,276],119895:[643,207,278,-124,301],119896:[683,11,444,14,461],119897:[683,11,278,41,279],119898:[441,9,722,12,704],119899:[441,9,500,14,474],119900:[441,11,500,27,468],119901:[441,205,500,-75,469],119902:[441,205,500,25,483],119903:[441,0,389,45,412],119904:[442,13,389,16,366],119905:[546,11,278,37,296],119906:[441,11,500,42,475],119907:[441,18,444,21,426],119908:[441,18,667,16,648],119909:[441,11,444,-27,447],119910:[441,206,444,-24,426],119911:[428,81,389,-2,380],119912:[683,0,667,-67,593],119913:[669,0,667,-24,624],119914:[685,18,667,32,677],119915:[669,0,722,-46,685],119916:[669,0,667,-27,653],119917:[669,0,667,-13,660],119918:[685,18,722,21,706],119919:[669,0,778,-24,799],119920:[669,0,389,-32,406],119921:[669,99,500,-46,524],119922:[669,0,667,-21,702],119923:[669,0,611,-22,590],119924:[669,12,889,-29,917],119925:[669,15,722,-27,748],119926:[685,18,722,27,691],119927:[669,0,611,-27,613],119928:[685,208,722,27,691],119929:[669,0,667,-29,623],119930:[685,18,556,2,526],119931:[669,0,611,50,650],119932:[669,18,722,67,744],119933:[669,18,667,65,715],119934:[669,18,889,65,940],119935:[669,0,667,-24,694],119936:[669,0,611,73,659],119937:[669,0,611,-11,590],119938:[462,14,500,-21,455],119939:[699,13,500,-14,444],119940:[462,13,444,-5,392],119941:[699,13,500,-21,517],119942:[462,13,444,5,398],119943:[698,205,333,-169,446],119944:[462,203,500,-52,478],119945:[699,9,556,-13,498],119946:[658,9,278,2,266],119947:[658,207,278,-189,284],119948:[699,8,500,-23,483],119949:[699,9,278,2,290],119950:[462,9,778,-14,722],119951:[462,9,556,-6,493],119952:[462,13,500,-3,441],119953:[462,205,500,-120,446],119954:[462,205,500,1,471],119955:[462,0,389,-21,389],119956:[462,13,389,-19,333],119957:[594,9,278,-11,281],119958:[462,9,556,15,492],119959:[462,13,444,16,401],119960:[462,13,667,16,614],119961:[462,13,500,-46,469],119962:[462,205,444,-94,392],119963:[449,78,389,-43,368],120484:[441,11,278,49,235],120485:[441,207,278,-124,246],120488:[690,0,840,80,760],120489:[676,0,763,80,683],120490:[676,0,737,80,657],120491:[690,0,761,80,681],120492:[676,0,785,80,705],120493:[676,0,766,80,686],120494:[676,0,898,80,818],120495:[691,19,868,80,788],120496:[676,0,510,80,430],120497:[676,0,899,80,819],120498:[690,0,840,80,760],120499:[676,0,1067,80,987],120500:[676,18,845,80,765],120501:[662,0,731,80,651],120502:[691,19,868,80,788],120503:[676,0,898,80,818],120504:[676,0,744,80,664],120505:[691,19,868,80,788],120506:[662,0,784,80,704],120507:[676,0,765,80,685],120508:[676,0,848,80,768],120509:[676,0,814,80,734],120510:[676,0,843,80,763],120511:[676,0,880,80,800],120512:[691,0,850,80,770],120513:[680,10,761,80,681],120514:[473,14,679,80,599],120515:[691,217,650,80,570],120516:[473,232,720,80,640],120517:[691,14,666,80,586],120518:[473,14,573,80,493],120519:[667,215,546,80,466],120520:[473,218,673,80,593],120521:[691,14,640,80,560],120522:[473,14,520,80,440],120523:[473,14,769,80,689],120524:[691,14,720,80,640],120525:[461,218,690,80,610],120526:[473,11,665,80,585],120527:[667,215,544,80,464],120528:[473,14,611,80,531],120529:[481,14,715,80,635],120530:[473,218,616,80,536],120531:[473,215,545,80,465],120532:[471,14,674,80,594],120533:[481,16,655,80,575],120534:[473,14,640,80,560],120535:[476,218,812,80,732],120536:[473,232,720,80,640],120537:[473,218,880,80,800],120538:[475,14,789,80,709],120539:[691,14,616,80,536],120540:[482,14,522,80,442],120541:[693,14,828,80,748],120542:[473,14,649,80,569],120543:[677,218,832,80,752],120544:[473,217,616,80,536],120545:[481,14,955,80,875],120546:[668,0,775,80,695],120547:[653,0,756,80,676],120548:[662,0,868,80,788],120549:[668,0,686,80,606],120550:[653,0,795,80,715],120551:[653,0,772,80,692],120552:[653,0,935,80,855],120553:[666,18,799,80,719],120554:[653,0,552,80,472],120555:[653,0,875,80,795],120556:[668,0,775,80,695],120557:[653,0,1051,80,971],120558:[653,15,907,80,827],120559:[653,0,822,80,742],120560:[666,18,799,80,719],120561:[653,0,935,80,855],120562:[653,0,765,80,685],120563:[666,18,799,80,719],120564:[653,0,848,80,768],120565:[653,0,734,80,654],120566:[653,0,798,80,717],120567:[653,0,708,79,627],120568:[653,0,844,80,764],120569:[653,0,770,80,690],120570:[649,0,855,80,774],120571:[658,10,686,80,606],120572:[441,16,645,79,565],120573:[645,208,694,80,614],120574:[442,224,684,80,604],120575:[645,15,630,80,550],120576:[441,15,568,79,487],120577:[639,201,591,80,510],120578:[441,208,581,80,500],120579:[645,15,577,80,496],120580:[441,16,389,80,309],120581:[441,14,677,80,596],120582:[645,17,672,80,592],120583:[426,209,685,80,605],120584:[441,15,604,80,524],120585:[639,201,594,80,514],120586:[441,11,601,80,521],120587:[452,15,766,80,686],120588:[441,209,654,80,573],120589:[441,201,582,80,501],120590:[452,15,658,80,578],120591:[452,15,647,80,567],120592:[441,15,588,80,508],120593:[441,209,678,80,598],120594:[441,226,806,80,726],120595:[441,209,768,79,688],120596:[444,15,763,79,682],120597:[645,16,586,79,505],120598:[441,15,524,79,444],120599:[645,15,696,80,615],120600:[441,15,654,79,574],120601:[630,208,698,79,617],120602:[441,208,576,79,496],120603:[452,20,906,80,826],120604:[683,0,820,80,740],120605:[669,0,808,80,728],120606:[676,0,918,80,838],120607:[683,0,735,80,655],120608:[669,0,840,80,760],120609:[669,0,761,80,681],120610:[669,0,983,80,903],120611:[685,18,844,80,764],120612:[669,0,598,80,518],120613:[669,0,883,80,803],120614:[683,0,820,80,740],120615:[669,12,1106,80,1026],120616:[669,15,935,80,855],120617:[662,0,874,80,794],120618:[685,18,824,80,744],120619:[669,0,983,80,903],120620:[669,0,800,80,720],120621:[685,18,844,80,764],120622:[662,0,909,80,829],120623:[669,0,760,80,680],120624:[676,0,786,80,705],120625:[676,0,786,79,706],120626:[669,0,878,80,798],120627:[676,0,860,80,780],120628:[691,0,892,80,812],120629:[673,10,735,80,655],120630:[473,14,728,80,648],120631:[691,217,791,80,710],120632:[473,232,751,80,671],120633:[691,14,697,80,617],120634:[473,14,624,80,544],120635:[667,215,604,79,523],120636:[473,218,652,80,571],120637:[691,14,659,79,579],120638:[473,14,443,80,363],120639:[473,14,747,80,666],120640:[691,14,746,80,666],120641:[461,218,757,80,677],120642:[473,11,673,80,592],120643:[667,215,615,79,535],120644:[473,13,608,80,528],120645:[481,14,821,80,741],120646:[473,218,731,80,650],120647:[473,215,610,79,530],120648:[471,14,742,79,662],120649:[481,16,705,80,625],120650:[473,14,648,80,567],120651:[476,218,805,79,724],120652:[473,232,877,80,797],120653:[473,218,874,80,794],120654:[475,14,772,80,692],120655:[691,14,670,80,589],120656:[482,14,580,80,500],120657:[693,14,798,80,717],120658:[473,14,714,80,633],120659:[677,218,822,79,742],120660:[473,217,673,80,593],120661:[481,14,985,80,905],120782:[688,13,500,24,476],120783:[688,0,500,65,442],120784:[688,0,500,17,478],120785:[688,14,500,16,468],120786:[688,0,500,19,475],120787:[676,8,500,22,470],120788:[688,13,500,28,475],120789:[676,0,500,17,477],120790:[688,13,500,28,472],120791:[688,13,500,26,473]};MathJax.Callback.Queue(["initFont",MathJax.OutputJax["HTML-CSS"],"GyreTermesMathJax_Normal"],["loadComplete",MathJax.Ajax,MathJax.OutputJax["HTML-CSS"].fontDir+"/Normal/Regular/Main.js"]);
| kevinsproles/cdnjs | ajax/libs/mathjax/2.3/jax/output/HTML-CSS/fonts/Gyre-Termes/Normal/Regular/Main.js | JavaScript | mit | 10,442 |
"use strict";angular.module("ngLocale",[],["$provide",function(a){var d={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};function c(f){f=f+"";var e=f.indexOf(".");return(e==-1)?0:f.length-e-1}function b(j,e){var g=e;if(undefined===g){g=Math.min(c(j),3)}var i=Math.pow(10,g);var h=((j*i)|0)%i;return{v:g,f:h}}a.value("$locale",{DATETIME_FORMATS:{AMPMS:["KI","UT"],DAY:["Kiumia","Njumatatu","Njumaine","Njumatano","Aramithi","Njumaa","NJumamothii"],ERANAMES:["Mbere ya Kristo","Thutha wa Kristo"],ERAS:["MK","TK"],FIRSTDAYOFWEEK:0,MONTH:["Mweri wa mbere","Mweri wa ka\u0129ri","Mweri wa kathat\u0169","Mweri wa kana","Mweri wa gatano","Mweri wa gatantat\u0169","Mweri wa m\u0169gwanja","Mweri wa kanana","Mweri wa kenda","Mweri wa ik\u0169mi","Mweri wa ik\u0169mi na \u0169mwe","Mweri wa ik\u0169mi na Ka\u0129r\u0129"],SHORTDAY:["Kma","Tat","Ine","Tan","Arm","Maa","NMM"],SHORTMONTH:["Mbe","Kai","Kat","Kan","Gat","Gan","Mug","Knn","Ken","Iku","Imw","Igi"],WEEKENDRANGE:[5,6],fullDate:"EEEE, d MMMM y",longDate:"d MMMM y",medium:"d MMM y h:mm:ss a",mediumDate:"d MMM y",mediumTime:"h:mm:ss a","short":"dd/MM/y h:mm a",shortDate:"dd/MM/y",shortTime:"h:mm a"},NUMBER_FORMATS:{CURRENCY_SYM:"Ksh",DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"\u00a4-",negSuf:"",posPre:"\u00a4",posSuf:""}]},id:"ebu",pluralCat:function(h,f){var g=h|0;var e=b(h,f);if(g==1&&e.v==0){return d.ONE}return d.OTHER}})}]); | dmsanchez86/cdnjs | ajax/libs/angular-i18n/1.4.2/angular-locale_ebu.min.js | JavaScript | mit | 1,552 |
"use strict";angular.module("ngLocale",[],["$provide",function(a){var b={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};a.value("$locale",{DATETIME_FORMATS:{AMPMS:["TO","TK"],DAY:["yakshanba","dushanba","seshanba","chorshanba","payshanba","juma","shanba"],ERANAMES:["M.A.","E"],ERAS:["M.A.","E"],FIRSTDAYOFWEEK:0,MONTH:["Yanvar","Fevral","Mart","Aprel","May","Iyun","Iyul","Avgust","Sentabr","Oktabr","Noyabr","Dekabr"],SHORTDAY:["Yaksh","Dush","Sesh","Chor","Pay","Jum","Shan"],SHORTMONTH:["Yanv","Fev","Mar","Apr","May","Iyun","Iyul","Avg","Sen","Okt","Noya","Dek"],WEEKENDRANGE:[5,6],fullDate:"EEEE, y MMMM dd",longDate:"y MMMM d",medium:"y MMM d HH:mm:ss",mediumDate:"y MMM d",mediumTime:"HH:mm:ss","short":"yy/MM/dd HH:mm",shortDate:"yy/MM/dd",shortTime:"HH:mm"},NUMBER_FORMATS:{CURRENCY_SYM:"so\u02bcm",DECIMAL_SEP:",",GROUP_SEP:"\u00a0",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"\u00a4\u00a0-",negSuf:"",posPre:"\u00a4\u00a0",posSuf:""}]},id:"uz",pluralCat:function(d,c){if(d==1){return b.ONE}return b.OTHER}})}]); | kennynaoh/cdnjs | ajax/libs/angular-i18n/1.4.1/angular-locale_uz.min.js | JavaScript | mit | 1,155 |
"use strict";angular.module("ngLocale",[],["$provide",function(a){var d={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};function c(f){f=f+"";var e=f.indexOf(".");return(e==-1)?0:f.length-e-1}function b(j,e){var g=e;if(undefined===g){g=Math.min(c(j),3)}var i=Math.pow(10,g);var h=((j*i)|0)%i;return{v:g,f:h}}a.value("$locale",{DATETIME_FORMATS:{AMPMS:["AM","PM"],DAY:["\ua55e\ua54c\ua535","\ua5f3\ua5e1\ua609","\ua55a\ua55e\ua55a","\ua549\ua55e\ua552","\ua549\ua524\ua546\ua562","\ua549\ua524\ua540\ua56e","\ua53b\ua52c\ua533"],ERANAMES:["BCE","CE"],ERAS:["BCE","CE"],FIRSTDAYOFWEEK:0,MONTH:["\ua5a8\ua56a\ua583 \ua51e\ua56e","\ua552\ua561\ua59d\ua595","\ua57e\ua5ba","\ua5a2\ua595","\ua591\ua571","6","7","\ua5db\ua515","\ua562\ua54c","\ua56d\ua583","\ua51e\ua60b\ua554\ua57f \ua578\ua583\ua5cf","\ua5a8\ua56a\ua571 \ua5cf\ua56e"],SHORTDAY:["\ua55e\ua54c\ua535","\ua5f3\ua5e1\ua609","\ua55a\ua55e\ua55a","\ua549\ua55e\ua552","\ua549\ua524\ua546\ua562","\ua549\ua524\ua540\ua56e","\ua53b\ua52c\ua533"],SHORTMONTH:["\ua5a8\ua56a\ua583 \ua51e\ua56e","\ua552\ua561\ua59d\ua595","\ua57e\ua5ba","\ua5a2\ua595","\ua591\ua571","6","7","\ua5db\ua515","\ua562\ua54c","\ua56d\ua583","\ua51e\ua60b\ua554\ua57f \ua578\ua583\ua5cf","\ua5a8\ua56a\ua571 \ua5cf\ua56e"],WEEKENDRANGE:[5,6],fullDate:"EEEE, d MMMM y",longDate:"d MMMM y",medium:"d MMM y h:mm:ss a",mediumDate:"d MMM y",mediumTime:"h:mm:ss a","short":"dd/MM/y h:mm a",shortDate:"dd/MM/y",shortTime:"h:mm a"},NUMBER_FORMATS:{CURRENCY_SYM:"$",DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"\u00a4-",negSuf:"",posPre:"\u00a4",posSuf:""}]},id:"vai",pluralCat:function(h,f){var g=h|0;var e=b(h,f);if(g==1&&e.v==0){return d.ONE}return d.OTHER}})}]); | BobbieBel/cdnjs | ajax/libs/angular-i18n/1.4.0-rc.2/angular-locale_vai.min.js | JavaScript | mit | 1,848 |
"use strict";angular.module("ngLocale",[],["$provide",function(a){var d={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};function c(f){f=f+"";var e=f.indexOf(".");return(e==-1)?0:f.length-e-1}function b(j,e){var g=e;if(undefined===g){g=Math.min(c(j),3)}var i=Math.pow(10,g);var h=((j*i)|0)%i;return{v:g,f:h}}a.value("$locale",{DATETIME_FORMATS:{AMPMS:["sn.","gn."],DAY:["Axad","Isniin","Talaado","Arbaco","Khamiis","Jimco","Sabti"],ERANAMES:["Ciise ka hor (CS)","Ciise ka dib (CS)"],ERAS:["CK","CD"],FIRSTDAYOFWEEK:0,MONTH:["Bisha Koobaad","Bisha Labaad","Bisha Saddexaad","Bisha Afraad","Bisha Shanaad","Bisha Lixaad","Bisha Todobaad","Bisha Sideedaad","Bisha Sagaalaad","Bisha Tobnaad","Bisha Kow iyo Tobnaad","Bisha Laba iyo Tobnaad"],SHORTDAY:["Axd","Isn","Tal","Arb","Kha","Jim","Sab"],SHORTMONTH:["Kob","Lab","Sad","Afr","Sha","Lix","Tod","Sid","Sag","Tob","KIT","LIT"],WEEKENDRANGE:[5,6],fullDate:"EEEE, MMMM dd, y",longDate:"dd MMMM y",medium:"dd-MMM-y h:mm:ss a",mediumDate:"dd-MMM-y",mediumTime:"h:mm:ss a","short":"dd/MM/yy h:mm a",shortDate:"dd/MM/yy",shortTime:"h:mm a"},NUMBER_FORMATS:{CURRENCY_SYM:"Birr",DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"\u00a4-",negSuf:"",posPre:"\u00a4",posSuf:""}]},id:"so-et",pluralCat:function(h,f){var g=h|0;var e=b(h,f);if(g==1&&e.v==0){return d.ONE}return d.OTHER}})}]); | lobbin/cdnjs | ajax/libs/angular-i18n/1.4.2/angular-locale_so-et.min.js | JavaScript | mit | 1,482 |
"use strict";angular.module("ngLocale",[],["$provide",function(a){var d={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};function c(f){f=f+"";var e=f.indexOf(".");return(e==-1)?0:f.length-e-1}function b(j,e){var g=e;if(undefined===g){g=Math.min(c(j),3)}var i=Math.pow(10,g);var h=((j*i)|0)%i;return{v:g,f:h}}a.value("$locale",{DATETIME_FORMATS:{AMPMS:["a.m.","p.m."],DAY:["domingo","luns","martes","m\u00e9rcores","xoves","venres","s\u00e1bado"],ERANAMES:["antes de Cristo","despois de Cristo"],ERAS:["a.C.","d.C."],FIRSTDAYOFWEEK:0,MONTH:["xaneiro","febreiro","marzo","abril","maio","xu\u00f1o","xullo","agosto","setembro","outubro","novembro","decembro"],SHORTDAY:["dom","lun","mar","m\u00e9r","xov","ven","s\u00e1b"],SHORTMONTH:["xan","feb","mar","abr","mai","xu\u00f1","xul","ago","set","out","nov","dec"],WEEKENDRANGE:[5,6],fullDate:"EEEE dd MMMM y",longDate:"dd MMMM y",medium:"d MMM, y HH:mm:ss",mediumDate:"d MMM, y",mediumTime:"HH:mm:ss","short":"dd/MM/yy HH:mm",shortDate:"dd/MM/yy",shortTime:"HH:mm"},NUMBER_FORMATS:{CURRENCY_SYM:"\u20ac",DECIMAL_SEP:",",GROUP_SEP:".",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"\u00a4-",negSuf:"",posPre:"\u00a4",posSuf:""}]},id:"gl-es",pluralCat:function(h,f){var g=h|0;var e=b(h,f);if(g==1&&e.v==0){return d.ONE}return d.OTHER}})}]); | jasonpang/cdnjs | ajax/libs/angular-i18n/1.4.2/angular-locale_gl-es.min.js | JavaScript | mit | 1,412 |
"use strict";angular.module("ngLocale",[],["$provide",function(a){var d={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};function c(f){f=f+"";var e=f.indexOf(".");return(e==-1)?0:f.length-e-1}function b(j,e){var g=e;if(undefined===g){g=Math.min(c(j),3)}var i=Math.pow(10,g);var h=((j*i)|0)%i;return{v:g,f:h}}a.value("$locale",{DATETIME_FORMATS:{AMPMS:["a. m.","p. m."],DAY:["diumenge","dilluns","dimarts","dimecres","dijous","divendres","dissabte"],ERANAMES:["abans de Crist","despr\u00e9s de Crist"],ERAS:["aC","dC"],FIRSTDAYOFWEEK:0,MONTH:["gener","febrer","mar\u00e7","abril","maig","juny","juliol","agost","setembre","octubre","novembre","desembre"],SHORTDAY:["dg.","dl.","dt.","dc.","dj.","dv.","ds."],SHORTMONTH:["gen.","febr.","mar\u00e7","abr.","maig","juny","jul.","ag.","set.","oct.","nov.","des."],WEEKENDRANGE:[5,6],fullDate:"EEEE, d MMMM 'de' y",longDate:"d MMMM 'de' y",medium:"d MMM y H:mm:ss",mediumDate:"d MMM y",mediumTime:"H:mm:ss","short":"d/M/yy H:mm",shortDate:"d/M/yy",shortTime:"H:mm"},NUMBER_FORMATS:{CURRENCY_SYM:"\u20ac",DECIMAL_SEP:",",GROUP_SEP:".",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"-",negSuf:"\u00a0\u00a4",posPre:"",posSuf:"\u00a0\u00a4"}]},id:"ca-fr",pluralCat:function(h,f){var g=h|0;var e=b(h,f);if(g==1&&e.v==0){return d.ONE}return d.OTHER}})}]); | aashish24/cdnjs | ajax/libs/angular-i18n/1.4.2/angular-locale_ca-fr.min.js | JavaScript | mit | 1,422 |
"use strict";angular.module("ngLocale",[],["$provide",function(a){var b={ZERO:"zero",ONE:"one",TWO:"two",FEW:"few",MANY:"many",OTHER:"other"};a.value("$locale",{DATETIME_FORMATS:{AMPMS:["\u0e01\u0e48\u0e2d\u0e19\u0e40\u0e17\u0e35\u0e48\u0e22\u0e07","\u0e2b\u0e25\u0e31\u0e07\u0e40\u0e17\u0e35\u0e48\u0e22\u0e07"],DAY:["\u0e27\u0e31\u0e19\u0e2d\u0e32\u0e17\u0e34\u0e15\u0e22\u0e4c","\u0e27\u0e31\u0e19\u0e08\u0e31\u0e19\u0e17\u0e23\u0e4c","\u0e27\u0e31\u0e19\u0e2d\u0e31\u0e07\u0e04\u0e32\u0e23","\u0e27\u0e31\u0e19\u0e1e\u0e38\u0e18","\u0e27\u0e31\u0e19\u0e1e\u0e24\u0e2b\u0e31\u0e2a\u0e1a\u0e14\u0e35","\u0e27\u0e31\u0e19\u0e28\u0e38\u0e01\u0e23\u0e4c","\u0e27\u0e31\u0e19\u0e40\u0e2a\u0e32\u0e23\u0e4c"],ERANAMES:["\u0e1b\u0e35\u0e01\u0e48\u0e2d\u0e19\u0e04\u0e23\u0e34\u0e2a\u0e15\u0e4c\u0e28\u0e31\u0e01\u0e23\u0e32\u0e0a","\u0e04\u0e23\u0e34\u0e2a\u0e15\u0e4c\u0e28\u0e31\u0e01\u0e23\u0e32\u0e0a"],ERAS:["\u0e1b\u0e35\u0e01\u0e48\u0e2d\u0e19 \u0e04.\u0e28.","\u0e04.\u0e28."],FIRSTDAYOFWEEK:6,MONTH:["\u0e21\u0e01\u0e23\u0e32\u0e04\u0e21","\u0e01\u0e38\u0e21\u0e20\u0e32\u0e1e\u0e31\u0e19\u0e18\u0e4c","\u0e21\u0e35\u0e19\u0e32\u0e04\u0e21","\u0e40\u0e21\u0e29\u0e32\u0e22\u0e19","\u0e1e\u0e24\u0e29\u0e20\u0e32\u0e04\u0e21","\u0e21\u0e34\u0e16\u0e38\u0e19\u0e32\u0e22\u0e19","\u0e01\u0e23\u0e01\u0e0e\u0e32\u0e04\u0e21","\u0e2a\u0e34\u0e07\u0e2b\u0e32\u0e04\u0e21","\u0e01\u0e31\u0e19\u0e22\u0e32\u0e22\u0e19","\u0e15\u0e38\u0e25\u0e32\u0e04\u0e21","\u0e1e\u0e24\u0e28\u0e08\u0e34\u0e01\u0e32\u0e22\u0e19","\u0e18\u0e31\u0e19\u0e27\u0e32\u0e04\u0e21"],SHORTDAY:["\u0e2d\u0e32.","\u0e08.","\u0e2d.","\u0e1e.","\u0e1e\u0e24.","\u0e28.","\u0e2a."],SHORTMONTH:["\u0e21.\u0e04.","\u0e01.\u0e1e.","\u0e21\u0e35.\u0e04.","\u0e40\u0e21.\u0e22.","\u0e1e.\u0e04.","\u0e21\u0e34.\u0e22.","\u0e01.\u0e04.","\u0e2a.\u0e04.","\u0e01.\u0e22.","\u0e15.\u0e04.","\u0e1e.\u0e22.","\u0e18.\u0e04."],WEEKENDRANGE:[5,6],fullDate:"EEEE\u0e17\u0e35\u0e48 d MMMM G y",longDate:"d MMMM G y",medium:"d MMM y HH:mm:ss",mediumDate:"d MMM y",mediumTime:"HH:mm:ss","short":"d/M/yy HH:mm",shortDate:"d/M/yy",shortTime:"HH:mm"},NUMBER_FORMATS:{CURRENCY_SYM:"\u0e3f",DECIMAL_SEP:".",GROUP_SEP:",",PATTERNS:[{gSize:3,lgSize:3,maxFrac:3,minFrac:0,minInt:1,negPre:"-",negSuf:"",posPre:"",posSuf:""},{gSize:3,lgSize:3,maxFrac:2,minFrac:2,minInt:1,negPre:"\u00a4-",negSuf:"",posPre:"\u00a4",posSuf:""}]},id:"th",pluralCat:function(d,c){return b.OTHER}})}]); | dada0423/cdnjs | ajax/libs/angular-i18n/1.4.0-rc.2/angular-locale_th.min.js | JavaScript | mit | 2,425 |
/*
* fs/anon_inodes.c
*
* Copyright (C) 2007 Davide Libenzi <davidel@xmailserver.org>
*
* Thanks to Arnd Bergmann for code review and suggestions.
* More changes for Thomas Gleixner suggestions.
*
*/
#include <linux/cred.h>
#include <linux/file.h>
#include <linux/poll.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/mount.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/magic.h>
#include <linux/anon_inodes.h>
#include <asm/uaccess.h>
static struct vfsmount *anon_inode_mnt __read_mostly;
static struct inode *anon_inode_inode;
static const struct file_operations anon_inode_fops;
/*
* anon_inodefs_dname() is called from d_path().
*/
static char *anon_inodefs_dname(struct dentry *dentry, char *buffer, int buflen)
{
return dynamic_dname(dentry, buffer, buflen, "anon_inode:%s",
dentry->d_name.name);
}
static const struct dentry_operations anon_inodefs_dentry_operations = {
.d_dname = anon_inodefs_dname,
};
static struct dentry *anon_inodefs_mount(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data)
{
return mount_pseudo(fs_type, "anon_inode:", NULL,
&anon_inodefs_dentry_operations, ANON_INODE_FS_MAGIC);
}
static struct file_system_type anon_inode_fs_type = {
.name = "anon_inodefs",
.mount = anon_inodefs_mount,
.kill_sb = kill_anon_super,
};
/*
* nop .set_page_dirty method so that people can use .page_mkwrite on
* anon inodes.
*/
static int anon_set_page_dirty(struct page *page)
{
return 0;
};
static const struct address_space_operations anon_aops = {
.set_page_dirty = anon_set_page_dirty,
};
/**
* anon_inode_getfile - creates a new file instance by hooking it up to an
* anonymous inode, and a dentry that describe the "class"
* of the file
*
* @name: [in] name of the "class" of the new file
* @fops: [in] file operations for the new file
* @priv: [in] private data for the new file (will be file's private_data)
* @flags: [in] flags
*
* Creates a new file by hooking it on a single inode. This is useful for files
* that do not need to have a full-fledged inode in order to operate correctly.
* All the files created with anon_inode_getfile() will share a single inode,
* hence saving memory and avoiding code duplication for the file/inode/dentry
* setup. Returns the newly created file* or an error pointer.
*/
struct file *anon_inode_getfile(const char *name,
const struct file_operations *fops,
void *priv, int flags)
{
struct qstr this;
struct path path;
struct file *file;
int error;
if (IS_ERR(anon_inode_inode))
return ERR_PTR(-ENODEV);
if (fops->owner && !try_module_get(fops->owner))
return ERR_PTR(-ENOENT);
/*
* Link the inode to a directory entry by creating a unique name
* using the inode sequence number.
*/
error = -ENOMEM;
this.name = name;
this.len = strlen(name);
this.hash = 0;
path.dentry = d_alloc_pseudo(anon_inode_mnt->mnt_sb, &this);
if (!path.dentry)
goto err_module;
path.mnt = mntget(anon_inode_mnt);
/*
* We know the anon_inode inode count is always greater than zero,
* so ihold() is safe.
*/
ihold(anon_inode_inode);
d_instantiate(path.dentry, anon_inode_inode);
error = -ENFILE;
file = alloc_file(&path, OPEN_FMODE(flags), fops);
if (!file)
goto err_dput;
file->f_mapping = anon_inode_inode->i_mapping;
file->f_pos = 0;
file->f_flags = flags & (O_ACCMODE | O_NONBLOCK);
file->f_version = 0;
file->private_data = priv;
return file;
err_dput:
path_put(&path);
err_module:
module_put(fops->owner);
return ERR_PTR(error);
}
EXPORT_SYMBOL_GPL(anon_inode_getfile);
/**
* anon_inode_getfd - creates a new file instance by hooking it up to an
* anonymous inode, and a dentry that describe the "class"
* of the file
*
* @name: [in] name of the "class" of the new file
* @fops: [in] file operations for the new file
* @priv: [in] private data for the new file (will be file's private_data)
* @flags: [in] flags
*
* Creates a new file by hooking it on a single inode. This is useful for files
* that do not need to have a full-fledged inode in order to operate correctly.
* All the files created with anon_inode_getfd() will share a single inode,
* hence saving memory and avoiding code duplication for the file/inode/dentry
* setup. Returns new descriptor or an error code.
*/
int anon_inode_getfd(const char *name, const struct file_operations *fops,
void *priv, int flags)
{
int error, fd;
struct file *file;
error = get_unused_fd_flags(flags);
if (error < 0)
return error;
fd = error;
file = anon_inode_getfile(name, fops, priv, flags);
if (IS_ERR(file)) {
error = PTR_ERR(file);
goto err_put_unused_fd;
}
fd_install(fd, file);
return fd;
err_put_unused_fd:
put_unused_fd(fd);
return error;
}
EXPORT_SYMBOL_GPL(anon_inode_getfd);
/*
* A single inode exists for all anon_inode files. Contrary to pipes,
* anon_inode inodes have no associated per-instance data, so we need
* only allocate one of them.
*/
static struct inode *anon_inode_mkinode(void)
{
struct inode *inode = new_inode_pseudo(anon_inode_mnt->mnt_sb);
if (!inode)
return ERR_PTR(-ENOMEM);
inode->i_ino = get_next_ino();
inode->i_fop = &anon_inode_fops;
inode->i_mapping->a_ops = &anon_aops;
/*
* Mark the inode dirty from the very beginning,
* that way it will never be moved to the dirty
* list because mark_inode_dirty() will think
* that it already _is_ on the dirty list.
*/
inode->i_state = I_DIRTY;
inode->i_mode = S_IRUSR | S_IWUSR;
inode->i_uid = current_fsuid();
inode->i_gid = current_fsgid();
inode->i_flags |= S_PRIVATE;
inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
return inode;
}
static int __init anon_inode_init(void)
{
int error;
error = register_filesystem(&anon_inode_fs_type);
if (error)
goto err_exit;
anon_inode_mnt = kern_mount(&anon_inode_fs_type);
if (IS_ERR(anon_inode_mnt)) {
error = PTR_ERR(anon_inode_mnt);
goto err_unregister_filesystem;
}
anon_inode_inode = anon_inode_mkinode();
if (IS_ERR(anon_inode_inode)) {
error = PTR_ERR(anon_inode_inode);
goto err_mntput;
}
return 0;
err_mntput:
kern_unmount(anon_inode_mnt);
err_unregister_filesystem:
unregister_filesystem(&anon_inode_fs_type);
err_exit:
panic(KERN_ERR "anon_inode_init() failed (%d)\n", error);
}
fs_initcall(anon_inode_init);
| sahdman/rpi_android_kernel | linux-3.1.9/fs/anon_inodes.c | C | mit | 6,506 |
/*!
* @overview Ember Data
* @copyright Copyright 2011-2013 Tilde Inc. and contributors.
* Portions Copyright 2011 LivingSocial Inc.
* @license Licensed under MIT license (see license.js)
*/
// Version: 1.0.0-beta.4
(function() {
var define, requireModule;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requireModule = function(name) {
if (seen[name]) { return seen[name]; }
seen[name] = {};
var mod, deps, callback, reified , exports;
mod = registry[name];
if (!mod) {
throw new Error("Module '" + name + "' not found.");
}
deps = mod.deps;
callback = mod.callback;
reified = [];
exports;
for (var i=0, l=deps.length; i<l; i++) {
if (deps[i] === 'exports') {
reified.push(exports = {});
} else {
reified.push(requireModule(deps[i]));
}
}
var value = callback.apply(this, reified);
return seen[name] = exports || value;
};
})();
(function() {
/**
@module ember-data
*/
/**
All Ember Data methods and functions are defined inside of this namespace.
@class DS
@static
*/
var DS;
if ('undefined' === typeof DS) {
DS = Ember.Namespace.create({
VERSION: '1.0.0-beta.4'
});
if ('undefined' !== typeof window) {
window.DS = DS;
}
if (Ember.libraries) {
Ember.libraries.registerCoreLibrary('Ember Data', DS.VERSION);
}
}
})();
(function() {
var get = Ember.get, set = Ember.set, isNone = Ember.isNone;
// Simple dispatcher to support overriding the aliased
// method in subclasses.
function aliasMethod(methodName) {
return function() {
return this[methodName].apply(this, arguments);
};
}
/**
In Ember Data a Serializer is used to serialize and deserialize
records when they are transfered in and out of an external source.
This process involves normalizing property names, transforming
attribute values and serializeing relationships.
For maximum performance Ember Data recomends you use the
[RESTSerializer](DS.RESTSerializer.html) or one of its subclasses.
`JSONSerializer` is useful for simpler or legacy backends that may
not support the http://jsonapi.org/ spec.
@class JSONSerializer
@namespace DS
*/
DS.JSONSerializer = Ember.Object.extend({
/**
The primaryKey is used when serializing and deserializing
data. Ember Data always uses the `id` propery to store the id of
the record. The external source may not always follow this
convention. In these cases it is usesful to override the
primaryKey property to match the primaryKey of your external
store.
Example
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
primaryKey: '_id'
});
```
@property primaryKey
@type {String}
*/
primaryKey: 'id',
/**
Given a subclass of `DS.Model` and a JSON object this method will
iterate through each attribute of the `DS.Model` and invoke the
`DS.Transform#deserialize` method on the matching property of the
JSON object. This method is typically called after the
serializer's `normalize` method.
@method applyTransforms
@private
@param {subclass of DS.Model} type
@param {Object} data The data to transform
@return {Object} data The transformed data object
*/
applyTransforms: function(type, data) {
type.eachTransformedAttribute(function(key, type) {
var transform = this.transformFor(type);
data[key] = transform.deserialize(data[key]);
}, this);
return data;
},
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
Example
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
normalize: function(type, hash) {
var normalizedHash = {};
var fields = Ember.get(type, 'fields');
fields.forEach(function(field) {
var normalizedProp = Ember.String.camelize(field);
normalizedHash[normalizedProp] = hash[field];
});
return this._super.apply(this, arguments);
}
});
```
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@return {Object}
*/
normalize: function(type, hash) {
if (!hash) { return hash; }
this.applyTransforms(type, hash);
return hash;
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```javascript
App.Comment = DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```javascript
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serialize: function(post, options) {
var json = {
POST_TTL: post.get('title'),
POST_BDY: post.get('body'),
POST_CMS: post.get('comments').mapProperty('id')
}
if (options.includeId) {
json.POST_ID_ = post.get('id');
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = {};
record.eachAttribute(function(name) {
json[serverAttributeName(name)] = record.get(name);
})
record.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = record.get(name).mapBy('id');
}
});
if (options.includeId) {
json.ID_ = record.get('id');
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```javascript
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serialize: function(record, options) {
var json = this._super.apply(this, arguments);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param {subclass of DS.Model} record
@param {Object} options
@return {Object} json
*/
serialize: function(record, options) {
var json = {};
if (options && options.includeId) {
var id = get(record, 'id');
if (id) {
json[get(this, 'primaryKey')] = get(record, 'id');
}
}
record.eachAttribute(function(key, attribute) {
this.serializeAttribute(record, json, key, attribute);
}, this);
record.eachRelationship(function(key, relationship) {
if (relationship.kind === 'belongsTo') {
this.serializeBelongsTo(record, json, relationship);
} else if (relationship.kind === 'hasMany') {
this.serializeHasMany(record, json, relationship);
}
}, this);
return json;
},
/**
`serializeAttribute` can be used to customize how `DS.attr`
properties are serialized
For example if you wanted to ensure all you attributes were always
serialized as properties on an `attributes` object you could
write:
```javascript
App.ApplicationSerializer = DS.JSONSerializer.extend({
serializeAttribute: function(record, json, key, attributes) {
json.attributes = json.attributes || {};
this._super(record, json.attributes, key, attributes);
}
});
```
@method serializeAttribute
@param {DS.Model} record
@param {Object} json
@param {String} key
@param {Object} attribute
*/
serializeAttribute: function(record, json, key, attribute) {
var attrs = get(this, 'attrs');
var value = get(record, key), type = attribute.type;
if (type) {
var transform = this.transformFor(type);
value = transform.serialize(value);
}
// if provided, use the mapping provided by `attrs` in
// the serializer
key = attrs && attrs[key] || (this.keyForAttribute ? this.keyForAttribute(key) : key);
json[key] = value;
},
/**
`serializeBelongsTo` can be used to customize how `DS.belongsTo`
properties are serialized.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serializeBelongsTo: function(record, json, relationship) {
var key = relationship.key;
var belongsTo = get(record, key);
key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key;
json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.toJSON();
}
});
```
@method serializeBelongsTo
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializeBelongsTo: function(record, json, relationship) {
var key = relationship.key;
var belongsTo = get(record, key);
key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key;
if (isNone(belongsTo)) {
json[key] = belongsTo;
} else {
json[key] = get(belongsTo, 'id');
}
if (relationship.options.polymorphic) {
this.serializePolymorphicType(record, json, relationship);
}
},
/**
`serializeHasMany` can be used to customize how `DS.hasMany`
properties are serialized.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
serializeHasMany: function(record, json, relationship) {
var key = relationship.key;
if (key === 'comments') {
return;
} else {
this._super.apply(this, arguments);
}
}
});
```
@method serializeHasMany
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializeHasMany: function(record, json, relationship) {
var key = relationship.key;
var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship);
if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') {
json[key] = get(record, key).mapBy('id');
// TODO support for polymorphic manyToNone and manyToMany relationships
}
},
/**
You can use this method to customize how polymorphic objects are
serialized. Objects are considered to be polymorphic if
`{polymorphic: true}` is pass as the second argument to the
`DS.belongsTo` function.
Example
```javascript
App.CommentSerializer = DS.JSONSerializer.extend({
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key,
belongsTo = get(record, key);
key = this.keyForAttribute ? this.keyForAttribute(key) : key;
json[key + "_type"] = belongsTo.constructor.typeKey;
}
});
```
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: Ember.K,
// EXTRACT
/**
The `extract` method is used to deserialize payload data from the
server. By default the `JSONSerializer` does not push the records
into the store. However records that subclass `JSONSerializer`
such as the `RESTSerializer` may push records into the store as
part of the extract call.
This method deletegates to a more specific extract method based on
the `requestType`.
Example
```javascript
var get = Ember.get;
socket.on('message', function(message) {
var modelName = message.model;
var data = message.data;
var type = store.modelFor(modelName);
var serializer = store.serializerFor(type.typeKey);
var record = serializer.extract(store, type, data, get(data, 'id'), 'single');
store.push(modelName, record);
});
```
@method extract
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String or Number} id
@param {String} requestType
@return {Object} json The deserialized payload
*/
extract: function(store, type, payload, id, requestType) {
this.extractMeta(store, type, payload);
var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1);
return this[specificExtract](store, type, payload, id, requestType);
},
/**
`extractFindAll` is a hook into the extract method used when a
call is made to `DS.Store#findAll`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindAll
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractFindAll: aliasMethod('extractArray'),
/**
`extractFindQuery` is a hook into the extract method used when a
call is made to `DS.Store#findQuery`. By default this method is an
alias for [extractArray](#method_extractArray).
@method extractFindQuery
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractFindQuery: aliasMethod('extractArray'),
/**
`extractFindMany` is a hook into the extract method used when a
call is made to `DS.Store#findMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractFindMany: aliasMethod('extractArray'),
/**
`extractFindHasMany` is a hook into the extract method used when a
call is made to `DS.Store#findHasMany`. By default this method is
alias for [extractArray](#method_extractArray).
@method extractFindHasMany
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractFindHasMany: aliasMethod('extractArray'),
/**
`extractCreateRecord` is a hook into the extract method used when a
call is made to `DS.Store#createRecord`. By default this method is
alias for [extractSave](#method_extractSave).
@method extractCreateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractCreateRecord: aliasMethod('extractSave'),
/**
`extractUpdateRecord` is a hook into the extract method used when
a call is made to `DS.Store#update`. By default this method is alias
for [extractSave](#method_extractSave).
@method extractUpdateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractUpdateRecord: aliasMethod('extractSave'),
/**
`extractDeleteRecord` is a hook into the extract method used when
a call is made to `DS.Store#deleteRecord`. By default this method is
alias for [extractSave](#method_extractSave).
@method extractDeleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractDeleteRecord: aliasMethod('extractSave'),
/**
`extractFind` is a hook into the extract method used when
a call is made to `DS.Store#find`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFind
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractFind: aliasMethod('extractSingle'),
/**
`extractFindBelongsTo` is a hook into the extract method used when
a call is made to `DS.Store#findBelongsTo`. By default this method is
alias for [extractSingle](#method_extractSingle).
@method extractFindBelongsTo
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractFindBelongsTo: aliasMethod('extractSingle'),
/**
`extractSave` is a hook into the extract method used when a call
is made to `DS.Model#save`. By default this method is alias
for [extractSingle](#method_extractSingle).
@method extractSave
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractSave: aliasMethod('extractSingle'),
/**
`extractSingle` is used to deserialize a single record returned
from the adapter.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractSingle: function(store, type, payload) {
payload.comments = payload._embedded.comment;
delete payload._embedded;
return this._super(store, type, payload);
},
});
```
@method extractSingle
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Object} json The deserialized payload
*/
extractSingle: function(store, type, payload) {
return this.normalize(type, payload);
},
/**
`extractArray` is used to deserialize an array of records
returned from the adapter.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractArray: function(store, type, payload) {
return payload.map(function(json) {
return this.extractSingle(json);
}, this);
}
});
```
@method extractArray
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@return {Array} array An array of deserialized objects
*/
extractArray: function(store, type, payload) {
return this.normalize(type, payload);
},
/**
`extractMeta` is used to deserialize any meta information in the
adapter payload. By default Ember Data expects meta information to
be located on the `meta` property of the payload object.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
extractMeta: function(store, type, payload) {
if (payload && payload._pagination) {
store.metaForType(type, payload._pagination);
delete payload._pagination;
}
}
});
```
@method extractMeta
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
*/
extractMeta: function(store, type, payload) {
if (payload && payload.meta) {
store.metaForType(type, payload.meta);
delete payload.meta;
}
},
/**
`keyForRelationship` can be used to define a custom key when
serializeing relationship properties. By default `JSONSerializer`
does not provide an implementation of this method.
Example
```javascript
App.PostSerializer = DS.JSONSerializer.extend({
keyForRelationship: function(key, relationship) {
return 'rel_' + Ember.String.underscore(key);
}
});
```
@method keyForRelationship
@param {String} key
@param {String} relationship type
@return {String} normalized key
*/
// HELPERS
/**
@method transformFor
@private
@param {String} attributeType
@param {Boolean} skipAssertion
@return {DS.Transform} transform
*/
transformFor: function(attributeType, skipAssertion) {
var transform = this.container.lookup('transform:' + attributeType);
Ember.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform);
return transform;
}
});
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get, capitalize = Ember.String.capitalize, underscore = Ember.String.underscore, DS = window.DS ;
/**
Extend `Ember.DataAdapter` with ED specific code.
@class DebugAdapter
@namespace DS
@extends Ember.DataAdapter
@private
*/
DS.DebugAdapter = Ember.DataAdapter.extend({
getFilters: function() {
return [
{ name: 'isNew', desc: 'New' },
{ name: 'isModified', desc: 'Modified' },
{ name: 'isClean', desc: 'Clean' }
];
},
detect: function(klass) {
return klass !== DS.Model && DS.Model.detect(klass);
},
columnsForType: function(type) {
var columns = [{ name: 'id', desc: 'Id' }], count = 0, self = this;
get(type, 'attributes').forEach(function(name, meta) {
if (count++ > self.attributeLimit) { return false; }
var desc = capitalize(underscore(name).replace('_', ' '));
columns.push({ name: name, desc: desc });
});
return columns;
},
getRecords: function(type) {
return this.get('store').all(type);
},
getRecordColumnValues: function(record) {
var self = this, count = 0,
columnValues = { id: get(record, 'id') };
record.eachAttribute(function(key) {
if (count++ > self.attributeLimit) {
return false;
}
var value = get(record, key);
columnValues[key] = value;
});
return columnValues;
},
getRecordKeywords: function(record) {
var keywords = [], keys = Ember.A(['id']);
record.eachAttribute(function(key) {
keys.push(key);
});
keys.forEach(function(key) {
keywords.push(get(record, key));
});
return keywords;
},
getRecordFilterValues: function(record) {
return {
isNew: record.get('isNew'),
isModified: record.get('isDirty') && !record.get('isNew'),
isClean: !record.get('isDirty')
};
},
getRecordColor: function(record) {
var color = 'black';
if (record.get('isNew')) {
color = 'green';
} else if (record.get('isDirty')) {
color = 'blue';
}
return color;
},
observeRecord: function(record, recordUpdated) {
var releaseMethods = Ember.A(), self = this,
keysToObserve = Ember.A(['id', 'isNew', 'isDirty']);
record.eachAttribute(function(key) {
keysToObserve.push(key);
});
keysToObserve.forEach(function(key) {
var handler = function() {
recordUpdated(self.wrapRecord(record));
};
Ember.addObserver(record, key, handler);
releaseMethods.push(function() {
Ember.removeObserver(record, key, handler);
});
});
var release = function() {
releaseMethods.forEach(function(fn) { fn(); } );
};
return release;
}
});
})();
(function() {
/**
The `DS.Transform` class is used to serialize and deserialize model
attributes when they are saved or loaded from an
adapter. Subclassing `DS.Transform` is useful for creating custom
attributes. All subclasses of `DS.Transform` must implement a
`serialize` and a `deserialize` method.
Example
```javascript
App.RawTransform = DS.Transform.extend({
deserialize: function(serialized) {
return serialized;
},
serialize: function(deserialized) {
return deserialized;
}
});
```
Usage
```javascript
var attr = DS.attr;
App.Requirement = DS.Model.extend({
name: attr('string'),
optionsArray: attr('raw')
});
```
@class Transform
@namespace DS
*/
DS.Transform = Ember.Object.extend({
/**
When given a deserialized value from a record attribute this
method must return the serialized value.
Example
```javascript
serialize: function(deserialized) {
return Ember.isEmpty(deserialized) ? null : Number(deserialized);
}
```
@method serialize
@param deserialized The deserialized value
@return The serialized value
*/
serialize: Ember.required(),
/**
When given a serialize value from a JSON object this method must
return the deserialized value for the record attribute.
Example
```javascript
deserialize: function(serialized) {
return empty(serialized) ? null : Number(serialized);
}
```
@method deserialized
@param serialized The serialized value
@return The deserialized value
*/
deserialize: Ember.required()
});
})();
(function() {
/**
The `DS.BooleanTransform` class is used to serialize and deserialize
boolean attributes on Ember Data record objects. This transform is
used when `boolean` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```javascript
var attr = DS.attr;
App.User = DS.Model.extend({
isAdmin: attr('boolean'),
name: attr('string'),
email: attr('string')
});
```
@class BooleanTransform
@extends DS.Transform
@namespace DS
*/
DS.BooleanTransform = DS.Transform.extend({
deserialize: function(serialized) {
var type = typeof serialized;
if (type === "boolean") {
return serialized;
} else if (type === "string") {
return serialized.match(/^true$|^t$|^1$/i) !== null;
} else if (type === "number") {
return serialized === 1;
} else {
return false;
}
},
serialize: function(deserialized) {
return Boolean(deserialized);
}
});
})();
(function() {
/**
The `DS.DateTransform` class is used to serialize and deserialize
date attributes on Ember Data record objects. This transform is used
when `date` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
```javascript
var attr = DS.attr;
App.Score = DS.Model.extend({
value: attr('number'),
player: DS.belongsTo('player'),
date: attr('date')
});
```
@class DateTransform
@extends DS.Transform
@namespace DS
*/
DS.DateTransform = DS.Transform.extend({
deserialize: function(serialized) {
var type = typeof serialized;
if (type === "string") {
return new Date(Ember.Date.parse(serialized));
} else if (type === "number") {
return new Date(serialized);
} else if (serialized === null || serialized === undefined) {
// if the value is not present in the data,
// return undefined, not null.
return serialized;
} else {
return null;
}
},
serialize: function(date) {
if (date instanceof Date) {
var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
var pad = function(num) {
return num < 10 ? "0"+num : ""+num;
};
var utcYear = date.getUTCFullYear(),
utcMonth = date.getUTCMonth(),
utcDayOfMonth = date.getUTCDate(),
utcDay = date.getUTCDay(),
utcHours = date.getUTCHours(),
utcMinutes = date.getUTCMinutes(),
utcSeconds = date.getUTCSeconds();
var dayOfWeek = days[utcDay];
var dayOfMonth = pad(utcDayOfMonth);
var month = months[utcMonth];
return dayOfWeek + ", " + dayOfMonth + " " + month + " " + utcYear + " " +
pad(utcHours) + ":" + pad(utcMinutes) + ":" + pad(utcSeconds) + " GMT";
} else {
return null;
}
}
});
})();
(function() {
var empty = Ember.isEmpty;
/**
The `DS.NumberTransform` class is used to serialize and deserialize
numeric attributes on Ember Data record objects. This transform is
used when `number` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```javascript
var attr = DS.attr;
App.Score = DS.Model.extend({
value: attr('number'),
player: DS.belongsTo('player'),
date: attr('date')
});
```
@class NumberTransform
@extends DS.Transform
@namespace DS
*/
DS.NumberTransform = DS.Transform.extend({
deserialize: function(serialized) {
return empty(serialized) ? null : Number(serialized);
},
serialize: function(deserialized) {
return empty(deserialized) ? null : Number(deserialized);
}
});
})();
(function() {
var none = Ember.isNone;
/**
The `DS.StringTransform` class is used to serialize and deserialize
string attributes on Ember Data record objects. This transform is
used when `string` is passed as the type parameter to the
[DS.attr](../../data#method_attr) function.
Usage
```javascript
var attr = DS.attr;
App.User = DS.Model.extend({
isAdmin: attr('boolean'),
name: attr('string'),
email: attr('string')
});
```
@class StringTransform
@extends DS.Transform
@namespace DS
*/
DS.StringTransform = DS.Transform.extend({
deserialize: function(serialized) {
return none(serialized) ? null : String(serialized);
},
serialize: function(deserialized) {
return none(deserialized) ? null : String(deserialized);
}
});
})();
(function() {
})();
(function() {
/**
@module ember-data
*/
var set = Ember.set;
/*
This code registers an injection for Ember.Application.
If an Ember.js developer defines a subclass of DS.Store on their application,
this code will automatically instantiate it and make it available on the
router.
Additionally, after an application's controllers have been injected, they will
each have the store made available to them.
For example, imagine an Ember.js application with the following classes:
App.Store = DS.Store.extend({
adapter: 'custom'
});
App.PostsController = Ember.ArrayController.extend({
// ...
});
When the application is initialized, `App.Store` will automatically be
instantiated, and the instance of `App.PostsController` will have its `store`
property set to that instance.
Note that this code will only be run if the `ember-application` package is
loaded. If Ember Data is being used in an environment other than a
typical application (e.g., node.js where only `ember-runtime` is available),
this code will be ignored.
*/
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer({
name: "store",
initialize: function(container, application) {
application.register('store:main', application.Store || DS.Store);
application.register('serializer:_default', DS.JSONSerializer);
application.register('serializer:_rest', DS.RESTSerializer);
application.register('adapter:_rest', DS.RESTAdapter);
// Eagerly generate the store so defaultStore is populated.
// TODO: Do this in a finisher hook
container.lookup('store:main');
}
});
Application.initializer({
name: "transforms",
before: "store",
initialize: function(container, application) {
application.register('transform:boolean', DS.BooleanTransform);
application.register('transform:date', DS.DateTransform);
application.register('transform:number', DS.NumberTransform);
application.register('transform:string', DS.StringTransform);
}
});
Application.initializer({
name: "dataAdapter",
before: "store",
initialize: function(container, application) {
application.register('dataAdapter:main', DS.DebugAdapter);
}
});
Application.initializer({
name: "injectStore",
before: "store",
initialize: function(container, application) {
application.inject('controller', 'store', 'store:main');
application.inject('route', 'store', 'store:main');
application.inject('serializer', 'store', 'store:main');
application.inject('dataAdapter', 'store', 'store:main');
}
});
});
})();
(function() {
/**
@module ember-data
*/
/**
Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601>
© 2011 Colin Snover <http://zetafleet.com>
Released under MIT license.
@class Date
@namespace Ember
@static
*/
Ember.Date = Ember.Date || {};
var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ];
/**
@method parse
@param date
*/
Ember.Date.parse = function (date) {
var timestamp, struct, minutesOffset = 0;
// ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
// before falling back to any implementation-specific date parsing, so that’s what we do, even if native
// implementations could be faster
// 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) {
// avoid NaN timestamps caused by “undefined” values being passed to Date.UTC
for (var i = 0, k; (k = numericKeys[i]); ++i) {
struct[k] = +struct[k] || 0;
}
// allow undefined days and months
struct[2] = (+struct[2] || 1) - 1;
struct[3] = +struct[3] || 1;
if (struct[8] !== 'Z' && struct[9] !== undefined) {
minutesOffset = struct[10] * 60 + struct[11];
if (struct[9] === '+') {
minutesOffset = 0 - minutesOffset;
}
}
timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]);
}
else {
timestamp = origParse ? origParse(date) : NaN;
}
return timestamp;
};
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) {
Date.parse = Ember.Date.parse;
}
})();
(function() {
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
/**
A record array is an array that contains records of a certain type. The record
array materializes records as needed when they are retrieved for the first
time. You should not create record arrays yourself. Instead, an instance of
DS.RecordArray or its subclasses will be returned by your application's store
in response to queries.
@class RecordArray
@namespace DS
@extends Ember.ArrayProxy
@uses Ember.Evented
*/
DS.RecordArray = Ember.ArrayProxy.extend(Ember.Evented, {
/**
The model type contained by this record array.
@property type
@type DS.Model
*/
type: null,
// The array of client ids backing the record array. When a
// record is requested from the record array, the record
// for the client id at the same index is materialized, if
// necessary, by the store.
content: null,
isLoaded: false,
isUpdating: false,
// The store that created this record array.
store: null,
objectAtContent: function(index) {
var content = get(this, 'content');
return content.objectAt(index);
},
update: function() {
if (get(this, 'isUpdating')) { return; }
var store = get(this, 'store'),
type = get(this, 'type');
store.fetchAll(type, this);
},
addRecord: function(record) {
get(this, 'content').addObject(record);
},
removeRecord: function(record) {
get(this, 'content').removeObject(record);
},
save: function() {
var promiseLabel = "DS: RecordArray#save " + get(this, 'type');
var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) {
return Ember.A(array);
}, null, "DS: RecordArray#save apply Ember.NativeArray");
return DS.PromiseArray.create({ promise: promise });
}
});
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get;
/**
@class FilteredRecordArray
@namespace DS
@extends DS.RecordArray
*/
DS.FilteredRecordArray = DS.RecordArray.extend({
filterFunction: null,
isLoaded: true,
replace: function() {
var type = get(this, 'type').toString();
throw new Error("The result of a client-side filter (on " + type + ") is immutable.");
},
updateFilter: Ember.observer(function() {
var manager = get(this, 'manager');
manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction'));
}, 'filterFunction')
});
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
/**
@class AdapterPopulatedRecordArray
@namespace DS
@extends DS.RecordArray
*/
DS.AdapterPopulatedRecordArray = DS.RecordArray.extend({
query: null,
replace: function() {
var type = get(this, 'type').toString();
throw new Error("The result of a server query (on " + type + ") is immutable.");
},
load: function(data) {
var store = get(this, 'store'),
type = get(this, 'type'),
records = store.pushMany(type, data),
meta = store.metadataFor(type);
this.setProperties({
content: Ember.A(records),
isLoaded: true,
meta: meta
});
// TODO: does triggering didLoad event should be the last action of the runLoop?
Ember.run.once(this, 'trigger', 'didLoad');
}
});
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var map = Ember.EnumerableUtils.map;
/**
A ManyArray is a RecordArray that represents the contents of a has-many
relationship.
The ManyArray is instantiated lazily the first time the relationship is
requested.
### Inverses
Often, the relationships in Ember Data applications will have
an inverse. For example, imagine the following models are
defined:
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
If you created a new instance of `App.Post` and added
a `App.Comment` record to its `comments` has-many
relationship, you would expect the comment's `post`
property to be set to the post that contained
the has-many.
We call the record to which a relationship belongs the
relationship's _owner_.
@class ManyArray
@namespace DS
@extends DS.RecordArray
*/
DS.ManyArray = DS.RecordArray.extend({
init: function() {
this._super.apply(this, arguments);
this._changesToSync = Ember.OrderedSet.create();
},
/**
The property name of the relationship
@property {String}
@private
*/
name: null,
/**
The record to which this relationship belongs.
@property {DS.Model}
@private
*/
owner: null,
/**
`true` if the relationship is polymorphic, `false` otherwise.
@property {Boolean}
@private
*/
isPolymorphic: false,
// LOADING STATE
isLoaded: false,
/**
Used for async `hasMany` arrays
to keep track of when they will resolve.
@property {Ember.RSVP.Promise}
@private
*/
promise: null,
loadingRecordsCount: function(count) {
this.loadingRecordsCount = count;
},
loadedRecord: function() {
this.loadingRecordsCount--;
if (this.loadingRecordsCount === 0) {
set(this, 'isLoaded', true);
this.trigger('didLoad');
}
},
fetch: function() {
var records = get(this, 'content'),
store = get(this, 'store'),
owner = get(this, 'owner'),
resolver = Ember.RSVP.defer("DS: ManyArray#fetch " + get(this, 'type'));
var unloadedRecords = records.filterProperty('isEmpty', true);
store.fetchMany(unloadedRecords, owner, resolver);
},
// Overrides Ember.Array's replace method to implement
replaceContent: function(index, removed, added) {
// Map the array of record objects into an array of client ids.
added = map(added, function(record) {
Ember.assert("You cannot add '" + record.constructor.typeKey + "' records to this relationship (only '" + this.type.typeKey + "' allowed)", !this.type || record instanceof this.type);
return record;
}, this);
this._super(index, removed, added);
},
arrangedContentDidChange: function() {
Ember.run.once(this, 'fetch');
},
arrayContentWillChange: function(index, removed, added) {
var owner = get(this, 'owner'),
name = get(this, 'name');
if (!owner._suspendedRelationships) {
// This code is the first half of code that continues inside
// of arrayContentDidChange. It gets or creates a change from
// the child object, adds the current owner as the old
// parent if this is the first time the object was removed
// from a ManyArray, and sets `newParent` to null.
//
// Later, if the object is added to another ManyArray,
// the `arrayContentDidChange` will set `newParent` on
// the change.
for (var i=index; i<index+removed; i++) {
var record = get(this, 'content').objectAt(i);
var change = DS.RelationshipChange.createChange(owner, record, get(this, 'store'), {
parentType: owner.constructor,
changeType: "remove",
kind: "hasMany",
key: name
});
this._changesToSync.add(change);
}
}
return this._super.apply(this, arguments);
},
arrayContentDidChange: function(index, removed, added) {
this._super.apply(this, arguments);
var owner = get(this, 'owner'),
name = get(this, 'name'),
store = get(this, 'store');
if (!owner._suspendedRelationships) {
// This code is the second half of code that started in
// `arrayContentWillChange`. It gets or creates a change
// from the child object, and adds the current owner as
// the new parent.
for (var i=index; i<index+added; i++) {
var record = get(this, 'content').objectAt(i);
var change = DS.RelationshipChange.createChange(owner, record, store, {
parentType: owner.constructor,
changeType: "add",
kind:"hasMany",
key: name
});
change.hasManyName = name;
this._changesToSync.add(change);
}
// We wait until the array has finished being
// mutated before syncing the OneToManyChanges created
// in arrayContentWillChange, so that the array
// membership test in the sync() logic operates
// on the final results.
this._changesToSync.forEach(function(change) {
change.sync();
});
this._changesToSync.clear();
}
},
// Create a child record within the owner
createRecord: function(hash) {
var owner = get(this, 'owner'),
store = get(owner, 'store'),
type = get(this, 'type'),
record;
Ember.assert("You cannot add '" + type.typeKey + "' records to this polymorphic relationship.", !get(this, 'isPolymorphic'));
record = store.createRecord.call(store, type, hash);
this.pushObject(record);
return record;
}
});
})();
(function() {
/**
@module ember-data
*/
})();
(function() {
/*globals Ember*/
/*jshint eqnull:true*/
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var once = Ember.run.once;
var isNone = Ember.isNone;
var forEach = Ember.EnumerableUtils.forEach;
var indexOf = Ember.EnumerableUtils.indexOf;
var map = Ember.EnumerableUtils.map;
var resolve = Ember.RSVP.resolve;
var copy = Ember.copy;
// Implementors Note:
//
// The variables in this file are consistently named according to the following
// scheme:
//
// * +id+ means an identifier managed by an external source, provided inside
// the data provided by that source. These are always coerced to be strings
// before being used internally.
// * +clientId+ means a transient numerical identifier generated at runtime by
// the data store. It is important primarily because newly created objects may
// not yet have an externally generated id.
// * +reference+ means a record reference object, which holds metadata about a
// record, even if it has not yet been fully materialized.
// * +type+ means a subclass of DS.Model.
// Used by the store to normalize IDs entering the store. Despite the fact
// that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`),
// it is important that internally we use strings, since IDs may be serialized
// and lose type information. For example, Ember's router may put a record's
// ID into the URL, and if we later try to deserialize that URL and find the
// corresponding record, we will not know if it is a string or a number.
var coerceId = function(id) {
return id == null ? null : id+'';
};
/**
The store contains all of the data for records loaded from the server.
It is also responsible for creating instances of DS.Model that wrap
the individual data for a record, so that they can be bound to in your
Handlebars templates.
Define your application's store like this:
```javascript
MyApp.Store = DS.Store.extend();
```
Most Ember.js applications will only have a single `DS.Store` that is
automatically created by their `Ember.Application`.
You can retrieve models from the store in several ways. To retrieve a record
for a specific id, use `DS.Model`'s `find()` method:
```javascript
var person = App.Person.find(123);
```
If your application has multiple `DS.Store` instances (an unusual case), you can
specify which store should be used:
```javascript
var person = store.find(App.Person, 123);
```
In general, you should retrieve models using the methods on `DS.Model`; you should
rarely need to interact with the store directly.
By default, the store will talk to your backend using a standard REST mechanism.
You can customize how the store talks to your backend by specifying a custom adapter:
```javascript
MyApp.store = DS.Store.create({
adapter: 'MyApp.CustomAdapter'
});
```
You can learn more about writing a custom adapter by reading the `DS.Adapter`
documentation.
@class Store
@namespace DS
@extends Ember.Object
*/
DS.Store = Ember.Object.extend({
/**
@method init
@private
*/
init: function() {
// internal bookkeeping; not observable
this.typeMaps = {};
this.recordArrayManager = DS.RecordArrayManager.create({
store: this
});
this._relationshipChanges = {};
this._pendingSave = [];
},
/**
The adapter to use to communicate to a backend server or other persistence layer.
This can be specified as an instance, class, or string.
If you want to specify `App.CustomAdapter` as a string, do:
```js
adapter: 'custom'
```
@property adapter
@default DS.RESTAdapter
@type {DS.Adapter|String}
*/
adapter: '_rest',
/**
Returns a JSON representation of the record using a custom
type-specific serializer, if one exists.
The available options are:
* `includeId`: `true` if the record's ID should be included in
the JSON representation
@method serialize
@private
@param {DS.Model} record the record to serialize
@param {Object} options an options hash
*/
serialize: function(record, options) {
return this.serializerFor(record.constructor.typeKey).serialize(record, options);
},
/**
This property returns the adapter, after resolving a possible
string key.
If the supplied `adapter` was a class, or a String property
path resolved to a class, this property will instantiate the
class.
This property is cacheable, so the same instance of a specified
adapter class should be used for the lifetime of the store.
@property defaultAdapter
@private
@returns DS.Adapter
*/
defaultAdapter: Ember.computed('adapter', function() {
var adapter = get(this, 'adapter');
Ember.assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name or a factory', !(adapter instanceof DS.Adapter));
if (typeof adapter === 'string') {
adapter = this.container.lookup('adapter:' + adapter) || this.container.lookup('adapter:application') || this.container.lookup('adapter:_rest');
}
if (DS.Adapter.detect(adapter)) {
adapter = adapter.create({ container: this.container });
}
return adapter;
}),
// .....................
// . CREATE NEW RECORD .
// .....................
/**
Create a new record in the current store. The properties passed
to this method are set on the newly created record.
To create a new instance of `App.Post`:
```js
store.createRecord('post', {
title: "Rails is omakase"
});
```
@method createRecord
@param {String} type
@param {Object} properties a hash of properties to set on the
newly created record.
@returns DS.Model
*/
createRecord: function(type, properties) {
type = this.modelFor(type);
properties = copy(properties) || {};
// If the passed properties do not include a primary key,
// give the adapter an opportunity to generate one. Typically,
// client-side ID generators will use something like uuid.js
// to avoid conflicts.
if (isNone(properties.id)) {
properties.id = this._generateId(type);
}
// Coerce ID to a string
properties.id = coerceId(properties.id);
var record = this.buildRecord(type, properties.id);
// Move the record out of its initial `empty` state into
// the `loaded` state.
record.loadedData();
// Set the properties specified on the record.
record.setProperties(properties);
return record;
},
/**
If possible, this method asks the adapter to generate an ID for
a newly created record.
@method generateId
@param {String} type
@returns String if the adapter can generate one, an ID
*/
_generateId: function(type) {
var adapter = this.adapterFor(type);
if (adapter && adapter.generateIdForRecord) {
return adapter.generateIdForRecord(this);
}
return null;
},
// .................
// . DELETE RECORD .
// .................
/**
For symmetry, a record can be deleted via the store.
@method deleteRecord
@param {DS.Model} record
*/
deleteRecord: function(record) {
record.deleteRecord();
},
/**
For symmetry, a record can be unloaded via the store.
@method unloadRecord
@param {DS.Model} record
*/
unloadRecord: function(record) {
record.unloadRecord();
},
// ................
// . FIND RECORDS .
// ................
/**
This is the main entry point into finding records. The first parameter to
this method is the model's name as a string.
---
To find a record by ID, pass the `id` as the second parameter:
```javascript
store.find('person', 1);
```
The `find` method will always return a **promise** that will be resolved
with the record. If the record was already in the store, the promise will
be resolved immediately. Otherwise, the store will ask the adapter's `find`
method to find the necessary data.
The `find` method will always resolve its promise with the same object for
a given type and `id`.
---
To find all records for a type, call `find` with no additional parameters:
```javascript
store.find('person');
```
This will ask the adapter's `findAll` method to find the records for the
given type, and return a promise that will be resolved once the server
returns the values.
---
To find a record by a query, call `find` with a hash as the second
parameter:
```javascript
store.find(App.Person, { page: 1 });
```
This will ask the adapter's `findQuery` method to find the records for
the query, and return a promise that will be resolved once the server
responds.
@method find
@param {DS.Model} type
@param {Object|String|Integer|null} id
*/
find: function(type, id) {
if (id === undefined) {
return this.findAll(type);
}
// We are passed a query instead of an id.
if (Ember.typeOf(id) === 'object') {
return this.findQuery(type, id);
}
return this.findById(type, coerceId(id));
},
/**
This method returns a record for a given type and id combination.
@method findById
@private
@param type
@param id
*/
findById: function(type, id) {
type = this.modelFor(type);
var record = this.recordForId(type, id);
var promise = this.fetchRecord(record) || resolve(record, "DS: Store#findById " + type + " with id: " + id);
return promiseObject(promise);
},
/**
This method makes a series of requests to the adapter's `find` method
and returns a promise that resolves once they are all loaded.
@private
@method findByIds
@param {String} type
@param {Array} ids
@returns Promise
*/
findByIds: function(type, ids) {
var store = this;
var promiseLabel = "DS: Store#findByIds " + type;
return promiseArray(Ember.RSVP.all(map(ids, function(id) {
return store.findById(type, id);
})).then(Ember.A, null, "DS: Store#findByIds of " + type + " complete"));
},
/**
This method is called by `findById` if it discovers that a particular
type/id pair hasn't been loaded yet to kick off a request to the
adapter.
@method fetchRecord
@private
@param {DS.Model} record
@returns Promise
*/
fetchRecord: function(record) {
if (isNone(record)) { return null; }
if (record._loadingPromise) { return record._loadingPromise; }
if (!get(record, 'isEmpty')) { return null; }
var type = record.constructor,
id = get(record, 'id'),
resolver = Ember.RSVP.defer("DS: Store#fetchRecord " + record );
record.loadingData(resolver.promise);
var adapter = this.adapterFor(type);
Ember.assert("You tried to find a record but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to find a record but your adapter (for " + type + ") does not implement 'find'", adapter.find);
resolver.resolve(_find(adapter, this, type, id));
return resolver.promise;
},
/**
Get a record by a given type and ID without triggering a fetch.
This method will synchronously return the record if it's available.
Otherwise, it will return null.
```js
var post = store.getById('post', 1);
```
@method getById
@param type
@param id
*/
getById: function(type, id) {
if (this.hasRecordForId(type, id)) {
return this.recordForId(type, id);
} else {
return null;
}
},
/**
This method is called by the record's `reload` method. The record's `reload`
passes in a resolver for the promise it returns.
This method calls the adapter's `find` method, which returns a promise. When
**that** promise resolves, `reloadRecord` will resolve the promise returned
by the record's `reload`.
@method reloadRecord
@private
@param {DS.Model} record
@param {Resolver} resolver
*/
reloadRecord: function(record) {
var type = record.constructor,
adapter = this.adapterFor(type),
id = get(record, 'id');
Ember.assert("You cannot reload a record without an ID", id);
Ember.assert("You tried to reload a record but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to reload a record but your adapter does not implement `find`", adapter.find);
return _find(adapter, this, type, id);
},
/**
This method takes a list of records, groups the records by type,
converts the records into IDs, and then invokes the adapter's `findMany`
method.
The records are grouped by type to invoke `findMany` on adapters
for each unique type in records.
It is used both by a brand new relationship (via the `findMany`
method) or when the data underlying an existing relationship
changes.
@method fetchMany
@private
@param records
@param owner
*/
fetchMany: function(records, owner, resolver) {
if (!records.length) { return; }
// Group By Type
var recordsByTypeMap = Ember.MapWithDefault.create({
defaultValue: function() { return Ember.A(); }
});
forEach(records, function(record) {
recordsByTypeMap.get(record.constructor).push(record);
});
forEach(recordsByTypeMap, function(type, records) {
var ids = records.mapProperty('id'),
adapter = this.adapterFor(type);
Ember.assert("You tried to load many records but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load many records but your adapter does not implement `findMany`", adapter.findMany);
resolver.resolve(_findMany(adapter, this, type, ids, owner));
}, this);
},
/**
Returns true if a record for a given type and ID is already loaded.
@method hasRecordForId
@param {DS.Model} type
@param {String|Integer} id
@returns Boolean
*/
hasRecordForId: function(type, id) {
id = coerceId(id);
type = this.modelFor(type);
return !!this.typeMapFor(type).idToRecord[id];
},
/**
Returns id record for a given type and ID. If one isn't already loaded,
it builds a new record and leaves it in the `empty` state.
@method recordForId
@param {String} type
@param {String|Integer} id
@returns DS.Model
*/
recordForId: function(type, id) {
type = this.modelFor(type);
id = coerceId(id);
var record = this.typeMapFor(type).idToRecord[id];
if (!record) {
record = this.buildRecord(type, id);
}
return record;
},
/**
@method findMany
@private
@param {DS.Model} owner
@param {Array<DS.Model>} records
@param {String} type
@param {Resolver} resolver
@return DS.ManyArray
*/
findMany: function(owner, records, type, resolver) {
type = this.modelFor(type);
records = Ember.A(records);
var unloadedRecords = records.filterProperty('isEmpty', true),
manyArray = this.recordArrayManager.createManyArray(type, records);
forEach(unloadedRecords, function(record) {
record.loadingData();
});
manyArray.loadingRecordsCount = unloadedRecords.length;
if (unloadedRecords.length) {
forEach(unloadedRecords, function(record) {
this.recordArrayManager.registerWaitingRecordArray(record, manyArray);
}, this);
this.fetchMany(unloadedRecords, owner, resolver);
} else {
if (resolver) { resolver.resolve(); }
manyArray.set('isLoaded', true);
Ember.run.once(manyArray, 'trigger', 'didLoad');
}
return manyArray;
},
/**
If a relationship was originally populated by the adapter as a link
(as opposed to a list of IDs), this method is called when the
relationship is fetched.
The link (which is usually a URL) is passed through unchanged, so the
adapter can make whatever request it wants.
The usual use-case is for the server to register a URL as a link, and
then use that URL in the future to make a request for the relationship.
@method findHasMany
@private
@param {DS.Model} owner
@param {any} link
@param {String} type
@param {Resolver} resolver
@return DS.ManyArray
*/
findHasMany: function(owner, link, relationship, resolver) {
var adapter = this.adapterFor(owner.constructor);
Ember.assert("You tried to load a hasMany relationship but you have no adapter (for " + owner.constructor + ")", adapter);
Ember.assert("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", adapter.findHasMany);
var records = this.recordArrayManager.createManyArray(relationship.type, Ember.A([]));
resolver.resolve(_findHasMany(adapter, this, owner, link, relationship));
return records;
},
findBelongsTo: function(owner, link, relationship, resolver) {
var adapter = this.adapterFor(owner.constructor);
Ember.assert("You tried to load a belongsTo relationship but you have no adapter (for " + owner.constructor + ")", adapter);
Ember.assert("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", adapter.findBelongsTo);
resolver.resolve(_findBelongsTo(adapter, this, owner, link, relationship));
},
/**
This method delegates a query to the adapter. This is the one place where
adapter-level semantics are exposed to the application.
Exposing queries this way seems preferable to creating an abstract query
language for all server-side queries, and then require all adapters to
implement them.
This method returns a promise, which is resolved with a `RecordArray`
once the server returns.
@method findQuery
@private
@param {String} type
@param {any} query an opaque query to be used by the adapter
@return Promise
*/
findQuery: function(type, query) {
type = this.modelFor(type);
var array = DS.AdapterPopulatedRecordArray.create({
type: type,
query: query,
content: Ember.A(),
store: this
});
var adapter = this.adapterFor(type),
promiseLabel = "DS: Store#findQuery " + type,
resolver = Ember.RSVP.defer(promiseLabel);
Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", adapter.findQuery);
resolver.resolve(_findQuery(adapter, this, type, query, array));
return promiseArray(resolver.promise);
},
/**
This method returns an array of all records adapter can find.
It triggers the adapter's `findAll` method to give it an opportunity to populate
the array with records of that type.
@method findAll
@private
@param {Class} type
@return {DS.AdapterPopulatedRecordArray}
*/
findAll: function(type) {
type = this.modelFor(type);
return this.fetchAll(type, this.all(type));
},
/**
@method fetchAll
@private
@param type
@param array
@returns Promise
*/
fetchAll: function(type, array) {
var adapter = this.adapterFor(type),
sinceToken = this.typeMapFor(type).metadata.since,
resolver = Ember.RSVP.defer("DS: Store#findAll " + type);
set(array, 'isUpdating', true);
Ember.assert("You tried to load all records but you have no adapter (for " + type + ")", adapter);
Ember.assert("You tried to load all records but your adapter does not implement `findAll`", adapter.findAll);
resolver.resolve(_findAll(adapter, this, type, sinceToken));
return promiseArray(resolver.promise);
},
/**
@method didUpdateAll
@param type
*/
didUpdateAll: function(type) {
var findAllCache = this.typeMapFor(type).findAllCache;
set(findAllCache, 'isUpdating', false);
},
/**
This method returns a filtered array that contains all of the known records
for a given type.
Note that because it's just a filter, it will have any locally
created records of the type.
Also note that multiple calls to `all` for a given type will always
return the same RecordArray.
@method all
@param {Class} type
@return {DS.RecordArray}
*/
all: function(type) {
type = this.modelFor(type);
var typeMap = this.typeMapFor(type),
findAllCache = typeMap.findAllCache;
if (findAllCache) { return findAllCache; }
var array = DS.RecordArray.create({
type: type,
content: Ember.A(),
store: this,
isLoaded: true
});
this.recordArrayManager.registerFilteredRecordArray(array, type);
typeMap.findAllCache = array;
return array;
},
/**
This method unloads all of the known records for a given type.
@method unloadAll
@param {Class} type
*/
unloadAll: function(type) {
type = this.modelFor(type);
var typeMap = this.typeMapFor(type),
records = typeMap.records, record;
while(record = records.pop()) {
record.unloadRecord();
}
typeMap.findAllCache = null;
},
/**
Takes a type and filter function, and returns a live RecordArray that
remains up to date as new records are loaded into the store or created
locally.
The callback function takes a materialized record, and returns true
if the record should be included in the filter and false if it should
not.
The filter function is called once on all records for the type when
it is created, and then once on each newly loaded or created record.
If any of a record's properties change, or if it changes state, the
filter function will be invoked again to determine whether it should
still be in the array.
Optionally you can pass a query which will be triggered at first. The
results returned by the server could then appear in the filter if they
match the filter function.
@method filter
@param {Class} type
@param {Object} query optional query
@param {Function} filter
@return {DS.FilteredRecordArray}
*/
filter: function(type, query, filter) {
var promise;
// allow an optional server query
if (arguments.length === 3) {
promise = this.findQuery(type, query);
} else if (arguments.length === 2) {
filter = query;
}
type = this.modelFor(type);
var array = DS.FilteredRecordArray.create({
type: type,
content: Ember.A(),
store: this,
manager: this.recordArrayManager,
filterFunction: filter
});
this.recordArrayManager.registerFilteredRecordArray(array, type, filter);
if (promise) {
return promise.then(function() { return array; }, null, "DS: Store#filter of " + type);
} else {
return array;
}
},
/**
This method returns if a certain record is already loaded
in the store. Use this function to know beforehand if a find()
will result in a request or that it will be a cache hit.
@method recordIsLoaded
@param type
@param {string} id
@return {boolean}
*/
recordIsLoaded: function(type, id) {
if (!this.hasRecordForId(type, id)) { return false; }
return !get(this.recordForId(type, id), 'isEmpty');
},
/**
This method returns the metadata for a specific type.
@method metadataFor
@param {string} type
@return {object}
*/
metadataFor: function(type) {
type = this.modelFor(type);
return this.typeMapFor(type).metadata;
},
// ............
// . UPDATING .
// ............
/**
If the adapter updates attributes or acknowledges creation
or deletion, the record will notify the store to update its
membership in any filters.
To avoid thrashing, this method is invoked only once per
run loop per record.
@method dataWasUpdated
@private
@param {Class} type
@param {Number|String} clientId
@param {DS.Model} record
*/
dataWasUpdated: function(type, record) {
this.recordArrayManager.recordDidChange(record);
},
// ..............
// . PERSISTING .
// ..............
/**
This method is called by `record.save`, and gets passed a
resolver for the promise that `record.save` returns.
It schedules saving to happen at the end of the run loop.
@method scheduleSave
@private
@param {DS.Model} record
@param {Resolver} resolver
*/
scheduleSave: function(record, resolver) {
record.adapterWillCommit();
this._pendingSave.push([record, resolver]);
once(this, 'flushPendingSave');
},
/**
This method is called at the end of the run loop, and
flushes any records passed into `scheduleSave`
@method flushPendingSave
@private
*/
flushPendingSave: function() {
var pending = this._pendingSave.slice();
this._pendingSave = [];
forEach(pending, function(tuple) {
var record = tuple[0], resolver = tuple[1],
adapter = this.adapterFor(record.constructor),
operation;
if (get(record, 'isNew')) {
operation = 'createRecord';
} else if (get(record, 'isDeleted')) {
operation = 'deleteRecord';
} else {
operation = 'updateRecord';
}
resolver.resolve(_commit(adapter, this, operation, record));
}, this);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is resolved.
If the data provides a server-generated ID, it will
update the record and the store's indexes.
@method didSaveRecord
@private
@param {DS.Model} record the in-flight record
@param {Object} data optional data (see above)
*/
didSaveRecord: function(record, data) {
if (data) {
// normalize relationship IDs into records
data = normalizeRelationships(this, record.constructor, data, record);
this.updateId(record, data);
}
record.adapterDidCommit(data);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected with a `DS.InvalidError`.
@method recordWasInvalid
@private
@param {DS.Model} record
@param {Object} errors
*/
recordWasInvalid: function(record, errors) {
record.adapterDidInvalidate(errors);
},
/**
This method is called once the promise returned by an
adapter's `createRecord`, `updateRecord` or `deleteRecord`
is rejected (with anything other than a `DS.InvalidError`).
@method recordWasError
@private
@param {DS.Model} record
*/
recordWasError: function(record) {
record.adapterDidError();
},
/**
When an adapter's `createRecord`, `updateRecord` or `deleteRecord`
resolves with data, this method extracts the ID from the supplied
data.
@method updateId
@private
@param {DS.Model} record
@param {Object} data
*/
updateId: function(record, data) {
var oldId = get(record, 'id'),
id = coerceId(data.id);
Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId);
this.typeMapFor(record.constructor).idToRecord[id] = record;
set(record, 'id', id);
},
/**
Returns a map of IDs to client IDs for a given type.
@method typeMapFor
@private
@param type
*/
typeMapFor: function(type) {
var typeMaps = get(this, 'typeMaps'),
guid = Ember.guidFor(type),
typeMap;
typeMap = typeMaps[guid];
if (typeMap) { return typeMap; }
typeMap = {
idToRecord: {},
records: [],
metadata: {}
};
typeMaps[guid] = typeMap;
return typeMap;
},
// ................
// . LOADING DATA .
// ................
/**
This internal method is used by `push`.
@method _load
@private
@param {DS.Model} type
@param {Object} data
@param {Boolean} partial the data should be merged into
the existing data, not replace it.
*/
_load: function(type, data, partial) {
var id = coerceId(data.id),
record = this.recordForId(type, id);
record.setupData(data, partial);
this.recordArrayManager.recordDidChange(record);
return record;
},
/**
Returns a model class for a particular key. Used by
methods that take a type key (like `find`, `createRecord`,
etc.)
@method modelFor
@param {String or subclass of DS.Model} key
@returns {subclass of DS.Model}
*/
modelFor: function(key) {
var factory;
if (typeof key === 'string') {
factory = this.container.lookupFactory('model:' + key);
if (!factory) { throw new Ember.Error("No model was found for '" + key + "'"); }
factory.typeKey = key;
} else {
// A factory already supplied.
factory = key;
}
factory.store = this;
return factory;
},
/**
Push some data for a given type into the store.
This method expects normalized data:
* The ID is a key named `id` (an ID is mandatory)
* The names of attributes are the ones you used in
your model's `DS.attr`s.
* Your relationships must be:
* represented as IDs or Arrays of IDs
* represented as model instances
* represented as URLs, under the `links` key
For this model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr(),
lastName: DS.attr(),
children: DS.hasMany('person')
});
```
To represent the children as IDs:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
children: [1, 2, 3]
}
```
To represent the children relationship as a URL:
```js
{
id: 1,
firstName: "Tom",
lastName: "Dale",
links: {
children: "/people/1/children"
}
}
```
If you're streaming data or implementing an adapter,
make sure that you have converted the incoming data
into this form.
This method can be used both to push in brand new
records, as well as to update existing records.
@method push
@param {String} type
@param {Object} data
@returns DS.Model the record that was created or
updated.
*/
push: function(type, data, _partial) {
// _partial is an internal param used by `update`.
// If passed, it means that the data should be
// merged into the existing data, not replace it.
Ember.assert("You must include an `id` in a hash passed to `push`", data.id != null);
type = this.modelFor(type);
// normalize relationship IDs into records
data = normalizeRelationships(this, type, data);
this._load(type, data, _partial);
return this.recordForId(type, data.id);
},
/**
Push some raw data into the store.
The data will be automatically deserialized using the
serializer for the `type` param.
This method can be used both to push in brand new
records, as well as to update existing records.
You can push in more than one type of object at once.
All objects should be in the format expected by the
serializer.
```js
App.ApplicationSerializer = DS.ActiveModelSerializer;
var pushData = {
posts: [
{id: 1, post_title: "Great post", comment_ids: [2]}
],
comments: [
{id: 2, comment_body: "Insightful comment"}
]
}
store.pushPayload('post', pushData);
```
@method pushPayload
@param {String} type
@param {Object} payload
*/
pushPayload: function (type, payload) {
var serializer;
if (!payload) {
payload = type;
serializer = defaultSerializer(this.container);
Ember.assert("You cannot use `store#pushPayload` without a type unless your default serializer defines `pushPayload`", serializer.pushPayload);
} else {
serializer = this.serializerFor(type);
}
serializer.pushPayload(this, payload);
},
update: function(type, data) {
Ember.assert("You must include an `id` in a hash passed to `update`", data.id != null);
return this.push(type, data, true);
},
/**
If you have an Array of normalized data to push,
you can call `pushMany` with the Array, and it will
call `push` repeatedly for you.
@method pushMany
@param {String} type
@param {Array} datas
@return {Array<DS.Model>}
*/
pushMany: function(type, datas) {
return map(datas, function(data) {
return this.push(type, data);
}, this);
},
/**
If you have some metadata to set for a type
you can call `metaForType`.
@method metaForType
@param {String} type
@param {Object} metadata
*/
metaForType: function(type, metadata) {
type = this.modelFor(type);
Ember.merge(this.typeMapFor(type).metadata, metadata);
},
/**
Build a brand new record for a given type, ID, and
initial data.
@method buildRecord
@private
@param {subclass of DS.Model} type
@param {String} id
@param {Object} data
@returns DS.Model
*/
buildRecord: function(type, id, data) {
var typeMap = this.typeMapFor(type),
idToRecord = typeMap.idToRecord;
Ember.assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]);
// lookupFactory should really return an object that creates
// instances with the injections applied
var record = type._create({
id: id,
store: this,
container: this.container
});
if (data) {
record.setupData(data);
}
// if we're creating an item, this process will be done
// later, once the object has been persisted.
if (id) {
idToRecord[id] = record;
}
typeMap.records.push(record);
return record;
},
// ...............
// . DESTRUCTION .
// ...............
/**
When a record is destroyed, this un-indexes it and
removes it from any record arrays so it can be GCed.
@method dematerializeRecord
@private
@param {DS.Model} record
*/
dematerializeRecord: function(record) {
var type = record.constructor,
typeMap = this.typeMapFor(type),
id = get(record, 'id');
record.updateRecordArrays();
if (id) {
delete typeMap.idToRecord[id];
}
var loc = indexOf(typeMap.records, record);
typeMap.records.splice(loc, 1);
},
// ........................
// . RELATIONSHIP CHANGES .
// ........................
addRelationshipChangeFor: function(childRecord, childKey, parentRecord, parentKey, change) {
var clientId = childRecord.clientId,
parentClientId = parentRecord ? parentRecord : parentRecord;
var key = childKey + parentKey;
var changes = this._relationshipChanges;
if (!(clientId in changes)) {
changes[clientId] = {};
}
if (!(parentClientId in changes[clientId])) {
changes[clientId][parentClientId] = {};
}
if (!(key in changes[clientId][parentClientId])) {
changes[clientId][parentClientId][key] = {};
}
changes[clientId][parentClientId][key][change.changeType] = change;
},
removeRelationshipChangeFor: function(clientRecord, childKey, parentRecord, parentKey, type) {
var clientId = clientRecord.clientId,
parentClientId = parentRecord ? parentRecord.clientId : parentRecord;
var changes = this._relationshipChanges;
var key = childKey + parentKey;
if (!(clientId in changes) || !(parentClientId in changes[clientId]) || !(key in changes[clientId][parentClientId])){
return;
}
delete changes[clientId][parentClientId][key][type];
},
relationshipChangePairsFor: function(record){
var toReturn = [];
if( !record ) { return toReturn; }
//TODO(Igor) What about the other side
var changesObject = this._relationshipChanges[record.clientId];
for (var objKey in changesObject){
if(changesObject.hasOwnProperty(objKey)){
for (var changeKey in changesObject[objKey]){
if(changesObject[objKey].hasOwnProperty(changeKey)){
toReturn.push(changesObject[objKey][changeKey]);
}
}
}
}
return toReturn;
},
// ......................
// . PER-TYPE ADAPTERS
// ......................
/**
Returns the adapter for a given type.
@method adapterFor
@private
@param {subclass of DS.Model} type
@returns DS.Adapter
*/
adapterFor: function(type) {
var container = this.container, adapter;
if (container) {
adapter = container.lookup('adapter:' + type.typeKey) || container.lookup('adapter:application');
}
return adapter || get(this, 'defaultAdapter');
},
// ..............................
// . RECORD CHANGE NOTIFICATION .
// ..............................
/**
Returns an instance of the serializer for a given type. For
example, `serializerFor('person')` will return an instance of
`App.PersonSerializer`.
If no `App.PersonSerializer` is found, this method will look
for an `App.ApplicationSerializer` (the default serializer for
your entire application).
If no `App.ApplicationSerializer` is found, it will fall back
to an instance of `DS.JSONSerializer`.
@method serializerFor
@private
@param {String} type the record to serialize
*/
serializerFor: function(type) {
type = this.modelFor(type);
var adapter = this.adapterFor(type);
return serializerFor(this.container, type.typeKey, adapter && adapter.defaultSerializer);
}
});
function normalizeRelationships(store, type, data, record) {
type.eachRelationship(function(key, relationship) {
// A link (usually a URL) was already provided in
// normalized form
if (data.links && data.links[key]) {
if (record && relationship.options.async) { record._relationships[key] = null; }
return;
}
var kind = relationship.kind,
value = data[key];
if (value == null) { return; }
if (kind === 'belongsTo') {
deserializeRecordId(store, data, key, relationship, value);
} else if (kind === 'hasMany') {
deserializeRecordIds(store, data, key, relationship, value);
addUnsavedRecords(record, key, value);
}
});
return data;
}
function deserializeRecordId(store, data, key, relationship, id) {
if (isNone(id) || id instanceof DS.Model) {
return;
}
var type;
if (typeof id === 'number' || typeof id === 'string') {
type = typeFor(relationship, key, data);
data[key] = store.recordForId(type, id);
} else if (typeof id === 'object') {
// polymorphic
data[key] = store.recordForId(id.type, id.id);
}
}
function typeFor(relationship, key, data) {
if (relationship.options.polymorphic) {
return data[key + "Type"];
} else {
return relationship.type;
}
}
function deserializeRecordIds(store, data, key, relationship, ids) {
for (var i=0, l=ids.length; i<l; i++) {
deserializeRecordId(store, ids, i, relationship, ids[i]);
}
}
// If there are any unsaved records that are in a hasMany they won't be
// in the payload, so add them back in manually.
function addUnsavedRecords(record, key, data) {
if(record) {
data.pushObjects(record.get(key).filterBy('isNew'));
}
}
// Delegation to the adapter and promise management
DS.PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin);
DS.PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin);
function promiseObject(promise) {
return DS.PromiseObject.create({ promise: promise });
}
function promiseArray(promise) {
return DS.PromiseArray.create({ promise: promise });
}
function isThenable(object) {
return object && typeof object.then === 'function';
}
function serializerFor(container, type, defaultSerializer) {
return container.lookup('serializer:'+type) ||
container.lookup('serializer:application') ||
container.lookup('serializer:' + defaultSerializer) ||
container.lookup('serializer:_default');
}
function defaultSerializer(container) {
return container.lookup('serializer:application') ||
container.lookup('serializer:_default');
}
function serializerForAdapter(adapter, type) {
var serializer = adapter.serializer,
defaultSerializer = adapter.defaultSerializer,
container = adapter.container;
if (container && serializer === undefined) {
serializer = serializerFor(container, type.typeKey, defaultSerializer);
}
if (serializer === null || serializer === undefined) {
serializer = {
extract: function(store, type, payload) { return payload; }
};
}
return serializer;
}
function _find(adapter, store, type, id) {
var promise = adapter.find(store, type, id),
serializer = serializerForAdapter(adapter, type);
return resolve(promise, "DS: Handle Adapter#find of " + type + " with id: " + id).then(function(payload) {
Ember.assert("You made a request for a " + type.typeKey + " with id " + id + ", but the adapter's response did not have any data", payload);
payload = serializer.extract(store, type, payload, id, 'find');
return store.push(type, payload);
}, function(error) {
var record = store.getById(type, id);
record.notFound();
throw error;
}, "DS: Extract payload of '" + type + "'");
}
function _findMany(adapter, store, type, ids, owner) {
var promise = adapter.findMany(store, type, ids, owner),
serializer = serializerForAdapter(adapter, type);
return resolve(promise, "DS: Handle Adapter#findMany of " + type).then(function(payload) {
payload = serializer.extract(store, type, payload, null, 'findMany');
Ember.assert("The response from a findMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
store.pushMany(type, payload);
}, null, "DS: Extract payload of " + type);
}
function _findHasMany(adapter, store, record, link, relationship) {
var promise = adapter.findHasMany(store, record, link, relationship),
serializer = serializerForAdapter(adapter, relationship.type);
return resolve(promise, "DS: Handle Adapter#findHasMany of " + record + " : " + relationship.type).then(function(payload) {
payload = serializer.extract(store, relationship.type, payload, null, 'findHasMany');
Ember.assert("The response from a findHasMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
var records = store.pushMany(relationship.type, payload);
record.updateHasMany(relationship.key, records);
}, null, "DS: Extract payload of " + record + " : hasMany " + relationship.type);
}
function _findBelongsTo(adapter, store, record, link, relationship) {
var promise = adapter.findBelongsTo(store, record, link, relationship),
serializer = serializerForAdapter(adapter, relationship.type);
return resolve(promise, "DS: Handle Adapter#findBelongsTo of " + record + " : " + relationship.type).then(function(payload) {
payload = serializer.extract(store, relationship.type, payload, null, 'findBelongsTo');
var record = store.push(relationship.type, payload);
record.updateBelongsTo(relationship.key, record);
return record;
}, null, "DS: Extract payload of " + record + " : " + relationship.type);
}
function _findAll(adapter, store, type, sinceToken) {
var promise = adapter.findAll(store, type, sinceToken),
serializer = serializerForAdapter(adapter, type);
return resolve(promise, "DS: Handle Adapter#findAll of " + type).then(function(payload) {
payload = serializer.extract(store, type, payload, null, 'findAll');
Ember.assert("The response from a findAll must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
store.pushMany(type, payload);
store.didUpdateAll(type);
return store.all(type);
}, null, "DS: Extract payload of findAll " + type);
}
function _findQuery(adapter, store, type, query, recordArray) {
var promise = adapter.findQuery(store, type, query, recordArray),
serializer = serializerForAdapter(adapter, type);
return resolve(promise, "DS: Handle Adapter#findQuery of " + type).then(function(payload) {
payload = serializer.extract(store, type, payload, null, 'findAll');
Ember.assert("The response from a findQuery must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array');
recordArray.load(payload);
return recordArray;
}, null, "DS: Extract payload of findQuery " + type);
}
function _commit(adapter, store, operation, record) {
var type = record.constructor,
promise = adapter[operation](store, type, record),
serializer = serializerForAdapter(adapter, type);
Ember.assert("Your adapter's '" + operation + "' method must return a promise, but it returned " + promise, isThenable(promise));
return promise.then(function(payload) {
if (payload) { payload = serializer.extract(store, type, payload, get(record, 'id'), operation); }
store.didSaveRecord(record, payload);
return record;
}, function(reason) {
if (reason instanceof DS.InvalidError) {
store.recordWasInvalid(record, reason.errors);
} else {
store.recordWasError(record, reason);
}
throw reason;
}, "DS: Extract and notify about " + operation + " completion of " + record);
}
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
/*
This file encapsulates the various states that a record can transition
through during its lifecycle.
*/
/**
### State
Each record has a `currentState` property that explicitly tracks what
state a record is in at any given time. For instance, if a record is
newly created and has not yet been sent to the adapter to be saved,
it would be in the `root.loaded.created.uncommitted` state. If a
record has had local modifications made to it that are in the
process of being saved, the record would be in the
`root.loaded.updated.inFlight` state. (These state paths will be
explained in more detail below.)
Events are sent by the record or its store to the record's
`currentState` property. How the state reacts to these events is
dependent on which state it is in. In some states, certain events
will be invalid and will cause an exception to be raised.
States are hierarchical and every state is a substate of the
`RootState`. For example, a record can be in the
`root.deleted.uncommitted` state, then transition into the
`root.deleted.inFlight` state. If a child state does not implement
an event handler, the state manager will attempt to invoke the event
on all parent states until the root state is reached. The state
hierarchy of a record is described in terms of a path string. You
can determine a record's current state by getting the state's
`stateName` property:
```javascript
record.get('currentState.stateName');
//=> "root.created.uncommitted"
```
The hierarchy of valid states that ship with ember data looks like
this:
```text
* root
* deleted
* saved
* uncommitted
* inFlight
* empty
* loaded
* created
* uncommitted
* inFlight
* saved
* updated
* uncommitted
* inFlight
* loading
```
The `DS.Model` states are themselves stateless. What we mean is
that, the hierarchical states that each of *those* points to is a
shared data structure. For performance reasons, instead of each
record getting its own copy of the hierarchy of states, each record
points to this global, immutable shared instance. How does a state
know which record it should be acting on? We pass the record
instance into the state's event handlers as the first argument.
The record passed as the first parameter is where you should stash
state about the record if needed; you should never store data on the state
object itself.
### Events and Flags
A state may implement zero or more events and flags.
#### Events
Events are named functions that are invoked when sent to a record. The
record will first look for a method with the given name on the
current state. If no method is found, it will search the current
state's parent, and then its grandparent, and so on until reaching
the top of the hierarchy. If the root is reached without an event
handler being found, an exception will be raised. This can be very
helpful when debugging new features.
Here's an example implementation of a state with a `myEvent` event handler:
```javascript
aState: DS.State.create({
myEvent: function(manager, param) {
console.log("Received myEvent with", param);
}
})
```
To trigger this event:
```javascript
record.send('myEvent', 'foo');
//=> "Received myEvent with foo"
```
Note that an optional parameter can be sent to a record's `send()` method,
which will be passed as the second parameter to the event handler.
Events should transition to a different state if appropriate. This can be
done by calling the record's `transitionTo()` method with a path to the
desired state. The state manager will attempt to resolve the state path
relative to the current state. If no state is found at that path, it will
attempt to resolve it relative to the current state's parent, and then its
parent, and so on until the root is reached. For example, imagine a hierarchy
like this:
* created
* uncommitted <-- currentState
* inFlight
* updated
* inFlight
If we are currently in the `uncommitted` state, calling
`transitionTo('inFlight')` would transition to the `created.inFlight` state,
while calling `transitionTo('updated.inFlight')` would transition to
the `updated.inFlight` state.
Remember that *only events* should ever cause a state transition. You should
never call `transitionTo()` from outside a state's event handler. If you are
tempted to do so, create a new event and send that to the state manager.
#### Flags
Flags are Boolean values that can be used to introspect a record's current
state in a more user-friendly way than examining its state path. For example,
instead of doing this:
```javascript
var statePath = record.get('stateManager.currentPath');
if (statePath === 'created.inFlight') {
doSomething();
}
```
You can say:
```javascript
if (record.get('isNew') && record.get('isSaving')) {
doSomething();
}
```
If your state does not set a value for a given flag, the value will
be inherited from its parent (or the first place in the state hierarchy
where it is defined).
The current set of flags are defined below. If you want to add a new flag,
in addition to the area below, you will also need to declare it in the
`DS.Model` class.
* [isEmpty](DS.Model.html#property_isEmpty)
* [isLoading](DS.Model.html#property_isLoading)
* [isLoaded](DS.Model.html#property_isLoaded)
* [isDirty](DS.Model.html#property_isDirty)
* [isSaving](DS.Model.html#property_isSaving)
* [isDeleted](DS.Model.html#property_isDeleted)
* [isNew](DS.Model.html#property_isNew)
* [isValid](DS.Model.html#property_isValid)
@namespace DS
@class RootState
*/
var hasDefinedProperties = function(object) {
// Ignore internal property defined by simulated `Ember.create`.
var names = Ember.keys(object);
var i, l, name;
for (i = 0, l = names.length; i < l; i++ ) {
name = names[i];
if (object.hasOwnProperty(name) && object[name]) { return true; }
}
return false;
};
var didSetProperty = function(record, context) {
if (context.value === context.originalValue) {
delete record._attributes[context.name];
record.send('propertyWasReset', context.name);
} else if (context.value !== context.oldValue) {
record.send('becomeDirty');
}
record.updateRecordArraysLater();
};
// Implementation notes:
//
// Each state has a boolean value for all of the following flags:
//
// * isLoaded: The record has a populated `data` property. When a
// record is loaded via `store.find`, `isLoaded` is false
// until the adapter sets it. When a record is created locally,
// its `isLoaded` property is always true.
// * isDirty: The record has local changes that have not yet been
// saved by the adapter. This includes records that have been
// created (but not yet saved) or deleted.
// * isSaving: The record has been committed, but
// the adapter has not yet acknowledged that the changes have
// been persisted to the backend.
// * isDeleted: The record was marked for deletion. When `isDeleted`
// is true and `isDirty` is true, the record is deleted locally
// but the deletion was not yet persisted. When `isSaving` is
// true, the change is in-flight. When both `isDirty` and
// `isSaving` are false, the change has persisted.
// * isError: The adapter reported that it was unable to save
// local changes to the backend. This may also result in the
// record having its `isValid` property become false if the
// adapter reported that server-side validations failed.
// * isNew: The record was created on the client and the adapter
// did not yet report that it was successfully saved.
// * isValid: No client-side validations have failed and the
// adapter did not report any server-side validation failures.
// The dirty state is a abstract state whose functionality is
// shared between the `created` and `updated` states.
//
// The deleted state shares the `isDirty` flag with the
// subclasses of `DirtyState`, but with a very different
// implementation.
//
// Dirty states have three child states:
//
// `uncommitted`: the store has not yet handed off the record
// to be saved.
// `inFlight`: the store has handed off the record to be saved,
// but the adapter has not yet acknowledged success.
// `invalid`: the record has invalid information and cannot be
// send to the adapter yet.
var DirtyState = {
initialState: 'uncommitted',
// FLAGS
isDirty: true,
// SUBSTATES
// When a record first becomes dirty, it is `uncommitted`.
// This means that there are local pending changes, but they
// have not yet begun to be saved, and are not invalid.
uncommitted: {
// EVENTS
didSetProperty: didSetProperty,
propertyWasReset: function(record, name) {
var stillDirty = false;
for (var prop in record._attributes) {
stillDirty = true;
break;
}
if (!stillDirty) { record.send('rolledBack'); }
},
pushedData: Ember.K,
becomeDirty: Ember.K,
willCommit: function(record) {
record.transitionTo('inFlight');
},
reloadRecord: function(record, resolve) {
resolve(get(record, 'store').reloadRecord(record));
},
rolledBack: function(record) {
record.transitionTo('loaded.saved');
},
becameInvalid: function(record) {
record.transitionTo('invalid');
},
rollback: function(record) {
record.rollback();
}
},
// Once a record has been handed off to the adapter to be
// saved, it is in the 'in flight' state. Changes to the
// record cannot be made during this window.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
didSetProperty: didSetProperty,
becomeDirty: Ember.K,
pushedData: Ember.K,
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function(record) {
var dirtyType = get(this, 'dirtyType');
record.transitionTo('saved');
record.send('invokeLifecycleCallbacks', dirtyType);
},
becameInvalid: function(record, errors) {
set(record, 'errors', errors);
record.transitionTo('invalid');
record.send('invokeLifecycleCallbacks');
},
becameError: function(record) {
record.transitionTo('uncommitted');
record.triggerLater('becameError', record);
}
},
// A record is in the `invalid` state when its client-side
// invalidations have failed, or if the adapter has indicated
// the the record failed server-side invalidations.
invalid: {
// FLAGS
isValid: false,
// EVENTS
deleteRecord: function(record) {
record.transitionTo('deleted.uncommitted');
record.clearRelationships();
},
didSetProperty: function(record, context) {
var errors = get(record, 'errors'),
key = context.name;
set(errors, key, null);
if (!hasDefinedProperties(errors)) {
record.send('becameValid');
}
didSetProperty(record, context);
},
becomeDirty: Ember.K,
rollback: function(record) {
record.send('becameValid');
record.send('rollback');
},
becameValid: function(record) {
record.transitionTo('uncommitted');
},
invokeLifecycleCallbacks: function(record) {
record.triggerLater('becameInvalid', record);
}
}
};
// The created and updated states are created outside the state
// chart so we can reopen their substates and add mixins as
// necessary.
function deepClone(object) {
var clone = {}, value;
for (var prop in object) {
value = object[prop];
if (value && typeof value === 'object') {
clone[prop] = deepClone(value);
} else {
clone[prop] = value;
}
}
return clone;
}
function mixin(original, hash) {
for (var prop in hash) {
original[prop] = hash[prop];
}
return original;
}
function dirtyState(options) {
var newState = deepClone(DirtyState);
return mixin(newState, options);
}
var createdState = dirtyState({
dirtyType: 'created',
// FLAGS
isNew: true
});
createdState.uncommitted.rolledBack = function(record) {
record.transitionTo('deleted.saved');
};
var updatedState = dirtyState({
dirtyType: 'updated'
});
createdState.uncommitted.deleteRecord = function(record) {
record.clearRelationships();
record.transitionTo('deleted.saved');
};
createdState.uncommitted.rollback = function(record) {
DirtyState.uncommitted.rollback.apply(this, arguments);
record.transitionTo('deleted.saved');
};
updatedState.uncommitted.deleteRecord = function(record) {
record.transitionTo('deleted.uncommitted');
record.clearRelationships();
};
var RootState = {
// FLAGS
isEmpty: false,
isLoading: false,
isLoaded: false,
isDirty: false,
isSaving: false,
isDeleted: false,
isNew: false,
isValid: true,
// DEFAULT EVENTS
// Trying to roll back if you're not in the dirty state
// doesn't change your state. For example, if you're in the
// in-flight state, rolling back the record doesn't move
// you out of the in-flight state.
rolledBack: Ember.K,
propertyWasReset: Ember.K,
// SUBSTATES
// A record begins its lifecycle in the `empty` state.
// If its data will come from the adapter, it will
// transition into the `loading` state. Otherwise, if
// the record is being created on the client, it will
// transition into the `created` state.
empty: {
isEmpty: true,
// EVENTS
loadingData: function(record, promise) {
record._loadingPromise = promise;
record.transitionTo('loading');
},
loadedData: function(record) {
record.transitionTo('loaded.created.uncommitted');
record.suspendRelationshipObservers(function() {
record.notifyPropertyChange('data');
});
},
pushedData: function(record) {
record.transitionTo('loaded.saved');
record.triggerLater('didLoad');
}
},
// A record enters this state when the store askes
// the adapter for its data. It remains in this state
// until the adapter provides the requested data.
//
// Usually, this process is asynchronous, using an
// XHR to retrieve the data.
loading: {
// FLAGS
isLoading: true,
exit: function(record) {
record._loadingPromise = null;
},
// EVENTS
pushedData: function(record) {
record.transitionTo('loaded.saved');
record.triggerLater('didLoad');
set(record, 'isError', false);
},
becameError: function(record) {
record.triggerLater('becameError', record);
},
notFound: function(record) {
record.transitionTo('empty');
}
},
// A record enters this state when its data is populated.
// Most of a record's lifecycle is spent inside substates
// of the `loaded` state.
loaded: {
initialState: 'saved',
// FLAGS
isLoaded: true,
// SUBSTATES
// If there are no local changes to a record, it remains
// in the `saved` state.
saved: {
setup: function(record) {
var attrs = record._attributes,
isDirty = false;
for (var prop in attrs) {
if (attrs.hasOwnProperty(prop)) {
isDirty = true;
break;
}
}
if (isDirty) {
record.adapterDidDirty();
}
},
// EVENTS
didSetProperty: didSetProperty,
pushedData: Ember.K,
becomeDirty: function(record) {
record.transitionTo('updated.uncommitted');
},
willCommit: function(record) {
record.transitionTo('updated.inFlight');
},
reloadRecord: function(record, resolve) {
resolve(get(record, 'store').reloadRecord(record));
},
deleteRecord: function(record) {
record.transitionTo('deleted.uncommitted');
record.clearRelationships();
},
unloadRecord: function(record) {
// clear relationships before moving to deleted state
// otherwise it fails
record.clearRelationships();
record.transitionTo('deleted.saved');
},
didCommit: function(record) {
record.send('invokeLifecycleCallbacks', get(record, 'lastDirtyType'));
},
// loaded.saved.notFound would be triggered by a failed
// `reload()` on an unchanged record
notFound: Ember.K
},
// A record is in this state after it has been locally
// created but before the adapter has indicated that
// it has been saved.
created: createdState,
// A record is in this state if it has already been
// saved to the server, but there are new local changes
// that have not yet been saved.
updated: updatedState
},
// A record is in this state if it was deleted from the store.
deleted: {
initialState: 'uncommitted',
dirtyType: 'deleted',
// FLAGS
isDeleted: true,
isLoaded: true,
isDirty: true,
// TRANSITIONS
setup: function(record) {
record.updateRecordArrays();
},
// SUBSTATES
// When a record is deleted, it enters the `start`
// state. It will exit this state when the record
// starts to commit.
uncommitted: {
// EVENTS
willCommit: function(record) {
record.transitionTo('inFlight');
},
rollback: function(record) {
record.rollback();
},
becomeDirty: Ember.K,
deleteRecord: Ember.K,
rolledBack: function(record) {
record.transitionTo('loaded.saved');
}
},
// After a record starts committing, but
// before the adapter indicates that the deletion
// has saved to the server, a record is in the
// `inFlight` substate of `deleted`.
inFlight: {
// FLAGS
isSaving: true,
// EVENTS
// TODO: More robust semantics around save-while-in-flight
willCommit: Ember.K,
didCommit: function(record) {
record.transitionTo('saved');
record.send('invokeLifecycleCallbacks');
},
becameError: function(record) {
record.transitionTo('uncommitted');
record.triggerLater('becameError', record);
}
},
// Once the adapter indicates that the deletion has
// been saved, the record enters the `saved` substate
// of `deleted`.
saved: {
// FLAGS
isDirty: false,
setup: function(record) {
var store = get(record, 'store');
store.dematerializeRecord(record);
},
invokeLifecycleCallbacks: function(record) {
record.triggerLater('didDelete', record);
record.triggerLater('didCommit', record);
}
}
},
invokeLifecycleCallbacks: function(record, dirtyType) {
if (dirtyType === 'created') {
record.triggerLater('didCreate', record);
} else {
record.triggerLater('didUpdate', record);
}
record.triggerLater('didCommit', record);
}
};
function wireState(object, parent, name) {
/*jshint proto:true*/
// TODO: Use Object.create and copy instead
object = mixin(parent ? Ember.create(parent) : {}, object);
object.parentState = parent;
object.stateName = name;
for (var prop in object) {
if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; }
if (typeof object[prop] === 'object') {
object[prop] = wireState(object[prop], object, name + "." + prop);
}
}
return object;
}
RootState = wireState(RootState, null, "root");
DS.RootState = RootState;
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set,
merge = Ember.merge, once = Ember.run.once;
var retrieveFromCurrentState = Ember.computed('currentState', function(key, value) {
return get(get(this, 'currentState'), key);
}).readOnly();
/**
The model class that all Ember Data records descend from.
@class Model
@namespace DS
@extends Ember.Object
@uses Ember.Evented
*/
DS.Model = Ember.Object.extend(Ember.Evented, {
/**
If this property is `true` the record is in the `empty`
state. Empty is the first state all records enter after they have
been created. Most records created by the store will quickly
transition to the `loading` state if data needs to be fetched from
the server or the `created` state if the record is created on the
client. A record can also enter the empty state if the adapter is
unable to locate the record.
@property isEmpty
@type {Boolean}
@readOnly
*/
isEmpty: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loading` state. A
record enters this state when the store askes the adapter for its
data. It remains in this state until the adapter provides the
requested data.
@property isLoading
@type {Boolean}
@readOnly
*/
isLoading: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `loaded` state. A
record enters this state when its data is populated. Most of a
record's lifecycle is spent inside substates of the `loaded`
state.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isLoaded'); // true
store.find('model', 1).then(function(model) {
model.get('isLoaded'); // true
});
```
@property isLoaded
@type {Boolean}
@readOnly
*/
isLoaded: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `dirty` state. The
record has local changes that have not yet been saved by the
adapter. This includes records that have been created (but not yet
saved) or deleted.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isDirty'); // true
store.find('model', 1).then(function(model) {
model.get('isDirty'); // false
model.set('foo', 'some value');
model.set('isDirty'); // true
});
```
@property isDirty
@type {Boolean}
@readOnly
*/
isDirty: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `saving` state. A
record enters the saving state when `save` is called, but the
adapter has not yet acknowledged that the changes have been
persisted to the backend.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isSaving'); // false
var promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
record.get('isSaving'); // false
});
```
@property isSaving
@type {Boolean}
@readOnly
*/
isSaving: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `deleted` state
and has been marked for deletion. When `isDeleted` is true and
`isDirty` is true, the record is deleted locally but the deletion
was not yet persisted. When `isSaving` is true, the change is
in-flight. When both `isDirty` and `isSaving` are false, the
change has persisted.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isDeleted'); // false
record.deleteRecord();
record.get('isDeleted'); // true
```
@property isDeleted
@type {Boolean}
@readOnly
*/
isDeleted: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `new` state. A
record will be in the `new` state when it has been created on the
client and the adapter has not yet report that it was successfully
saved.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('isNew'); // true
store.find('model', 1).then(function(model) {
model.get('isNew'); // false
});
```
@property isNew
@type {Boolean}
@readOnly
*/
isNew: retrieveFromCurrentState,
/**
If this property is `true` the record is in the `valid` state. A
record will be in the `valid` state when no client-side
validations have failed and the adapter did not report any
server-side validation failures.
@property isValid
@type {Boolean}
@readOnly
*/
isValid: retrieveFromCurrentState,
/**
If the record is in the dirty state this property will report what
kind of change has caused it to move into the dirty
state. Possible values are:
- `created` The record has been created by the client and not yet saved to the adapter.
- `updated` The record has been updated by the client and not yet saved to the adapter.
- `deleted` The record has been deleted by the client and not yet saved to the adapter.
Example
```javascript
var record = store.createRecord(App.Model);
record.get('dirtyType'); // 'created'
```
@property dirtyType
@type {String}
@readOnly
*/
dirtyType: retrieveFromCurrentState,
/**
If `true` the adapter reported that it was unable to save local
changes to the backend. This may also result in the record having
its `isValid` property become false if the adapter reported that
server-side validations failed.
Example
```javascript
record.get('isError'); // false
record.set('foo', 'invalid value');
record.save().then(null, function() {
record.get('isError'); // true
});
```
@property isError
@type {Boolean}
@readOnly
*/
isError: false,
/**
If `true` the store is attempting to reload the record form the adapter.
Example
```javascript
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true
```
@property isReloading
@type {Boolean}
@readOnly
*/
isReloading: false,
/**
The `clientId` property is a transient numerical identifier
generated at runtime by the data store. It is important
primarily because newly created objects may not yet have an
externally generated id.
@property clientId
@private
@type {Number|String}
*/
clientId: null,
/**
All ember models have an id property. This is an identifier
managed by an external source. These are always coerced to be
strings before being used internally. Note when declaring the
attributes for a model it is an error to declare an id
attribute.
```javascript
var record = store.createRecord(App.Model);
record.get('id'); // null
store.find('model', 1).then(function(model) {
model.get('id'); // '1'
});
```
@property id
@type {String}
*/
id: null,
transaction: null,
/**
@property currentState
@private
@type {Object}
*/
currentState: null,
/**
When the record is in the `invalid` state this object will contain
any errors returned by the adapter. When present the errors hash
typically contains keys coresponding to the invalid property names
and values which are an array of error messages.
```javascript
record.get('errors'); // null
record.set('foo', 'invalid value');
record.save().then(null, function() {
record.get('errors'); // {foo: ['foo should be a number.']}
});
```
@property errors
@type {Object}
*/
errors: null,
/**
Create a JSON representation of the record, using the serialization
strategy of the store's adapter.
`serialize` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method serialize
@param {Object} options
@returns {Object} an object whose values are primitive JSON values only
*/
serialize: function(options) {
var store = get(this, 'store');
return store.serialize(this, options);
},
/**
Use [DS.JSONSerializer](DS.JSONSerializer.html) to
get the JSON representation of a record.
`toJSON` takes an optional hash as a parameter, currently
supported options are:
- `includeId`: `true` if the record's ID should be included in the
JSON representation.
@method toJSON
@param {Object} options
@returns {Object} A JSON representation of the object.
*/
toJSON: function(options) {
// container is for lazy transform lookups
var serializer = DS.JSONSerializer.create({ container: this.container });
return serializer.serialize(this, options);
},
/**
Fired when the record is loaded from the server.
@event didLoad
*/
didLoad: Ember.K,
/**
Fired when the record is updated.
@event didUpdate
*/
didUpdate: Ember.K,
/**
Fired when the record is created.
@event didCreate
*/
didCreate: Ember.K,
/**
Fired when the record is deleted.
@event didDelete
*/
didDelete: Ember.K,
/**
Fired when the record becomes invalid.
@event becameInvalid
*/
becameInvalid: Ember.K,
/**
Fired when the record enters the error state.
@event becameError
*/
becameError: Ember.K,
/**
@property data
@private
@type {Object}
*/
data: Ember.computed(function() {
this._data = this._data || {};
return this._data;
}).property(),
_data: null,
init: function() {
set(this, 'currentState', DS.RootState.empty);
this._super();
this._setup();
},
_setup: function() {
this._changesToSync = {};
this._deferredTriggers = [];
this._data = {};
this._attributes = {};
this._inFlightAttributes = {};
this._relationships = {};
},
/**
@method send
@private
@param {String} name
@param {Object} context
*/
send: function(name, context) {
var currentState = get(this, 'currentState');
if (!currentState[name]) {
this._unhandledEvent(currentState, name, context);
}
return currentState[name](this, context);
},
/**
@method transitionTo
@private
@param {String} name
*/
transitionTo: function(name) {
// POSSIBLE TODO: Remove this code and replace with
// always having direct references to state objects
var pivotName = name.split(".", 1),
currentState = get(this, 'currentState'),
state = currentState;
do {
if (state.exit) { state.exit(this); }
state = state.parentState;
} while (!state.hasOwnProperty(pivotName));
var path = name.split(".");
var setups = [], enters = [], i, l;
for (i=0, l=path.length; i<l; i++) {
state = state[path[i]];
if (state.enter) { enters.push(state); }
if (state.setup) { setups.push(state); }
}
for (i=0, l=enters.length; i<l; i++) {
enters[i].enter(this);
}
set(this, 'currentState', state);
for (i=0, l=setups.length; i<l; i++) {
setups[i].setup(this);
}
this.updateRecordArraysLater();
},
_unhandledEvent: function(state, name, context) {
var errorMessage = "Attempted to handle event `" + name + "` ";
errorMessage += "on " + String(this) + " while in state ";
errorMessage += state.stateName + ". ";
if (context !== undefined) {
errorMessage += "Called with " + Ember.inspect(context) + ".";
}
throw new Ember.Error(errorMessage);
},
withTransaction: function(fn) {
var transaction = get(this, 'transaction');
if (transaction) { fn(transaction); }
},
/**
@method loadingData
@private
@param {Promise} promise
*/
loadingData: function(promise) {
this.send('loadingData', promise);
},
/**
@method loadedData
@private
*/
loadedData: function() {
this.send('loadedData');
},
/**
@method notFound
@private
*/
notFound: function() {
this.send('notFound');
},
/**
@method pushedData
@private
*/
pushedData: function() {
this.send('pushedData');
},
/**
Marks the record as deleted but does not save it. You must call
`save` afterwards if you want to persist it. You might use this
method if you want to allow the user to still `rollback()` a
delete after it was made.
Example
```javascript
App.ModelDeleteRoute = Ember.Route.extend({
actions: {
softDelete: function() {
this.get('model').deleteRecord();
},
confirm: function() {
this.get('model').save();
},
undo: function() {
this.get('model').rollback();
}
}
});
```
@method deleteRecord
*/
deleteRecord: function() {
this.send('deleteRecord');
},
/**
Same as `deleteRecord`, but saves the record immediately.
Example
```javascript
App.ModelDeleteRoute = Ember.Route.extend({
actions: {
delete: function() {
var controller = this.controller;
this.get('model').destroyRecord().then(function() {
controller.transitionToRoute('model.index');
});
}
}
});
```
@method destroyRecord
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
destroyRecord: function() {
this.deleteRecord();
return this.save();
},
/**
@method unloadRecord
@private
*/
unloadRecord: function() {
Ember.assert("You can only unload a loaded, non-dirty record.", !get(this, 'isDirty'));
this.send('unloadRecord');
},
/**
@method clearRelationships
@private
*/
clearRelationships: function() {
this.eachRelationship(function(name, relationship) {
if (relationship.kind === 'belongsTo') {
set(this, name, null);
} else if (relationship.kind === 'hasMany') {
var hasMany = this._relationships[relationship.name];
if (hasMany) { hasMany.clear(); }
}
}, this);
},
/**
@method updateRecordArrays
@private
*/
updateRecordArrays: function() {
get(this, 'store').dataWasUpdated(this.constructor, this);
},
/**
Returns an object, whose keys are changed properties, and value is
an [oldProp, newProp] array.
Example
```javascript
App.Mascot = DS.Model.extend({
name: attr('string')
});
var person = store.createRecord('person');
person.changedAttributes(); // {}
person.set('name', 'Tomster');
person.changedAttributes(); // {name: [undefined, 'Tomster']}
```
@method changedAttributes
@return {Object} an object, whose keys are changed properties,
and value is an [oldProp, newProp] array.
*/
changedAttributes: function() {
var oldData = get(this, '_data'),
newData = get(this, '_attributes'),
diffData = {},
prop;
for (prop in newData) {
diffData[prop] = [oldData[prop], newData[prop]];
}
return diffData;
},
/**
@method adapterWillCommit
@private
*/
adapterWillCommit: function() {
this.send('willCommit');
},
/**
If the adapter did not return a hash in response to a commit,
merge the changed attributes and relationships into the existing
saved data.
@method adapterDidCommit
*/
adapterDidCommit: function(data) {
set(this, 'isError', false);
if (data) {
this._data = data;
} else {
Ember.mixin(this._data, this._inFlightAttributes);
}
this._inFlightAttributes = {};
this.send('didCommit');
this.updateRecordArraysLater();
if (!data) { return; }
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
/**
@method adapterDidDirty
@private
*/
adapterDidDirty: function() {
this.send('becomeDirty');
this.updateRecordArraysLater();
},
dataDidChange: Ember.observer(function() {
this.reloadHasManys();
}, 'data'),
reloadHasManys: function() {
var relationships = get(this.constructor, 'relationshipsByName');
this.updateRecordArraysLater();
relationships.forEach(function(name, relationship) {
if (this._data.links && this._data.links[name]) { return; }
if (relationship.kind === 'hasMany') {
this.hasManyDidChange(relationship.key);
}
}, this);
},
hasManyDidChange: function(key) {
var hasMany = this._relationships[key];
if (hasMany) {
var records = this._data[key] || [];
set(hasMany, 'content', Ember.A(records));
set(hasMany, 'isLoaded', true);
hasMany.trigger('didLoad');
}
},
/**
@method updateRecordArraysLater
@private
*/
updateRecordArraysLater: function() {
Ember.run.once(this, this.updateRecordArrays);
},
/**
@method setupData
@private
@param {Object} data
@param {Boolean} partial the data should be merged into
the existing data, not replace it.
*/
setupData: function(data, partial) {
if (partial) {
Ember.merge(this._data, data);
} else {
this._data = data;
}
var relationships = this._relationships;
this.eachRelationship(function(name, rel) {
if (data.links && data.links[name]) { return; }
if (rel.options.async) { relationships[name] = null; }
});
if (data) { this.pushedData(); }
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
materializeId: function(id) {
set(this, 'id', id);
},
materializeAttributes: function(attributes) {
Ember.assert("Must pass a hash of attributes to materializeAttributes", !!attributes);
merge(this._data, attributes);
},
materializeAttribute: function(name, value) {
this._data[name] = value;
},
/**
@method updateHasMany
@private
@param {String} name
@param {Array} records
*/
updateHasMany: function(name, records) {
this._data[name] = records;
this.hasManyDidChange(name);
},
/**
@method updateBelongsTo
@private
@param {String} name
@param {DS.Model} record
*/
updateBelongsTo: function(name, record) {
this._data[name] = record;
},
/**
If the model `isDirty` this function will which discard any unsaved
changes
Example
```javascript
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollback();
record.get('name'); // 'Untitled Document'
```
@method rollback
*/
rollback: function() {
this._attributes = {};
if (get(this, 'isError')) {
this._inFlightAttributes = {};
set(this, 'isError', false);
}
if (!get(this, 'isValid')) {
this._inFlightAttributes = {};
this.send('becameValid');
}
this.send('rolledBack');
this.suspendRelationshipObservers(function() {
this.notifyPropertyChange('data');
});
},
toStringExtension: function() {
return get(this, 'id');
},
/**
The goal of this method is to temporarily disable specific observers
that take action in response to application changes.
This allows the system to make changes (such as materialization and
rollback) that should not trigger secondary behavior (such as setting an
inverse relationship or marking records as dirty).
The specific implementation will likely change as Ember proper provides
better infrastructure for suspending groups of observers, and if Array
observation becomes more unified with regular observers.
@method suspendRelationshipObservers
@private
@param callback
@param binding
*/
suspendRelationshipObservers: function(callback, binding) {
var observers = get(this.constructor, 'relationshipNames').belongsTo;
var self = this;
try {
this._suspendedRelationships = true;
Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() {
Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() {
callback.call(binding || self);
});
});
} finally {
this._suspendedRelationships = false;
}
},
/**
Save the record and persist any changes to the record to an
extenal source via the adapter.
Example
```javascript
record.set('name', 'Tomster');
record.save().then(function(){
// Success callback
}, function() {
// Error callback
});
```
@method save
@return {Promise} a promise that will be resolved when the adapter returns
successfully or rejected if the adapter returns with an error.
*/
save: function() {
var promiseLabel = "DS: Model#save " + this;
var resolver = Ember.RSVP.defer(promiseLabel);
this.get('store').scheduleSave(this, resolver);
this._inFlightAttributes = this._attributes;
this._attributes = {};
return DS.PromiseObject.create({ promise: resolver.promise });
},
/**
Reload the record from the adapter.
This will only work if the record has already finished loading
and has not yet been modified (`isLoaded` but not `isDirty`,
or `isSaving`).
Example
```javascript
App.ModelViewRoute = Ember.Route.extend({
actions: {
reload: function() {
this.get('model').reload();
}
}
});
```
@method reload
@return {Promise} a promise that will be resolved with the record when the
adapter returns successfully or rejected if the adapter returns
with an error.
*/
reload: function() {
set(this, 'isReloading', true);
var record = this;
var promiseLabel = "DS: Model#reload of " + this;
var promise = new Ember.RSVP.Promise(function(resolve){
record.send('reloadRecord', resolve);
}, promiseLabel).then(function() {
record.set('isReloading', false);
record.set('isError', false);
return record;
}, function(reason) {
record.set('isError', true);
throw reason;
}, "DS: Model#reload complete, update flags");
return DS.PromiseObject.create({ promise: promise });
},
// FOR USE DURING COMMIT PROCESS
adapterDidUpdateAttribute: function(attributeName, value) {
// If a value is passed in, update the internal attributes and clear
// the attribute cache so it picks up the new value. Otherwise,
// collapse the current value into the internal attributes because
// the adapter has acknowledged it.
if (value !== undefined) {
this._data[attributeName] = value;
this.notifyPropertyChange(attributeName);
} else {
this._data[attributeName] = this._inFlightAttributes[attributeName];
}
this.updateRecordArraysLater();
},
/**
@method adapterDidInvalidate
@private
*/
adapterDidInvalidate: function(errors) {
this.send('becameInvalid', errors);
},
/**
@method adapterDidError
@private
*/
adapterDidError: function() {
this.send('becameError');
set(this, 'isError', true);
},
/**
Override the default event firing from Ember.Evented to
also call methods with the given name.
@method trigger
@private
@param name
*/
trigger: function(name) {
Ember.tryInvoke(this, name, [].slice.call(arguments, 1));
this._super.apply(this, arguments);
},
triggerLater: function() {
this._deferredTriggers.push(arguments);
once(this, '_triggerDeferredTriggers');
},
_triggerDeferredTriggers: function() {
for (var i=0, l=this._deferredTriggers.length; i<l; i++) {
this.trigger.apply(this, this._deferredTriggers[i]);
}
this._deferredTriggers = [];
}
});
DS.Model.reopenClass({
/**
Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model
instances from within the store, but if end users accidentally call `create()`
(instead of `createRecord()`), we can raise an error.
@method _create
@private
@static
*/
_create: DS.Model.create,
/**
Override the class' `create()` method to raise an error. This
prevents end users from inadvertently calling `create()` instead
of `createRecord()`. The store is still able to create instances
by calling the `_create()` method. To create an instance of a
`DS.Model` use [store.createRecord](DS.Store.html#method_createRecord).
@method create
@private
@static
*/
create: function() {
throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.");
}
});
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get;
/**
@class Model
@namespace DS
*/
DS.Model.reopenClass({
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are the meta object for the
property.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
var attributes = Ember.get(App.Person, 'attributes')
attributes.forEach(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@property attributes
@static
@type {Ember.Map}
@readOnly
*/
attributes: Ember.computed(function() {
var map = Ember.Map.create();
this.eachComputedProperty(function(name, meta) {
if (meta.isAttribute) {
Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id');
meta.name = name;
map.set(name, meta);
}
});
return map;
}),
/**
A map whose keys are the attributes of the model (properties
described by DS.attr) and whose values are type of transformation
applied to each attribute. This map does not include any
attributes that do not have an transformation type.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
var transformedAttributes = Ember.get(App.Person, 'transformedAttributes')
transformedAttributes.forEach(function(field, type) {
console.log(field, type);
});
// prints:
// lastName string
// birthday date
```
@property transformedAttributes
@static
@type {Ember.Map}
@readOnly
*/
transformedAttributes: Ember.computed(function() {
var map = Ember.Map.create();
this.eachAttribute(function(key, meta) {
if (meta.type) {
map.set(key, meta.type);
}
});
return map;
}),
/**
Iterates through the attributes of the model, calling the passed function on each
attribute.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, meta);
```
- `name` the name of the current property in the iteration
- `meta` the meta object for the attribute property in the iteration
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
App.Person.eachAttribute(function(name, meta) {
console.log(name, meta);
});
// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}
```
@method eachAttribute
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@static
*/
eachAttribute: function(callback, binding) {
get(this, 'attributes').forEach(function(name, meta) {
callback.call(binding, name, meta);
}, binding);
},
/**
Iterates through the transformedAttributes of the model, calling
the passed function on each attribute. Note the callback will not be
called for any attributes that do not have an transformation type.
The callback method you provide should have the following signature (all
parameters are optional):
```javascript
function(name, type);
```
- `name` the name of the current property in the iteration
- `type` a tring contrining the name of the type of transformed
applied to the attribute
Note that in addition to a callback, you can also pass an optional target
object that will be set as `this` on the context.
Example
```javascript
App.Person = DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
App.Person.eachTransformedAttribute(function(name, type) {
console.log(name, type);
});
// prints:
// lastName string
// birthday date
```
@method eachTransformedAttribute
@param {Function} callback The callback to execute
@param {Object} [target] The target object to use
@static
*/
eachTransformedAttribute: function(callback, binding) {
get(this, 'transformedAttributes').forEach(function(name, type) {
callback.call(binding, name, type);
});
}
});
DS.Model.reopen({
eachAttribute: function(callback, binding) {
this.constructor.eachAttribute(callback, binding);
}
});
function getDefaultValue(record, options, key) {
if (typeof options.defaultValue === "function") {
return options.defaultValue();
} else {
return options.defaultValue;
}
}
function hasValue(record, key) {
return record._attributes.hasOwnProperty(key) ||
record._inFlightAttributes.hasOwnProperty(key) ||
record._data.hasOwnProperty(key);
}
function getValue(record, key) {
if (record._attributes.hasOwnProperty(key)) {
return record._attributes[key];
} else if (record._inFlightAttributes.hasOwnProperty(key)) {
return record._inFlightAttributes[key];
} else {
return record._data[key];
}
}
/**
`DS.attr` defines an attribute on a [DS.Model](DS.Model.html).
By default, attributes are passed through as-is, however you can specify an
optional type to have the value automatically transformed.
Ember Data ships with four basic transform types: `string`, `number`,
`boolean` and `date`. You can define your own transforms by subclassing
[DS.Transform](DS.Transform.html).
`DS.attr` takes an optional hash as a second parameter, currently
supported options are:
- `defaultValue`: Pass a string or a function to be called to set the attribute
to a default value if none is supplied.
Example
```javascript
var attr = DS.attr;
App.User = DS.Model.extend({
username: attr('string'),
email: attr('string'),
verified: attr('boolean', {defaultValue: false})
});
```
@namespace
@method attr
@for DS
@param {String} type the attribute type
@param {Object} options a hash of options
@return {Attribute}
*/
DS.attr = function(type, options) {
options = options || {};
var meta = {
type: type,
isAttribute: true,
options: options
};
return Ember.computed(function(key, value) {
if (arguments.length > 1) {
Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id');
var oldValue = this._attributes[key] || this._inFlightAttributes[key] || this._data[key];
this.send('didSetProperty', {
name: key,
oldValue: oldValue,
originalValue: this._data[key],
value: value
});
this._attributes[key] = value;
return value;
} else if (hasValue(this, key)) {
return getValue(this, key);
} else {
return getDefaultValue(this, options, key);
}
// `data` is never set directly. However, it may be
// invalidated from the state manager's setData
// event.
}).property('data').meta(meta);
};
})();
(function() {
/**
@module ember-data
*/
})();
(function() {
/**
@module ember-data
*/
/**
An AttributeChange object is created whenever a record's
attribute changes value. It is used to track changes to a
record between transaction commits.
@class AttributeChange
@namespace DS
@private
@constructor
*/
var AttributeChange = DS.AttributeChange = function(options) {
this.record = options.record;
this.store = options.store;
this.name = options.name;
this.value = options.value;
this.oldValue = options.oldValue;
};
AttributeChange.createChange = function(options) {
return new AttributeChange(options);
};
AttributeChange.prototype = {
sync: function() {
if (this.value !== this.oldValue) {
this.record.send('becomeDirty');
this.record.updateRecordArraysLater();
}
// TODO: Use this object in the commit process
this.destroy();
},
/**
If the AttributeChange is destroyed (either by being rolled back
or being committed), remove it from the list of pending changes
on the record.
@method destroy
*/
destroy: function() {
delete this.record._changesToSync[this.name];
}
};
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var forEach = Ember.EnumerableUtils.forEach;
/**
@class RelationshipChange
@namespace DS
@private
@construtor
*/
DS.RelationshipChange = function(options) {
this.parentRecord = options.parentRecord;
this.childRecord = options.childRecord;
this.firstRecord = options.firstRecord;
this.firstRecordKind = options.firstRecordKind;
this.firstRecordName = options.firstRecordName;
this.secondRecord = options.secondRecord;
this.secondRecordKind = options.secondRecordKind;
this.secondRecordName = options.secondRecordName;
this.changeType = options.changeType;
this.store = options.store;
this.committed = {};
};
/**
@class RelationshipChangeAdd
@namespace DS
@private
@construtor
*/
DS.RelationshipChangeAdd = function(options){
DS.RelationshipChange.call(this, options);
};
/**
@class RelationshipChangeRemove
@namespace DS
@private
@construtor
*/
DS.RelationshipChangeRemove = function(options){
DS.RelationshipChange.call(this, options);
};
DS.RelationshipChange.create = function(options) {
return new DS.RelationshipChange(options);
};
DS.RelationshipChangeAdd.create = function(options) {
return new DS.RelationshipChangeAdd(options);
};
DS.RelationshipChangeRemove.create = function(options) {
return new DS.RelationshipChangeRemove(options);
};
DS.OneToManyChange = {};
DS.OneToNoneChange = {};
DS.ManyToNoneChange = {};
DS.OneToOneChange = {};
DS.ManyToManyChange = {};
DS.RelationshipChange._createChange = function(options){
if(options.changeType === "add"){
return DS.RelationshipChangeAdd.create(options);
}
if(options.changeType === "remove"){
return DS.RelationshipChangeRemove.create(options);
}
};
DS.RelationshipChange.determineRelationshipType = function(recordType, knownSide){
var knownKey = knownSide.key, key, otherKind;
var knownKind = knownSide.kind;
var inverse = recordType.inverseFor(knownKey);
if (inverse){
key = inverse.name;
otherKind = inverse.kind;
}
if (!inverse){
return knownKind === "belongsTo" ? "oneToNone" : "manyToNone";
}
else{
if(otherKind === "belongsTo"){
return knownKind === "belongsTo" ? "oneToOne" : "manyToOne";
}
else{
return knownKind === "belongsTo" ? "oneToMany" : "manyToMany";
}
}
};
DS.RelationshipChange.createChange = function(firstRecord, secondRecord, store, options){
// Get the type of the child based on the child's client ID
var firstRecordType = firstRecord.constructor, changeType;
changeType = DS.RelationshipChange.determineRelationshipType(firstRecordType, options);
if (changeType === "oneToMany"){
return DS.OneToManyChange.createChange(firstRecord, secondRecord, store, options);
}
else if (changeType === "manyToOne"){
return DS.OneToManyChange.createChange(secondRecord, firstRecord, store, options);
}
else if (changeType === "oneToNone"){
return DS.OneToNoneChange.createChange(firstRecord, secondRecord, store, options);
}
else if (changeType === "manyToNone"){
return DS.ManyToNoneChange.createChange(firstRecord, secondRecord, store, options);
}
else if (changeType === "oneToOne"){
return DS.OneToOneChange.createChange(firstRecord, secondRecord, store, options);
}
else if (changeType === "manyToMany"){
return DS.ManyToManyChange.createChange(firstRecord, secondRecord, store, options);
}
};
DS.OneToNoneChange.createChange = function(childRecord, parentRecord, store, options) {
var key = options.key;
var change = DS.RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
store: store,
changeType: options.changeType,
firstRecordName: key,
firstRecordKind: "belongsTo"
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
DS.ManyToNoneChange.createChange = function(childRecord, parentRecord, store, options) {
var key = options.key;
var change = DS.RelationshipChange._createChange({
parentRecord: childRecord,
childRecord: parentRecord,
secondRecord: childRecord,
store: store,
changeType: options.changeType,
secondRecordName: options.key,
secondRecordKind: "hasMany"
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
DS.ManyToManyChange.createChange = function(childRecord, parentRecord, store, options) {
// If the name of the belongsTo side of the relationship is specified,
// use that
// If the type of the parent is specified, look it up on the child's type
// definition.
var key = options.key;
var change = DS.RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
secondRecord: parentRecord,
firstRecordKind: "hasMany",
secondRecordKind: "hasMany",
store: store,
changeType: options.changeType,
firstRecordName: key
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
DS.OneToOneChange.createChange = function(childRecord, parentRecord, store, options) {
var key;
// If the name of the belongsTo side of the relationship is specified,
// use that
// If the type of the parent is specified, look it up on the child's type
// definition.
if (options.parentType) {
key = options.parentType.inverseFor(options.key).name;
} else if (options.key) {
key = options.key;
} else {
Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false);
}
var change = DS.RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
secondRecord: parentRecord,
firstRecordKind: "belongsTo",
secondRecordKind: "belongsTo",
store: store,
changeType: options.changeType,
firstRecordName: key
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change);
return change;
};
DS.OneToOneChange.maintainInvariant = function(options, store, childRecord, key){
if (options.changeType === "add" && store.recordIsMaterialized(childRecord)) {
var oldParent = get(childRecord, key);
if (oldParent){
var correspondingChange = DS.OneToOneChange.createChange(childRecord, oldParent, store, {
parentType: options.parentType,
hasManyName: options.hasManyName,
changeType: "remove",
key: options.key
});
store.addRelationshipChangeFor(childRecord, key, options.parentRecord , null, correspondingChange);
correspondingChange.sync();
}
}
};
DS.OneToManyChange.createChange = function(childRecord, parentRecord, store, options) {
var key;
// If the name of the belongsTo side of the relationship is specified,
// use that
// If the type of the parent is specified, look it up on the child's type
// definition.
if (options.parentType) {
key = options.parentType.inverseFor(options.key).name;
DS.OneToManyChange.maintainInvariant( options, store, childRecord, key );
} else if (options.key) {
key = options.key;
} else {
Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false);
}
var change = DS.RelationshipChange._createChange({
parentRecord: parentRecord,
childRecord: childRecord,
firstRecord: childRecord,
secondRecord: parentRecord,
firstRecordKind: "belongsTo",
secondRecordKind: "hasMany",
store: store,
changeType: options.changeType,
firstRecordName: key
});
store.addRelationshipChangeFor(childRecord, key, parentRecord, change.getSecondRecordName(), change);
return change;
};
DS.OneToManyChange.maintainInvariant = function(options, store, childRecord, key){
if (options.changeType === "add" && childRecord) {
var oldParent = get(childRecord, key);
if (oldParent){
var correspondingChange = DS.OneToManyChange.createChange(childRecord, oldParent, store, {
parentType: options.parentType,
hasManyName: options.hasManyName,
changeType: "remove",
key: options.key
});
store.addRelationshipChangeFor(childRecord, key, options.parentRecord, correspondingChange.getSecondRecordName(), correspondingChange);
correspondingChange.sync();
}
}
};
/**
@class RelationshipChange
@namespace DS
*/
DS.RelationshipChange.prototype = {
getSecondRecordName: function() {
var name = this.secondRecordName, parent;
if (!name) {
parent = this.secondRecord;
if (!parent) { return; }
var childType = this.firstRecord.constructor;
var inverse = childType.inverseFor(this.firstRecordName);
this.secondRecordName = inverse.name;
}
return this.secondRecordName;
},
/**
Get the name of the relationship on the belongsTo side.
@method getFirstRecordName
@return {String}
*/
getFirstRecordName: function() {
var name = this.firstRecordName;
return name;
},
/**
@method destroy
@private
*/
destroy: function() {
var childRecord = this.childRecord,
belongsToName = this.getFirstRecordName(),
hasManyName = this.getSecondRecordName(),
store = this.store;
store.removeRelationshipChangeFor(childRecord, belongsToName, this.parentRecord, hasManyName, this.changeType);
},
getSecondRecord: function(){
return this.secondRecord;
},
/**
@method getFirstRecord
@private
*/
getFirstRecord: function() {
return this.firstRecord;
},
coalesce: function(){
var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecord);
forEach(relationshipPairs, function(pair){
var addedChange = pair["add"];
var removedChange = pair["remove"];
if(addedChange && removedChange) {
addedChange.destroy();
removedChange.destroy();
}
});
}
};
DS.RelationshipChangeAdd.prototype = Ember.create(DS.RelationshipChange.create({}));
DS.RelationshipChangeRemove.prototype = Ember.create(DS.RelationshipChange.create({}));
// the object is a value, and not a promise
function isValue(object) {
return typeof object === 'object' && (!object.then || typeof object.then !== 'function');
}
DS.RelationshipChangeAdd.prototype.changeType = "add";
DS.RelationshipChangeAdd.prototype.sync = function() {
var secondRecordName = this.getSecondRecordName(),
firstRecordName = this.getFirstRecordName(),
firstRecord = this.getFirstRecord(),
secondRecord = this.getSecondRecord();
//Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName);
//Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName);
if (secondRecord instanceof DS.Model && firstRecord instanceof DS.Model) {
if(this.secondRecordKind === "belongsTo"){
secondRecord.suspendRelationshipObservers(function(){
set(secondRecord, secondRecordName, firstRecord);
});
}
else if(this.secondRecordKind === "hasMany"){
secondRecord.suspendRelationshipObservers(function(){
var relationship = get(secondRecord, secondRecordName);
if (isValue(relationship)) { relationship.addObject(firstRecord); }
});
}
}
if (firstRecord instanceof DS.Model && secondRecord instanceof DS.Model && get(firstRecord, firstRecordName) !== secondRecord) {
if(this.firstRecordKind === "belongsTo"){
firstRecord.suspendRelationshipObservers(function(){
set(firstRecord, firstRecordName, secondRecord);
});
}
else if(this.firstRecordKind === "hasMany"){
firstRecord.suspendRelationshipObservers(function(){
var relationship = get(firstRecord, firstRecordName);
if (isValue(relationship)) { relationship.addObject(secondRecord); }
});
}
}
this.coalesce();
};
DS.RelationshipChangeRemove.prototype.changeType = "remove";
DS.RelationshipChangeRemove.prototype.sync = function() {
var secondRecordName = this.getSecondRecordName(),
firstRecordName = this.getFirstRecordName(),
firstRecord = this.getFirstRecord(),
secondRecord = this.getSecondRecord();
//Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName);
//Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName);
if (secondRecord instanceof DS.Model && firstRecord instanceof DS.Model) {
if(this.secondRecordKind === "belongsTo"){
secondRecord.suspendRelationshipObservers(function(){
set(secondRecord, secondRecordName, null);
});
}
else if(this.secondRecordKind === "hasMany"){
secondRecord.suspendRelationshipObservers(function(){
var relationship = get(secondRecord, secondRecordName);
if (isValue(relationship)) { relationship.removeObject(firstRecord); }
});
}
}
if (firstRecord instanceof DS.Model && get(firstRecord, firstRecordName)) {
if(this.firstRecordKind === "belongsTo"){
firstRecord.suspendRelationshipObservers(function(){
set(firstRecord, firstRecordName, null);
});
}
else if(this.firstRecordKind === "hasMany"){
firstRecord.suspendRelationshipObservers(function(){
var relationship = get(firstRecord, firstRecordName);
if (isValue(relationship)) { relationship.removeObject(secondRecord); }
});
}
}
this.coalesce();
};
})();
(function() {
/**
@module ember-data
*/
})();
(function() {
var get = Ember.get, set = Ember.set,
isNone = Ember.isNone;
/**
@module ember-data
*/
function asyncBelongsTo(type, options, meta) {
return Ember.computed(function(key, value) {
var data = get(this, 'data'),
store = get(this, 'store'),
promiseLabel = "DS: Async belongsTo " + this + " : " + key;
if (arguments.length === 2) {
Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof store.modelFor(type));
return value === undefined ? null : DS.PromiseObject.create({ promise: Ember.RSVP.resolve(value, promiseLabel) });
}
var link = data.links && data.links[key],
belongsTo = data[key];
if(!isNone(belongsTo)) {
var promise = store.fetchRecord(belongsTo) || Ember.RSVP.resolve(belongsTo, promiseLabel);
return DS.PromiseObject.create({ promise: promise});
} else if (link) {
var resolver = Ember.RSVP.defer("DS: Async belongsTo (link) " + this + " : " + key);
store.findBelongsTo(this, link, meta, resolver);
return DS.PromiseObject.create({ promise: resolver.promise });
} else {
return null;
}
}).property('data').meta(meta);
}
/**
`DS.belongsTo` is used to define One-To-One and One-To-Many
relationships on a [DS.Model](DS.Model.html).
`DS.belongsTo` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a
related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses)
#### One-To-One
To declare a one-to-one relationship between two models, use
`DS.belongsTo`:
```javascript
App.User = DS.Model.extend({
profile: DS.belongsTo('profile')
});
App.Profile = DS.Model.extend({
user: DS.belongsTo('user')
});
```
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
```
@namespace
@method belongsTo
@for DS
@param {String or DS.Model} type the model type of the relationship
@param {Object} options a hash of options
@return {Ember.computed} relationship
*/
DS.belongsTo = function(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
} else {
Ember.assert("The first argument DS.belongsTo must be a model type or string, like DS.belongsTo(App.Person)", !!type && (typeof type === 'string' || DS.Model.detect(type)));
}
options = options || {};
var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo' };
if (options.async) {
return asyncBelongsTo(type, options, meta);
}
return Ember.computed(function(key, value) {
var data = get(this, 'data'),
store = get(this, 'store'), belongsTo, typeClass;
if (typeof type === 'string') {
typeClass = store.modelFor(type);
} else {
typeClass = type;
}
if (arguments.length === 2) {
Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof typeClass);
return value === undefined ? null : value;
}
belongsTo = data[key];
if (isNone(belongsTo)) { return null; }
store.fetchRecord(belongsTo);
return belongsTo;
}).property('data').meta(meta);
};
/**
These observers observe all `belongsTo` relationships on the record. See
`relationships/ext` to see how these observers get their dependencies.
@class Model
@namespace DS
*/
DS.Model.reopen({
/**
@method belongsToWillChange
@private
@static
@param record
@param key
*/
belongsToWillChange: Ember.beforeObserver(function(record, key) {
if (get(record, 'isLoaded')) {
var oldParent = get(record, key);
if (oldParent) {
var store = get(record, 'store'),
change = DS.RelationshipChange.createChange(record, oldParent, store, { key: key, kind: "belongsTo", changeType: "remove" });
change.sync();
this._changesToSync[key] = change;
}
}
}),
/**
@method belongsToDidChange
@private
@static
@param record
@param key
*/
belongsToDidChange: Ember.immediateObserver(function(record, key) {
if (get(record, 'isLoaded')) {
var newParent = get(record, key);
if (newParent) {
var store = get(record, 'store'),
change = DS.RelationshipChange.createChange(record, newParent, store, { key: key, kind: "belongsTo", changeType: "add" });
change.sync();
}
}
delete this._changesToSync[key];
})
});
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set, setProperties = Ember.setProperties;
function asyncHasMany(type, options, meta) {
return Ember.computed(function(key, value) {
var relationship = this._relationships[key],
promiseLabel = "DS: Async hasMany " + this + " : " + key;
if (!relationship) {
var resolver = Ember.RSVP.defer(promiseLabel);
relationship = buildRelationship(this, key, options, function(store, data) {
var link = data.links && data.links[key];
var rel;
if (link) {
rel = store.findHasMany(this, link, meta, resolver);
} else {
rel = store.findMany(this, data[key], meta.type, resolver);
}
// cache the promise so we can use it
// when we come back and don't need to rebuild
// the relationship.
set(rel, 'promise', resolver.promise);
return rel;
});
}
var promise = relationship.get('promise').then(function() {
return relationship;
}, null, "DS: Async hasMany records received");
return DS.PromiseArray.create({ promise: promise });
}).property('data').meta(meta);
}
function buildRelationship(record, key, options, callback) {
var rels = record._relationships;
if (rels[key]) { return rels[key]; }
var data = get(record, 'data'),
store = get(record, 'store');
var relationship = rels[key] = callback.call(record, store, data);
return setProperties(relationship, {
owner: record, name: key, isPolymorphic: options.polymorphic
});
}
function hasRelationship(type, options) {
options = options || {};
var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany' };
if (options.async) {
return asyncHasMany(type, options, meta);
}
return Ember.computed(function(key, value) {
return buildRelationship(this, key, options, function(store, data) {
var records = data[key];
Ember.assert("You looked up the '" + key + "' relationship on '" + this + "' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", Ember.A(records).everyProperty('isEmpty', false));
return store.findMany(this, data[key], meta.type);
});
}).property('data').meta(meta);
}
/**
`DS.hasMany` is used to define One-To-Many and Many-To-Many
relationships on a [DS.Model](DS.Model.html).
`DS.hasMany` takes an optional hash as a second parameter, currently
supported options are:
- `async`: A boolean value used to explicitly declare this to be an async relationship.
- `inverse`: A string used to identify the inverse property on a related model.
#### One-To-Many
To declare a one-to-many relationship between two models, use
`DS.belongsTo` in combination with `DS.hasMany`, like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
App.Comment = DS.Model.extend({
post: DS.belongsTo('post')
});
```
#### Many-To-Many
To declare a many-to-many relationship between two models, use
`DS.hasMany`:
```javascript
App.Post = DS.Model.extend({
tags: DS.hasMany('tag')
});
App.Tag = DS.Model.extend({
posts: DS.hasMany('post')
});
```
#### Explicit Inverses
Ember Data will do its best to discover which relationships map to
one another. In the one-to-many code above, for example, Ember Data
can figure out that changing the `comments` relationship should update
the `post` relationship on the inverse because post is the only
relationship to that model.
However, sometimes you may have multiple `belongsTo`/`hasManys` for the
same type. You can specify which property on the related model is
the inverse using `DS.hasMany`'s `inverse` option:
```javascript
var belongsTo = DS.belongsTo,
hasMany = DS.hasMany;
App.Comment = DS.Model.extend({
onePost: belongsTo('post'),
twoPost: belongsTo('post'),
redPost: belongsTo('post'),
bluePost: belongsTo('post')
});
App.Post = DS.Model.extend({
comments: hasMany('comment', {
inverse: 'redPost'
})
});
```
You can also specify an inverse on a `belongsTo`, which works how
you'd expect.
@namespace
@method hasMany
@for DS
@param {String or DS.Model} type the model type of the relationship
@param {Object} options a hash of options
@return {Ember.computed} relationship
*/
DS.hasMany = function(type, options) {
if (typeof type === 'object') {
options = type;
type = undefined;
}
return hasRelationship(type, options);
};
})();
(function() {
var get = Ember.get, set = Ember.set;
/**
@module ember-data
*/
/*
This file defines several extensions to the base `DS.Model` class that
add support for one-to-many relationships.
*/
/**
@class Model
@namespace DS
*/
DS.Model.reopen({
/**
This Ember.js hook allows an object to be notified when a property
is defined.
In this case, we use it to be notified when an Ember Data user defines a
belongs-to relationship. In that case, we need to set up observers for
each one, allowing us to track relationship changes and automatically
reflect changes in the inverse has-many array.
This hook passes the class being set up, as well as the key and value
being defined. So, for example, when the user does this:
```javascript
DS.Model.extend({
parent: DS.belongsTo('user')
});
```
This hook would be called with "parent" as the key and the computed
property returned by `DS.belongsTo` as the value.
@method didDefineProperty
@param proto
@param key
@param value
*/
didDefineProperty: function(proto, key, value) {
// Check if the value being set is a computed property.
if (value instanceof Ember.Descriptor) {
// If it is, get the metadata for the relationship. This is
// populated by the `DS.belongsTo` helper when it is creating
// the computed property.
var meta = value.meta();
if (meta.isRelationship && meta.kind === 'belongsTo') {
Ember.addObserver(proto, key, null, 'belongsToDidChange');
Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange');
}
meta.parentType = proto.constructor;
}
}
});
/*
These DS.Model extensions add class methods that provide relationship
introspection abilities about relationships.
A note about the computed properties contained here:
**These properties are effectively sealed once called for the first time.**
To avoid repeatedly doing expensive iteration over a model's fields, these
values are computed once and then cached for the remainder of the runtime of
your application.
If your application needs to modify a class after its initial definition
(for example, using `reopen()` to add additional attributes), make sure you
do it before using your model with the store, which uses these properties
extensively.
*/
DS.Model.reopenClass({
/**
For a given relationship name, returns the model type of the relationship.
For example, if you define a model like this:
```javascript
App.Post = DS.Model.extend({
comments: DS.hasMany('comment')
});
```
Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`.
@method typeForRelationship
@static
@param {String} name the name of the relationship
@return {subclass of DS.Model} the type of the relationship, or undefined
*/
typeForRelationship: function(name) {
var relationship = get(this, 'relationshipsByName').get(name);
return relationship && relationship.type;
},
inverseFor: function(name) {
var inverseType = this.typeForRelationship(name);
if (!inverseType) { return null; }
var options = this.metaForProperty(name).options;
if (options.inverse === null) { return null; }
var inverseName, inverseKind;
if (options.inverse) {
inverseName = options.inverse;
inverseKind = Ember.get(inverseType, 'relationshipsByName').get(inverseName).kind;
} else {
var possibleRelationships = findPossibleInverses(this, inverseType);
if (possibleRelationships.length === 0) { return null; }
Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ".", possibleRelationships.length === 1);
inverseName = possibleRelationships[0].name;
inverseKind = possibleRelationships[0].kind;
}
function findPossibleInverses(type, inverseType, possibleRelationships) {
possibleRelationships = possibleRelationships || [];
var relationshipMap = get(inverseType, 'relationships');
if (!relationshipMap) { return; }
var relationships = relationshipMap.get(type);
if (relationships) {
possibleRelationships.push.apply(possibleRelationships, relationshipMap.get(type));
}
if (type.superclass) {
findPossibleInverses(type.superclass, inverseType, possibleRelationships);
}
return possibleRelationships;
}
return {
type: inverseType,
name: inverseName,
kind: inverseKind
};
},
/**
The model's relationships as a map, keyed on the type of the
relationship. The value of each entry is an array containing a descriptor
for each relationship with that type, describing the name of the relationship
as well as the type.
For example, given the following model definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This computed property would return a map describing these
relationships, like this:
```javascript
var relationships = Ember.get(App.Blog, 'relationships');
relationships.get(App.User);
//=> [ { name: 'users', kind: 'hasMany' },
// { name: 'owner', kind: 'belongsTo' } ]
relationships.get(App.Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]
```
@property relationships
@static
@type Ember.Map
@readOnly
*/
relationships: Ember.computed(function() {
var map = new Ember.MapWithDefault({
defaultValue: function() { return []; }
});
// Loop through each computed property on the class
this.eachComputedProperty(function(name, meta) {
// If the computed property is a relationship, add
// it to the map.
if (meta.isRelationship) {
if (typeof meta.type === 'string') {
meta.type = this.store.modelFor(meta.type);
}
var relationshipsForType = map.get(meta.type);
relationshipsForType.push({ name: name, kind: meta.kind });
}
});
return map;
}),
/**
A hash containing lists of the model's relationships, grouped
by the relationship kind. For example, given a model with this
definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relationshipNames = Ember.get(App.Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']
```
@property relationshipNames
@static
@type Object
@readOnly
*/
relationshipNames: Ember.computed(function() {
var names = { hasMany: [], belongsTo: [] };
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
names[meta.kind].push(name);
}
});
return names;
}),
/**
An array of types directly related to a model. Each type will be
included once, regardless of the number of relationships it has with
the model.
For example, given a model with this definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relatedTypes = Ember.get(App.Blog, 'relatedTypes');
//=> [ App.User, App.Post ]
```
@property relatedTypes
@static
@type Ember.Array
@readOnly
*/
relatedTypes: Ember.computed(function() {
var type,
types = Ember.A();
// Loop through each computed property on the class,
// and create an array of the unique types involved
// in relationships
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
type = meta.type;
if (typeof type === 'string') {
type = get(this, type, false) || this.store.modelFor(type);
}
Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", type);
if (!types.contains(type)) {
Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!type);
types.push(type);
}
}
});
return types;
}),
/**
A map whose keys are the relationships of a model and whose values are
relationship descriptors.
For example, given a model with this
definition:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post')
});
```
This property would contain the following:
```javascript
var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: App.User }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: App.User }
```
@property relationshipsByName
@static
@type Ember.Map
@readOnly
*/
relationshipsByName: Ember.computed(function() {
var map = Ember.Map.create(), type;
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
meta.key = name;
type = meta.type;
if (!type && meta.kind === 'hasMany') {
type = Ember.String.singularize(name);
} else if (!type) {
type = name;
}
if (typeof type === 'string') {
meta.type = this.store.modelFor(type);
}
map.set(name, meta);
}
});
return map;
}),
/**
A map whose keys are the fields of the model and whose values are strings
describing the kind of the field. A model's fields are the union of all of its
attributes and relationships.
For example:
```javascript
App.Blog = DS.Model.extend({
users: DS.hasMany('user'),
owner: DS.belongsTo('user'),
posts: DS.hasMany('post'),
title: DS.attr('string')
});
var fields = Ember.get(App.Blog, 'fields');
fields.forEach(function(field, kind) {
console.log(field, kind);
});
// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute
```
@property fields
@static
@type Ember.Map
@readOnly
*/
fields: Ember.computed(function() {
var map = Ember.Map.create();
this.eachComputedProperty(function(name, meta) {
if (meta.isRelationship) {
map.set(name, meta.kind);
} else if (meta.isAttribute) {
map.set(name, 'attribute');
}
});
return map;
}),
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function(callback, binding) {
get(this, 'relationshipsByName').forEach(function(name, relationship) {
callback.call(binding, name, relationship);
});
},
/**
Given a callback, iterates over each of the types related to a model,
invoking the callback with the related type's class. Each type will be
returned just once, regardless of how many different relationships it has
with a model.
@method eachRelatedType
@static
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelatedType: function(callback, binding) {
get(this, 'relatedTypes').forEach(function(type) {
callback.call(binding, type);
});
}
});
DS.Model.reopen({
/**
Given a callback, iterates over each of the relationships in the model,
invoking the callback with the name of each relationship and its relationship
descriptor.
@method eachRelationship
@param {Function} callback the callback to invoke
@param {any} binding the value to which the callback's `this` should be bound
*/
eachRelationship: function(callback, binding) {
this.constructor.eachRelationship(callback, binding);
}
});
})();
(function() {
/**
@module ember-data
*/
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var once = Ember.run.once;
var forEach = Ember.EnumerableUtils.forEach;
/**
@class RecordArrayManager
@namespace DS
@private
@extends Ember.Object
*/
DS.RecordArrayManager = Ember.Object.extend({
init: function() {
this.filteredRecordArrays = Ember.MapWithDefault.create({
defaultValue: function() { return []; }
});
this.changedRecords = [];
},
recordDidChange: function(record) {
this.changedRecords.push(record);
once(this, this.updateRecordArrays);
},
recordArraysForRecord: function(record) {
record._recordArrays = record._recordArrays || Ember.OrderedSet.create();
return record._recordArrays;
},
/**
This method is invoked whenever data is loaded into the store by the
adapter or updated by the adapter, or when a record has changed.
It updates all record arrays that a record belongs to.
To avoid thrashing, it only runs at most once per run loop.
@method updateRecordArrays
@param {Class} type
@param {Number|String} clientId
*/
updateRecordArrays: function() {
forEach(this.changedRecords, function(record) {
if (get(record, 'isDeleted')) {
this._recordWasDeleted(record);
} else {
this._recordWasChanged(record);
}
}, this);
this.changedRecords = [];
},
_recordWasDeleted: function (record) {
var recordArrays = record._recordArrays;
if (!recordArrays) { return; }
forEach(recordArrays, function(array) {
array.removeRecord(record);
});
},
_recordWasChanged: function (record) {
var type = record.constructor,
recordArrays = this.filteredRecordArrays.get(type),
filter;
forEach(recordArrays, function(array) {
filter = get(array, 'filterFunction');
this.updateRecordArray(array, filter, type, record);
}, this);
// loop through all manyArrays containing an unloaded copy of this
// clientId and notify them that the record was loaded.
var manyArrays = record._loadingRecordArrays;
if (manyArrays) {
for (var i=0, l=manyArrays.length; i<l; i++) {
manyArrays[i].loadedRecord();
}
record._loadingRecordArrays = [];
}
},
/**
Update an individual filter.
@method updateRecordArray
@param {DS.FilteredRecordArray} array
@param {Function} filter
@param {Class} type
@param {Number|String} clientId
*/
updateRecordArray: function(array, filter, type, record) {
var shouldBeInArray;
if (!filter) {
shouldBeInArray = true;
} else {
shouldBeInArray = filter(record);
}
var recordArrays = this.recordArraysForRecord(record);
if (shouldBeInArray) {
recordArrays.add(array);
array.addRecord(record);
} else if (!shouldBeInArray) {
recordArrays.remove(array);
array.removeRecord(record);
}
},
/**
This method is invoked if the `filterFunction` property is
changed on a `DS.FilteredRecordArray`.
It essentially re-runs the filter from scratch. This same
method is invoked when the filter is created in th first place.
@method updateFilter
@param array
@param type
@param filter
*/
updateFilter: function(array, type, filter) {
var typeMap = this.store.typeMapFor(type),
records = typeMap.records, record;
for (var i=0, l=records.length; i<l; i++) {
record = records[i];
if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) {
this.updateRecordArray(array, filter, type, record);
}
}
},
/**
Create a `DS.ManyArray` for a type and list of record references, and index
the `ManyArray` under each reference. This allows us to efficiently remove
records from `ManyArray`s when they are deleted.
@method createManyArray
@param {Class} type
@param {Array} references
@return {DS.ManyArray}
*/
createManyArray: function(type, records) {
var manyArray = DS.ManyArray.create({
type: type,
content: records,
store: this.store
});
forEach(records, function(record) {
var arrays = this.recordArraysForRecord(record);
arrays.add(manyArray);
}, this);
return manyArray;
},
/**
Register a RecordArray for a given type to be backed by
a filter function. This will cause the array to update
automatically when records of that type change attribute
values or states.
@method registerFilteredRecordArray
@param {DS.RecordArray} array
@param {Class} type
@param {Function} filter
*/
registerFilteredRecordArray: function(array, type, filter) {
var recordArrays = this.filteredRecordArrays.get(type);
recordArrays.push(array);
this.updateFilter(array, type, filter);
},
// Internally, we maintain a map of all unloaded IDs requested by
// a ManyArray. As the adapter loads data into the store, the
// store notifies any interested ManyArrays. When the ManyArray's
// total number of loading records drops to zero, it becomes
// `isLoaded` and fires a `didLoad` event.
registerWaitingRecordArray: function(record, array) {
var loadingRecordArrays = record._loadingRecordArrays || [];
loadingRecordArrays.push(array);
record._loadingRecordArrays = loadingRecordArrays;
}
});
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var map = Ember.ArrayPolyfills.map;
var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
DS.InvalidError = function(errors) {
var tmp = Error.prototype.constructor.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors));
this.errors = errors;
for (var i=0, l=errorProps.length; i<l; i++) {
this[errorProps[i]] = tmp[errorProps[i]];
}
};
DS.InvalidError.prototype = Ember.create(Error.prototype);
/**
An adapter is an object that receives requests from a store and
translates them into the appropriate action to take against your
persistence layer. The persistence layer is usually an HTTP API, but may
be anything, such as the browser's local storage.
### Creating an Adapter
First, create a new subclass of `DS.Adapter`:
```javascript
App.MyAdapter = DS.Adapter.extend({
// ...your code here
});
```
To tell your store which adapter to use, set its `adapter` property:
```javascript
App.store = DS.Store.create({
adapter: App.MyAdapter.create()
});
```
`DS.Adapter` is an abstract base class that you should override in your
application to customize it for your backend. The minimum set of methods
that you should implement is:
* `find()`
* `createRecord()`
* `updateRecord()`
* `deleteRecord()`
To improve the network performance of your application, you can optimize
your adapter by overriding these lower-level methods:
* `findMany()`
* `createRecords()`
* `updateRecords()`
* `deleteRecords()`
* `commit()`
For an example implementation, see `DS.RESTAdapter`, the
included REST adapter.
@class Adapter
@namespace DS
@extends Ember.Object
*/
DS.Adapter = Ember.Object.extend({
/**
The `find()` method is invoked when the store is asked for a record that
has not previously been loaded. In response to `find()` being called, you
should query your persistence layer for a record with the given ID. Once
found, you can asynchronously call the store's `push()` method to push
the record into the store.
Here is an example `find` implementation:
```javascript
find: function(store, type, id) {
var url = type.url;
url = url.fmt(id);
jQuery.getJSON(url, function(data) {
// data is a hash of key/value pairs. If your server returns a
// root, simply do something like:
// store.push(type, id, data.person)
store.push(type, id, data);
});
}
```
@method find
*/
find: Ember.required(Function),
/**
@private
@method findAll
@param store
@param type
@param since
*/
findAll: null,
/**
@private
@method findQuery
@param store
@param type
@param query
@param recordArray
*/
findQuery: null,
/**
If the globally unique IDs for your records should be generated on the client,
implement the `generateIdForRecord()` method. This method will be invoked
each time you create a new record, and the value returned from it will be
assigned to the record's `primaryKey`.
Most traditional REST-like HTTP APIs will not use this method. Instead, the ID
of the record will be set by the server, and your adapter will update the store
with the new ID when it calls `didCreateRecord()`. Only implement this method if
you intend to generate record IDs on the client-side.
The `generateIdForRecord()` method will be invoked with the requesting store as
the first parameter and the newly created record as the second parameter:
```javascript
generateIdForRecord: function(store, record) {
var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision();
return uuid;
}
```
@method generateIdForRecord
@param {DS.Store} store
@param {DS.Model} record
*/
generateIdForRecord: null,
/**
Proxies to the serializer's `serialize` method.
@method serialize
@param {DS.Model} record
@param {Object} options
*/
serialize: function(record, options) {
return get(record, 'store').serializerFor(record.constructor.typeKey).serialize(record, options);
},
/**
Implement this method in a subclass to handle the creation of
new records.
Serializes the record and send it to the server.
This implementation should call the adapter's `didCreateRecord`
method on success or `didError` method on failure.
@method createRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
*/
createRecord: Ember.required(Function),
/**
Implement this method in a subclass to handle the updating of
a record.
Serializes the record update and send it to the server.
@method updateRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
*/
updateRecord: Ember.required(Function),
/**
Implement this method in a subclass to handle the deletion of
a record.
Sends a delete request for the record to the server.
@method deleteRecord
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the record
@param {DS.Model} record
*/
deleteRecord: Ember.required(Function),
/**
Find multiple records at once.
By default, it loops over the provided ids and calls `find` on each.
May be overwritten to improve performance and reduce the number of
server requests.
@method findMany
@param {DS.Store} store
@param {subclass of DS.Model} type the DS.Model class of the records
@param {Array} ids
*/
findMany: function(store, type, ids) {
var promises = map.call(ids, function(id) {
return this.find(store, type, id);
}, this);
return Ember.RSVP.all(promises);
}
});
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get, fmt = Ember.String.fmt,
indexOf = Ember.EnumerableUtils.indexOf;
var counter = 0;
/**
`DS.FixtureAdapter` is an adapter that loads records from memory.
Its primarily used for development and testing. You can also use
`DS.FixtureAdapter` while working on the API but are not ready to
integrate yet. It is a fully functioning adapter. All CRUD methods
are implemented. You can also implement query logic that a remote
system would do. Its possible to do develop your entire application
with `DS.FixtureAdapter`.
@class FixtureAdapter
@namespace DS
@extends DS.Adapter
*/
DS.FixtureAdapter = DS.Adapter.extend({
// by default, fixtures are already in normalized form
serializer: null,
simulateRemoteResponse: true,
latency: 50,
/**
Implement this method in order to provide data associated with a type
@method fixturesForType
@param type
*/
fixturesForType: function(type) {
if (type.FIXTURES) {
var fixtures = Ember.A(type.FIXTURES);
return fixtures.map(function(fixture){
var fixtureIdType = typeof fixture.id;
if(fixtureIdType !== "number" && fixtureIdType !== "string"){
throw new Error(fmt('the id property must be defined as a number or string for fixture %@', [fixture]));
}
fixture.id = fixture.id + '';
return fixture;
});
}
return null;
},
/**
Implement this method in order to query fixtures data
@method queryFixtures
@param fixture
@param query
@param type
*/
queryFixtures: function(fixtures, query, type) {
Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.');
},
/**
@method updateFixtures
@param type
@param fixture
*/
updateFixtures: function(type, fixture) {
if(!type.FIXTURES) {
type.FIXTURES = [];
}
var fixtures = type.FIXTURES;
this.deleteLoadedFixture(type, fixture);
fixtures.push(fixture);
},
/**
Implement this method in order to provide json for CRUD methods
@method mockJSON
@param type
@param record
*/
mockJSON: function(store, type, record) {
return store.serializerFor(type).serialize(record, { includeId: true });
},
/**
@method generateIdForRecord
@param store
@param record
*/
generateIdForRecord: function(store) {
return "fixture-" + counter++;
},
/**
@method find
@param store
@param type
@param id
*/
find: function(store, type, id) {
var fixtures = this.fixturesForType(type),
fixture;
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
if (fixtures) {
fixture = Ember.A(fixtures).findProperty('id', id);
}
if (fixture) {
return this.simulateRemoteCall(function() {
return fixture;
}, this);
}
},
/**
@method findMany
@param store
@param type
@param ids
*/
findMany: function(store, type, ids) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
if (fixtures) {
fixtures = fixtures.filter(function(item) {
return indexOf(ids, item.id) !== -1;
});
}
if (fixtures) {
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
}
},
/**
@private
@method findAll
@param store
@param type
*/
findAll: function(store, type) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
},
/**
@private
@method findQuery
@param store
@param type
@param query
@param array
*/
findQuery: function(store, type, query, array) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures);
fixtures = this.queryFixtures(fixtures, query, type);
if (fixtures) {
return this.simulateRemoteCall(function() {
return fixtures;
}, this);
}
},
/**
@method createRecord
@param store
@param type
@param record
*/
createRecord: function(store, type, record) {
var fixture = this.mockJSON(store, type, record);
this.updateFixtures(type, fixture);
return this.simulateRemoteCall(function() {
return fixture;
}, this);
},
/**
@method updateRecord
@param store
@param type
@param record
*/
updateRecord: function(store, type, record) {
var fixture = this.mockJSON(store, type, record);
this.updateFixtures(type, fixture);
return this.simulateRemoteCall(function() {
return fixture;
}, this);
},
/**
@method deleteRecord
@param store
@param type
@param record
*/
deleteRecord: function(store, type, record) {
var fixture = this.mockJSON(store, type, record);
this.deleteLoadedFixture(type, fixture);
return this.simulateRemoteCall(function() {
// no payload in a deletion
return null;
});
},
/*
@method deleteLoadedFixture
@private
@param type
@param record
*/
deleteLoadedFixture: function(type, record) {
var existingFixture = this.findExistingFixture(type, record);
if(existingFixture) {
var index = indexOf(type.FIXTURES, existingFixture);
type.FIXTURES.splice(index, 1);
return true;
}
},
/*
@method findExistingFixture
@private
@param type
@param record
*/
findExistingFixture: function(type, record) {
var fixtures = this.fixturesForType(type);
var id = get(record, 'id');
return this.findFixtureById(fixtures, id);
},
/*
@method findFixtureById
@private
@param type
@param record
*/
findFixtureById: function(fixtures, id) {
return Ember.A(fixtures).find(function(r) {
if(''+get(r, 'id') === ''+id) {
return true;
} else {
return false;
}
});
},
/*
@method simulateRemoteCall
@private
@param callback
@param context
*/
simulateRemoteCall: function(callback, context) {
var adapter = this;
return new Ember.RSVP.Promise(function(resolve) {
if (get(adapter, 'simulateRemoteResponse')) {
// Schedule with setTimeout
Ember.run.later(function() {
resolve(callback.call(context));
}, get(adapter, 'latency'));
} else {
// Asynchronous, but at the of the runloop with zero latency
Ember.run.schedule('actions', null, function() {
resolve(callback.call(context));
});
}
}, "DS: FixtureAdapter#simulateRemoteCall");
}
});
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var forEach = Ember.ArrayPolyfills.forEach;
var map = Ember.ArrayPolyfills.map;
function coerceId(id) {
return id == null ? null : id+'';
}
/**
Normally, applications will use the `RESTSerializer` by implementing
the `normalize` method and individual normalizations under
`normalizeHash`.
This allows you to do whatever kind of munging you need, and is
especially useful if your server is inconsistent and you need to
do munging differently for many different kinds of responses.
See the `normalize` documentation for more information.
## Across the Board Normalization
There are also a number of hooks that you might find useful to defined
across-the-board rules for your payload. These rules will be useful
if your server is consistent, or if you're building an adapter for
an infrastructure service, like Parse, and want to encode service
conventions.
For example, if all of your keys are underscored and all-caps, but
otherwise consistent with the names you use in your models, you
can implement across-the-board rules for how to convert an attribute
name in your model to a key in your JSON.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
keyForAttribute: function(attr) {
return Ember.String.underscore(attr).toUpperCase();
}
});
```
You can also implement `keyForRelationship`, which takes the name
of the relationship as the first parameter, and the kind of
relationship (`hasMany` or `belongsTo`) as the second parameter.
@class RESTSerializer
@namespace DS
@extends DS.JSONSerializer
*/
DS.RESTSerializer = DS.JSONSerializer.extend({
/**
Normalizes a part of the JSON payload returned by
the server. You should override this method, munge the hash
and call super if you have generic normalization to do.
It takes the type of the record that is being normalized
(as a DS.Model class), the property where the hash was
originally found, and the hash to normalize.
For example, if you have a payload that looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2 ]
},
"comments": [{
"id": 1,
"body": "FIRST"
}, {
"id": 2,
"body": "Rails is unagi"
}]
}
```
The `normalize` method will be called three times:
* With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }`
* With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }`
* With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }`
You can use this method, for example, to normalize underscored keys to camelized
or other general-purpose normalizations.
If you want to do normalizations specific to some part of the payload, you
can specify those under `normalizeHash`.
For example, if the `IDs` under `"comments"` are provided as `_id` instead of
`id`, you can specify how to normalize just the comments:
```js
App.PostSerializer = DS.RESTSerializer.extend({
normalizeHash: {
comments: function(hash) {
hash.id = hash._id;
delete hash._id;
return hash;
}
}
});
```
The key under `normalizeHash` is just the original key that was in the original
payload.
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@param {String} prop
@returns {Object}
*/
normalize: function(type, hash, prop) {
this.normalizeId(hash);
this.normalizeUsingDeclaredMapping(type, hash);
this.normalizeAttributes(type, hash);
this.normalizeRelationships(type, hash);
if (this.normalizeHash && this.normalizeHash[prop]) {
this.normalizeHash[prop](hash);
}
return this._super(type, hash, prop);
},
/**
You can use this method to normalize all payloads, regardless of whether they
represent single records or an array.
For example, you might want to remove some extraneous data from the payload:
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
normalizePayload: function(type, payload) {
delete payload.version;
delete payload.status;
return payload;
}
});
```
@method normalizePayload
@param {subclass of DS.Model} type
@param {Object} hash
@returns {Object} the normalized payload
*/
normalizePayload: function(type, payload) {
return payload;
},
/**
@method normalizeId
@private
*/
normalizeId: function(hash) {
var primaryKey = get(this, 'primaryKey');
if (primaryKey === 'id') { return; }
hash.id = hash[primaryKey];
delete hash[primaryKey];
},
/**
@method normalizeUsingDeclaredMapping
@private
*/
normalizeUsingDeclaredMapping: function(type, hash) {
var attrs = get(this, 'attrs'), payloadKey, key;
if (attrs) {
for (key in attrs) {
payloadKey = attrs[key];
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}
}
},
/**
@method normalizeAttributes
@private
*/
normalizeAttributes: function(type, hash) {
var payloadKey, key;
if (this.keyForAttribute) {
type.eachAttribute(function(key) {
payloadKey = this.keyForAttribute(key);
if (key === payloadKey) { return; }
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
@method normalizeRelationships
@private
*/
normalizeRelationships: function(type, hash) {
var payloadKey, key;
if (this.keyForRelationship) {
type.eachRelationship(function(key, relationship) {
payloadKey = this.keyForRelationship(key, relationship.kind);
if (key === payloadKey) { return; }
hash[key] = hash[payloadKey];
delete hash[payloadKey];
}, this);
}
},
/**
Called when the server has returned a payload representing
a single record, such as in response to a `find` or `save`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
post 1:
```js
{
"id": 1,
"title": "Rails is omakase",
"_embedded": {
"comment": [{
"_id": 1,
"comment_title": "FIRST"
}, {
"_id": 2,
"comment_title": "Rails is unagi"
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```js
App.PostSerializer = DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
extractSingle: function(store, type, payload, id, requestType) {
var comments = payload._embedded.comment;
delete payload._embedded;
payload = { comments: comments, post: payload };
return this._super(store, type, payload, id, requestType);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractSingle`, the
built-in implementation will find the primary record in your normalized
payload and push the remaining records into the store.
The primary record is the single hash found under `post` or the first
element of the `posts` array.
The primary record has special meaning when the record is being created
for the first time or updated (`createRecord` or `updateRecord`). In
particular, it will update the properties of the record that was saved.
@method extractSingle
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {String} id
@param {'find'|'createRecord'|'updateRecord'|'deleteRecord'} requestType
@returns {Object} the primary response to the original request
*/
extractSingle: function(store, primaryType, payload, recordId, requestType) {
payload = this.normalizePayload(primaryType, payload);
var primaryTypeName = primaryType.typeKey,
primaryRecord;
for (var prop in payload) {
var typeName = this.typeForRoot(prop),
isPrimary = typeName === primaryTypeName;
// legacy support for singular resources
if (isPrimary && Ember.typeOf(payload[prop]) !== "array" ) {
primaryRecord = this.normalize(primaryType, payload[prop], prop);
continue;
}
var type = store.modelFor(typeName);
/*jshint loopfunc:true*/
forEach.call(payload[prop], function(hash) {
var typeName = this.typeForRoot(prop),
type = store.modelFor(typeName),
typeSerializer = store.serializerFor(type);
hash = typeSerializer.normalize(type, hash, prop);
var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord,
isUpdatedRecord = isPrimary && coerceId(hash.id) === recordId;
// find the primary record.
//
// It's either:
// * the record with the same ID as the original request
// * in the case of a newly created record that didn't have an ID, the first
// record in the Array
if (isFirstCreatedRecord || isUpdatedRecord) {
primaryRecord = hash;
} else {
store.push(typeName, hash);
}
}, this);
}
return primaryRecord;
},
/**
Called when the server has returned a payload representing
multiple records, such as in response to a `findAll` or `findQuery`.
It is your opportunity to clean up the server's response into the normalized
form expected by Ember Data.
If you want, you can just restructure the top-level of your payload, and
do more fine-grained normalization in the `normalize` method.
For example, if you have a payload like this in response to a request for
all posts:
```js
{
"_embedded": {
"post": [{
"id": 1,
"title": "Rails is omakase"
}, {
"id": 2,
"title": "The Parley Letter"
}],
"comment": [{
"_id": 1,
"comment_title": "Rails is unagi"
"post_id": 1
}, {
"_id": 2,
"comment_title": "Don't tread on me",
"post_id": 2
}]
}
}
```
You could implement a serializer that looks like this to get your payload
into shape:
```js
App.PostSerializer = DS.RESTSerializer.extend({
// First, restructure the top-level so it's organized by type
// and the comments are listed under a post's `comments` key.
extractArray: function(store, type, payload, id, requestType) {
var posts = payload._embedded.post;
var comments = [];
var postCache = {};
posts.forEach(function(post) {
post.comments = [];
postCache[post.id] = post;
});
payload._embedded.comment.forEach(function(comment) {
comments.push(comment);
postCache[comment.post_id].comments.push(comment);
delete comment.post_id;
}
payload = { comments: comments, posts: payload };
return this._super(store, type, payload, id, requestType);
},
normalizeHash: {
// Next, normalize individual comments, which (after `extract`)
// are now located under `comments`
comments: function(hash) {
hash.id = hash._id;
hash.title = hash.comment_title;
delete hash._id;
delete hash.comment_title;
return hash;
}
}
})
```
When you call super from your own implementation of `extractArray`, the
built-in implementation will find the primary array in your normalized
payload and push the remaining records into the store.
The primary array is the array found under `posts`.
The primary record has special meaning when responding to `findQuery`
or `findHasMany`. In particular, the primary array will become the
list of records in the record array that kicked off the request.
If your primary array contains secondary (embedded) records of the same type,
you cannot place these into the primary array `posts`. Instead, place the
secondary items into an underscore prefixed property `_posts`, which will
push these items into the store and will not affect the resulting query.
@method extractArray
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} payload
@param {'findAll'|'findMany'|'findHasMany'|'findQuery'} requestType
@returns {Array} The primary array that was returned in response
to the original query.
*/
extractArray: function(store, primaryType, payload) {
payload = this.normalizePayload(primaryType, payload);
var primaryTypeName = primaryType.typeKey,
primaryArray;
for (var prop in payload) {
var typeKey = prop,
forcedSecondary = false;
if (prop.charAt(0) === '_') {
forcedSecondary = true;
typeKey = prop.substr(1);
}
var typeName = this.typeForRoot(typeKey),
type = store.modelFor(typeName),
typeSerializer = store.serializerFor(type),
isPrimary = (!forcedSecondary && (typeName === primaryTypeName));
/*jshint loopfunc:true*/
var normalizedArray = map.call(payload[prop], function(hash) {
return typeSerializer.normalize(type, hash, prop);
}, this);
if (isPrimary) {
primaryArray = normalizedArray;
} else {
store.pushMany(typeName, normalizedArray);
}
}
return primaryArray;
},
/**
This method allows you to push a payload containing top-level
collections of records organized per type.
```js
{
"posts": [{
"id": "1",
"title": "Rails is omakase",
"author", "1",
"comments": [ "1" ]
}],
"comments": [{
"id": "1",
"body": "FIRST"
}],
"users": [{
"id": "1",
"name": "@d2h"
}]
}
```
It will first normalize the payload, so you can use this to push
in data streaming in from your server structured the same way
that fetches and saves are structured.
@method pushPayload
@param {DS.Store} store
@param {Object} payload
*/
pushPayload: function(store, payload) {
payload = this.normalizePayload(null, payload);
for (var prop in payload) {
var typeName = this.typeForRoot(prop),
type = store.modelFor(typeName);
/*jshint loopfunc:true*/
var normalizedArray = map.call(payload[prop], function(hash) {
return this.normalize(type, hash, prop);
}, this);
store.pushMany(typeName, normalizedArray);
}
},
/**
You can use this method to normalize the JSON root keys returned
into the model type expected by your store.
For example, your server may return underscored root keys rather than
the expected camelcased versions.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
typeForRoot: function(root) {
var camelized = Ember.String.camelize(root);
return Ember.String.singularize(camelized);
}
});
```
@method typeForRoot
@param {String} root
@returns {String} the model's typeKey
*/
typeForRoot: function(root) {
return Ember.String.singularize(root);
},
// SERIALIZE
/**
Called when a record is saved in order to convert the
record into JSON.
By default, it creates a JSON object with a key for
each attribute and belongsTo relationship.
For example, consider this model:
```js
App.Comment = DS.Model.extend({
title: DS.attr(),
body: DS.attr(),
author: DS.belongsTo('user')
});
```
The default serialization would create a JSON object like:
```js
{
"title": "Rails is unagi",
"body": "Rails? Omakase? O_O",
"author": 12
}
```
By default, attributes are passed through as-is, unless
you specified an attribute type (`DS.attr('date')`). If
you specify a transform, the JavaScript value will be
serialized when inserted into the JSON hash.
By default, belongs-to relationships are converted into
IDs when inserted into the JSON hash.
## IDs
`serialize` takes an options hash with a single option:
`includeId`. If this option is `true`, `serialize` will,
by default include the ID in the JSON object it builds.
The adapter passes in `includeId: true` when serializing
a record for `createRecord`, but not for `updateRecord`.
## Customization
Your server may expect a different JSON format than the
built-in serialization format.
In that case, you can implement `serialize` yourself and
return a JSON hash of your choosing.
```js
App.PostSerializer = DS.RESTSerializer.extend({
serialize: function(post, options) {
var json = {
POST_TTL: post.get('title'),
POST_BDY: post.get('body'),
POST_CMS: post.get('comments').mapProperty('id')
}
if (options.includeId) {
json.POST_ID_ = post.get('id');
}
return json;
}
});
```
## Customizing an App-Wide Serializer
If you want to define a serializer for your entire
application, you'll probably want to use `eachAttribute`
and `eachRelationship` on the record.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serialize: function(record, options) {
var json = {};
record.eachAttribute(function(name) {
json[serverAttributeName(name)] = record.get(name);
})
record.eachRelationship(function(name, relationship) {
if (relationship.kind === 'hasMany') {
json[serverHasManyName(name)] = record.get(name).mapBy('id');
}
});
if (options.includeId) {
json.ID_ = record.get('id');
}
return json;
}
});
function serverAttributeName(attribute) {
return attribute.underscore().toUpperCase();
}
function serverHasManyName(name) {
return serverAttributeName(name.singularize()) + "_IDS";
}
```
This serializer will generate JSON that looks like this:
```js
{
"TITLE": "Rails is omakase",
"BODY": "Yep. Omakase.",
"COMMENT_IDS": [ 1, 2, 3 ]
}
```
## Tweaking the Default JSON
If you just want to do some small tweaks on the default JSON,
you can call super first and make the tweaks on the returned
JSON.
```js
App.PostSerializer = DS.RESTSerializer.extend({
serialize: function(record, options) {
var json = this._super(record, options);
json.subject = json.title;
delete json.title;
return json;
}
});
```
@method serialize
@param record
@param options
*/
serialize: function(record, options) {
return this._super.apply(this, arguments);
},
/**
You can use this method to customize the root keys serialized into the JSON.
By default the REST Serializer sends camelized root keys.
For example, your server may expect underscored root objects.
```js
App.ApplicationSerializer = DS.RESTSerializer.extend({
serializeIntoHash: function(data, type, record, options) {
var root = Ember.String.decamelize(type.typeKey);
data[root] = this.serialize(record, options);
}
});
```
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Model} record
@param {Object} options
*/
serializeIntoHash: function(hash, type, record, options) {
hash[type.typeKey] = this.serialize(record, options);
},
/**
You can use this method to customize how polymorphic objects are serialized.
By default the JSON Serializer creates the key by appending `Type` to
the attribute and value from the model's camelcased model name.
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param {Object} relationship
*/
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key,
belongsTo = get(record, key);
key = this.keyForAttribute ? this.keyForAttribute(key) : key;
json[key + "Type"] = belongsTo.constructor.typeKey;
}
});
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get, set = Ember.set;
var forEach = Ember.ArrayPolyfills.forEach;
/**
The REST adapter allows your store to communicate with an HTTP server by
transmitting JSON via XHR. Most Ember.js apps that consume a JSON API
should use the REST adapter.
This adapter is designed around the idea that the JSON exchanged with
the server should be conventional.
## JSON Structure
The REST adapter expects the JSON returned from your server to follow
these conventions.
### Object Root
The JSON payload should be an object that contains the record inside a
root property. For example, in response to a `GET` request for
`/posts/1`, the JSON should look like this:
```js
{
"post": {
title: "I'm Running to Reform the W3C's Tag",
author: "Yehuda Katz"
}
}
```
### Conventional Names
Attribute names in your JSON payload should be the camelCased versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.Person = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"person": {
"firstName": "Barack",
"lastName": "Obama",
"occupation": "President"
}
}
```
## Customization
### Endpoint path customization
Endpoint paths can be prefixed with a `namespace` by setting the namespace
property on the adapter:
```js
DS.RESTAdapter.reopen({
namespace: 'api/1'
});
```
Requests for `App.Person` would now target `/api/1/people/1`.
### Host customization
An adapter can target other hosts by setting the `host` property.
```js
DS.RESTAdapter.reopen({
host: 'https://api.example.com'
});
```
### Headers customization
Some APIs require HTTP headers, e.g. to provide an API key. An array of
headers can be added to the adapter which are passed with every request:
```js
DS.RESTAdapter.reopen({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
```
@class RESTAdapter
@constructor
@namespace DS
@extends DS.Adapter
*/
DS.RESTAdapter = DS.Adapter.extend({
defaultSerializer: '_rest',
/**
Called by the store in order to fetch the JSON for a given
type and ID.
The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
This method performs an HTTP `GET` request with the id provided as part of the querystring.
@method find
@see RESTAdapter/buildURL
@see RESTAdapter/ajax
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} id
@returns Promise
*/
find: function(store, type, id) {
return this.ajax(this.buildURL(type.typeKey, id), 'GET');
},
/**
Called by the store in order to fetch a JSON array for all
of the records for a given type.
The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@private
@method findAll
@see RESTAdapter/buildURL
@see RESTAdapter/ajax
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {String} sinceToken
@returns Promise
*/
findAll: function(store, type, sinceToken) {
var query;
if (sinceToken) {
query = { since: sinceToken };
}
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
},
/**
Called by the store in order to fetch a JSON array for
the records that match a particular query.
The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
The `query` argument is a simple JavaScript object that will be passed directly
to the server as parameters.
@private
@method findQuery
@see RESTAdapter/buildURL
@see RESTAdapter/ajax
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Object} query
@returns Promise
*/
findQuery: function(store, type, query) {
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query });
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a has-many relationship that were originally
specified as IDs.
For example, if the original payload looks like:
```js
{
"id": 1,
"title": "Rails is omakase",
"comments": [ 1, 2, 3 ]
}
```
The IDs will be passed as a URL-encoded Array of IDs, in this form:
```
ids[]=1&ids[]=2&ids[]=3
```
Many servers, such as Rails and PHP, will automatically convert this URL-encoded array
into an Array for you on the server-side. If you want to encode the
IDs, differently, just override this (one-line) method.
The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a
promise for the resulting payload.
@method findMany
@see RESTAdapter/buildURL
@see RESTAdapter/ajax
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {Array<String>} ids
@returns Promise
*/
findMany: function(store, type, ids, owner) {
return this.ajax(this.buildURL(type.typeKey), 'GET', { data: { ids: ids } });
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a has-many relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "comments": "/posts/1/comments" }
}
}
```
This method will be called with the parent record and `/posts/1/comments`.
The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL.
If the URL is host-relative (starting with a single slash), the
request will use the host specified on the adapter (if any).
@method findHasMany
@see RESTAdapter/buildURL
@see RESTAdapter/ajax
@param {DS.Store} store
@param {DS.Model} record
@param {String} url
@returns Promise
*/
findHasMany: function(store, record, url) {
var host = get(this, 'host'),
id = get(record, 'id'),
type = record.constructor.typeKey;
if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') {
url = host + url;
}
return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET');
},
/**
Called by the store in order to fetch a JSON array for
the unloaded records in a belongs-to relationship that were originally
specified as a URL (inside of `links`).
For example, if your original payload looks like this:
```js
{
"person": {
"id": 1,
"name": "Tom Dale",
"links": { "group": "/people/1/group" }
}
}
```
This method will be called with the parent record and `/people/1/group`.
The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL.
@method findBelongsTo
@see RESTAdapter/buildURL
@see RESTAdapter/ajax
@param {DS.Store} store
@param {DS.Model} record
@param {String} url
@returns Promise
*/
findBelongsTo: function(store, record, url) {
var id = get(record, 'id'),
type = record.constructor.typeKey;
return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET');
},
/**
Called by the store when a newly created record is
saved via the `save` method on a model record instance.
The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method createRecord
@see RESTAdapter/buildURL
@see RESTAdapter/ajax
@see RESTAdapter/serialize
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@returns Promise
*/
createRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record, { includeId: true });
return this.ajax(this.buildURL(type.typeKey), "POST", { data: data });
},
/**
Called by the store when an existing record is saved
via the `save` method on a model record instance.
The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request
to a URL computed by `buildURL`.
See `serialize` for information on how to customize the serialized form
of a record.
@method updateRecord
@see RESTAdapter/buildURL
@see RESTAdapter/ajax
@see RESTAdapter/serialize
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@returns Promise
*/
updateRecord: function(store, type, record) {
var data = {};
var serializer = store.serializerFor(type.typeKey);
serializer.serializeIntoHash(data, type, record);
var id = get(record, 'id');
return this.ajax(this.buildURL(type.typeKey, id), "PUT", { data: data });
},
/**
Called by the store when a record is deleted.
The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`.
@method deleteRecord
@see RESTAdapter/buildURL
@see RESTAdapter/ajax
@see RESTAdapter/serialize
@param {DS.Store} store
@param {subclass of DS.Model} type
@param {DS.Model} record
@returns Promise
*/
deleteRecord: function(store, type, record) {
var id = get(record, 'id');
return this.ajax(this.buildURL(type.typeKey, id), "DELETE");
},
/**
Builds a URL for a given type and optional ID.
By default, it pluralizes the type's name (for example,
'post' becomes 'posts' and 'person' becomes 'people').
If an ID is specified, it adds the ID to the path generated
for the type, separated by a `/`.
@method buildURL
@param {String} type
@param {String} id
@returns String
*/
buildURL: function(type, id) {
var url = [],
host = get(this, 'host'),
prefix = this.urlPrefix();
if (type) { url.push(this.pathForType(type)); }
if (id) { url.push(id); }
if (prefix) { url.unshift(prefix); }
url = url.join('/');
if (!host && url) { url = '/' + url; }
return url;
},
urlPrefix: function(path, parentURL) {
var host = get(this, 'host'),
namespace = get(this, 'namespace'),
url = [];
if (path) {
// Absolute path
if (path.charAt(0) === '/') {
if (host) {
path = path.slice(1);
url.push(host);
}
// Relative path
} else if (!/^http(s)?:\/\//.test(path)) {
url.push(parentURL);
}
} else {
if (host) { url.push(host); }
if (namespace) { url.push(namespace); }
}
if (path) {
url.push(path);
}
return url.join('/');
},
/**
Determines the pathname for a given type.
By default, it pluralizes the type's name (for example,
'post' becomes 'posts' and 'person' becomes 'people').
### Pathname customization
For example if you have an object LineItem with an
endpoint of "/line_items/".
```js
DS.RESTAdapter.reopen({
pathForType: function(type) {
var decamelized = Ember.String.decamelize(type);
return Ember.String.pluralize(decamelized);
};
});
```
@method pathForType
@param {String} type
@returns String
**/
pathForType: function(type) {
return Ember.String.pluralize(type);
},
/**
Takes an ajax response, and returns a relavant error.
By default, the `ajaxError` method has the following behavior:
* It simply returns the ajax response (jqXHR).
@method ajaxError
@param jqXHR
*/
ajaxError: function(jqXHR) {
if (jqXHR) {
jqXHR.then = null;
}
return jqXHR;
},
/**
Takes a URL, an HTTP method and a hash of data, and makes an
HTTP request.
When the server responds with a payload, Ember Data will call into `extractSingle`
or `extractArray` (depending on whether the original query was for one record or
many records).
By default, `ajax` method has the following behavior:
* It sets the response `dataType` to `"json"`
* If the HTTP method is not `"GET"`, it sets the `Content-Type` to be
`application/json; charset=utf-8`
* If the HTTP method is not `"GET"`, it stringifies the data passed in. The
data is the serialized record in the case of a save.
* Registers success and failure handlers.
@method ajax
@private
@param url
@param type
@param hash
*/
ajax: function(url, type, hash) {
var adapter = this;
return new Ember.RSVP.Promise(function(resolve, reject) {
hash = adapter.ajaxOptions(url, type, hash);
hash.success = function(json) {
Ember.run(null, resolve, json);
};
hash.error = function(jqXHR, textStatus, errorThrown) {
Ember.run(null, reject, adapter.ajaxError(jqXHR));
};
Ember.$.ajax(hash);
}, "DS: RestAdapter#ajax " + type + " to " + url);
},
ajaxOptions: function(url, type, hash) {
hash = hash || {};
hash.url = url;
hash.type = type;
hash.dataType = 'json';
hash.context = this;
if (hash.data && type !== 'GET') {
hash.contentType = 'application/json; charset=utf-8';
hash.data = JSON.stringify(hash.data);
}
if (this.headers !== undefined) {
var headers = this.headers;
hash.beforeSend = function (xhr) {
forEach.call(Ember.keys(headers), function(key) {
xhr.setRequestHeader(key, headers[key]);
});
};
}
return hash;
}
});
})();
(function() {
/**
@module ember-data
*/
})();
(function() {
DS.Model.reopen({
/**
Provides info about the model for debugging purposes
by grouping the properties into more semantic groups.
Meant to be used by debugging tools such as the Chrome Ember Extension.
- Groups all attributes in "Attributes" group.
- Groups all belongsTo relationships in "Belongs To" group.
- Groups all hasMany relationships in "Has Many" group.
- Groups all flags in "Flags" group.
- Flags relationship CPs as expensive properties.
@method _debugInfo
@for DS.Model
@private
*/
_debugInfo: function() {
var attributes = ['id'],
relationships = { belongsTo: [], hasMany: [] },
expensiveProperties = [];
this.eachAttribute(function(name, meta) {
attributes.push(name);
}, this);
this.eachRelationship(function(name, relationship) {
relationships[relationship.kind].push(name);
expensiveProperties.push(name);
});
var groups = [
{
name: 'Attributes',
properties: attributes,
expand: true
},
{
name: 'Belongs To',
properties: relationships.belongsTo,
expand: true
},
{
name: 'Has Many',
properties: relationships.hasMany,
expand: true
},
{
name: 'Flags',
properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid']
}
];
return {
propertyInfo: {
// include all other mixins / properties (not just the grouped ones)
includeOtherProperties: true,
groups: groups,
// don't pre-calculate unless cached
expensiveProperties: expensiveProperties
}
};
}
});
})();
(function() {
/**
@module ember-data
*/
})();
(function() {
/**
Ember Data
@module ember-data
@main ember-data
*/
})();
(function() {
Ember.String.pluralize = function(word) {
return Ember.Inflector.inflector.pluralize(word);
};
Ember.String.singularize = function(word) {
return Ember.Inflector.inflector.singularize(word);
};
})();
(function() {
var BLANK_REGEX = /^\s*$/;
function loadUncountable(rules, uncountable) {
for (var i = 0, length = uncountable.length; i < length; i++) {
rules.uncountable[uncountable[i].toLowerCase()] = true;
}
}
function loadIrregular(rules, irregularPairs) {
var pair;
for (var i = 0, length = irregularPairs.length; i < length; i++) {
pair = irregularPairs[i];
rules.irregular[pair[0].toLowerCase()] = pair[1];
rules.irregularInverse[pair[1].toLowerCase()] = pair[0];
}
}
/**
Inflector.Ember provides a mechanism for supplying inflection rules for your
application. Ember includes a default set of inflection rules, and provides an
API for providing additional rules.
Examples:
Creating an inflector with no rules.
```js
var inflector = new Ember.Inflector();
```
Creating an inflector with the default ember ruleset.
```js
var inflector = new Ember.Inflector(Ember.Inflector.defaultRules);
inflector.pluralize('cow') //=> 'kine'
inflector.singularize('kine') //=> 'cow'
```
Creating an inflector and adding rules later.
```javascript
var inflector = Ember.Inflector.inflector;
inflector.pluralize('advice') // => 'advices'
inflector.uncountable('advice');
inflector.pluralize('advice') // => 'advice'
inflector.pluralize('formula') // => 'formulas'
inflector.irregular('formula', 'formulae');
inflector.pluralize('formula') // => 'formulae'
// you would not need to add these as they are the default rules
inflector.plural(/$/, 's');
inflector.singular(/s$/i, '');
```
Creating an inflector with a nondefault ruleset.
```javascript
var rules = {
plurals: [ /$/, 's' ],
singular: [ /\s$/, '' ],
irregularPairs: [
[ 'cow', 'kine' ]
],
uncountable: [ 'fish' ]
};
var inflector = new Ember.Inflector(rules);
```
@class Inflector
@namespace Ember
*/
function Inflector(ruleSet) {
ruleSet = ruleSet || {};
ruleSet.uncountable = ruleSet.uncountable || {};
ruleSet.irregularPairs = ruleSet.irregularPairs || {};
var rules = this.rules = {
plurals: ruleSet.plurals || [],
singular: ruleSet.singular || [],
irregular: {},
irregularInverse: {},
uncountable: {}
};
loadUncountable(rules, ruleSet.uncountable);
loadIrregular(rules, ruleSet.irregularPairs);
}
Inflector.prototype = {
/**
@method plural
@param {RegExp} regex
@param {String} string
*/
plural: function(regex, string) {
this.rules.plurals.push([regex, string.toLowerCase()]);
},
/**
@method singular
@param {RegExp} regex
@param {String} string
*/
singular: function(regex, string) {
this.rules.singular.push([regex, string.toLowerCase()]);
},
/**
@method uncountable
@param {String} regex
*/
uncountable: function(string) {
loadUncountable(this.rules, [string.toLowerCase()]);
},
/**
@method irregular
@param {String} singular
@param {String} plural
*/
irregular: function (singular, plural) {
loadIrregular(this.rules, [[singular, plural]]);
},
/**
@method pluralize
@param {String} word
*/
pluralize: function(word) {
return this.inflect(word, this.rules.plurals, this.rules.irregular);
},
/**
@method singularize
@param {String} word
*/
singularize: function(word) {
return this.inflect(word, this.rules.singular, this.rules.irregularInverse);
},
/**
@protected
@method inflect
@param {String} word
@param {Object} typeRules
@param {Object} irregular
*/
inflect: function(word, typeRules, irregular) {
var inflection, substitution, result, lowercase, isBlank,
isUncountable, isIrregular, isIrregularInverse, rule;
isBlank = BLANK_REGEX.test(word);
if (isBlank) {
return word;
}
lowercase = word.toLowerCase();
isUncountable = this.rules.uncountable[lowercase];
if (isUncountable) {
return word;
}
isIrregular = irregular && irregular[lowercase];
if (isIrregular) {
return isIrregular;
}
for (var i = typeRules.length, min = 0; i > min; i--) {
inflection = typeRules[i-1];
rule = inflection[0];
if (rule.test(word)) {
break;
}
}
inflection = inflection || [];
rule = inflection[0];
substitution = inflection[1];
result = word.replace(rule, substitution);
return result;
}
};
Ember.Inflector = Inflector;
})();
(function() {
Ember.Inflector.defaultRules = {
plurals: [
[/$/, 's'],
[/s$/i, 's'],
[/^(ax|test)is$/i, '$1es'],
[/(octop|vir)us$/i, '$1i'],
[/(octop|vir)i$/i, '$1i'],
[/(alias|status)$/i, '$1es'],
[/(bu)s$/i, '$1ses'],
[/(buffal|tomat)o$/i, '$1oes'],
[/([ti])um$/i, '$1a'],
[/([ti])a$/i, '$1a'],
[/sis$/i, 'ses'],
[/(?:([^f])fe|([lr])f)$/i, '$1$2ves'],
[/(hive)$/i, '$1s'],
[/([^aeiouy]|qu)y$/i, '$1ies'],
[/(x|ch|ss|sh)$/i, '$1es'],
[/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'],
[/^(m|l)ouse$/i, '$1ice'],
[/^(m|l)ice$/i, '$1ice'],
[/^(ox)$/i, '$1en'],
[/^(oxen)$/i, '$1'],
[/(quiz)$/i, '$1zes']
],
singular: [
[/s$/i, ''],
[/(ss)$/i, '$1'],
[/(n)ews$/i, '$1ews'],
[/([ti])a$/i, '$1um'],
[/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'],
[/(^analy)(sis|ses)$/i, '$1sis'],
[/([^f])ves$/i, '$1fe'],
[/(hive)s$/i, '$1'],
[/(tive)s$/i, '$1'],
[/([lr])ves$/i, '$1f'],
[/([^aeiouy]|qu)ies$/i, '$1y'],
[/(s)eries$/i, '$1eries'],
[/(m)ovies$/i, '$1ovie'],
[/(x|ch|ss|sh)es$/i, '$1'],
[/^(m|l)ice$/i, '$1ouse'],
[/(bus)(es)?$/i, '$1'],
[/(o)es$/i, '$1'],
[/(shoe)s$/i, '$1'],
[/(cris|test)(is|es)$/i, '$1is'],
[/^(a)x[ie]s$/i, '$1xis'],
[/(octop|vir)(us|i)$/i, '$1us'],
[/(alias|status)(es)?$/i, '$1'],
[/^(ox)en/i, '$1'],
[/(vert|ind)ices$/i, '$1ex'],
[/(matr)ices$/i, '$1ix'],
[/(quiz)zes$/i, '$1'],
[/(database)s$/i, '$1']
],
irregularPairs: [
['person', 'people'],
['man', 'men'],
['child', 'children'],
['sex', 'sexes'],
['move', 'moves'],
['cow', 'kine'],
['zombie', 'zombies']
],
uncountable: [
'equipment',
'information',
'rice',
'money',
'species',
'series',
'fish',
'sheep',
'jeans',
'police'
]
};
})();
(function() {
if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) {
/**
See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}}
@method pluralize
@for String
*/
String.prototype.pluralize = function() {
return Ember.String.pluralize(this);
};
/**
See {{#crossLink "Ember.String/singularize"}}{{/crossLink}}
@method singularize
@for String
*/
String.prototype.singularize = function() {
return Ember.String.singularize(this);
};
}
})();
(function() {
Ember.Inflector.inflector = new Ember.Inflector(Ember.Inflector.defaultRules);
})();
(function() {
})();
(function() {
/**
@module ember-data
*/
var get = Ember.get;
var forEach = Ember.EnumerableUtils.forEach;
DS.ActiveModelSerializer = DS.RESTSerializer.extend({
// SERIALIZE
/**
Converts camelcased attributes to underscored when serializing.
@method keyForAttribute
@param {String} attribute
@returns String
*/
keyForAttribute: function(attr) {
return Ember.String.decamelize(attr);
},
/**
Underscores relationship names and appends "_id" or "_ids" when serializing
relationship keys.
@method keyForRelationship
@param {String} key
@param {String} kind
@returns String
*/
keyForRelationship: function(key, kind) {
key = Ember.String.decamelize(key);
if (kind === "belongsTo") {
return key + "_id";
} else if (kind === "hasMany") {
return Ember.String.singularize(key) + "_ids";
} else {
return key;
}
},
/**
Does not serialize hasMany relationships by default.
*/
serializeHasMany: Ember.K,
/**
Underscores the JSON root keys when serializing.
@method serializeIntoHash
@param {Object} hash
@param {subclass of DS.Model} type
@param {DS.Model} record
@param {Object} options
*/
serializeIntoHash: function(data, type, record, options) {
var root = Ember.String.decamelize(type.typeKey);
data[root] = this.serialize(record, options);
},
/**
Serializes a polymorphic type as a fully capitalized model name.
@method serializePolymorphicType
@param {DS.Model} record
@param {Object} json
@param relationship
*/
serializePolymorphicType: function(record, json, relationship) {
var key = relationship.key,
belongsTo = get(record, key);
key = this.keyForAttribute(key);
json[key + "_type"] = Ember.String.capitalize(belongsTo.constructor.typeKey);
},
// EXTRACT
/**
Extracts the model typeKey from underscored root objects.
@method typeForRoot
@param {String} root
@returns String the model's typeKey
*/
typeForRoot: function(root) {
var camelized = Ember.String.camelize(root);
return Ember.String.singularize(camelized);
},
/**
Add extra step to `DS.RESTSerializer.normalize` so links are
normalized.
If your payload looks like this
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flagged_comments": "api/comments/flagged" }
}
}
```
The normalized version would look like this
```js
{
"post": {
"id": 1,
"title": "Rails is omakase",
"links": { "flaggedComments": "api/comments/flagged" }
}
}
```
@method normalize
@param {subclass of DS.Model} type
@param {Object} hash
@param {String} prop
@returns Object
*/
normalize: function(type, hash, prop) {
this.normalizeLinks(hash);
return this._super(type, hash, prop);
},
/**
Convert `snake_cased` links to `camelCase`
@method normalizeLinks
@param {Object} hash
*/
normalizeLinks: function(data){
if (data.links) {
var links = data.links;
for (var link in links) {
var camelizedLink = Ember.String.camelize(link);
if (camelizedLink !== link) {
links[camelizedLink] = links[link];
delete links[link];
}
}
}
},
/**
Normalize the polymorphic type from the JSON.
Normalize:
```js
{
id: "1"
minion: { type: "evil_minion", id: "12"}
}
```
To:
```js
{
id: "1"
minion: { type: "evilMinion", id: "12"}
}
```
@method normalizeRelationships
@private
*/
normalizeRelationships: function(type, hash) {
var payloadKey, payload;
if (this.keyForRelationship) {
type.eachRelationship(function(key, relationship) {
if (relationship.options.polymorphic) {
payloadKey = this.keyForAttribute(key);
payload = hash[payloadKey];
if (payload && payload.type) {
payload.type = this.typeForRoot(payload.type);
} else if (payload && relationship.kind === "hasMany") {
var self = this;
forEach(payload, function(single) {
single.type = self.typeForRoot(single.type);
});
}
} else {
payloadKey = this.keyForRelationship(key, relationship.kind);
payload = hash[payloadKey];
}
hash[key] = payload;
if (key !== payloadKey) {
delete hash[payloadKey];
}
}, this);
}
}
});
})();
(function() {
var get = Ember.get;
var forEach = Ember.EnumerableUtils.forEach;
/**
The EmbeddedRecordsMixin allows you to add embedded record support to your
serializers.
To set up embedded records, you include the mixin into the serializer and then
define your embedded relations.
```js
App.PostSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
comments: {embedded: 'always'}
}
})
```
Currently only `{embedded: 'always'}` records are supported.
@class EmbeddedRecordsMixin
@namespace DS
*/
DS.EmbeddedRecordsMixin = Ember.Mixin.create({
/**
Serialize has-may relationship when it is configured as embedded objects.
@method serializeHasMany
*/
serializeHasMany: function(record, json, relationship) {
var key = relationship.key,
attrs = get(this, 'attrs'),
embed = attrs && attrs[key] && attrs[key].embedded === 'always';
if (embed) {
json[this.keyForAttribute(key)] = get(record, key).map(function(relation) {
var data = relation.serialize(),
primaryKey = get(this, 'primaryKey');
data[primaryKey] = get(relation, primaryKey);
return data;
}, this);
}
},
/**
Extract embedded objects out of the payload for a single object
and add them as sideloaded objects instead.
@method extractSingle
*/
extractSingle: function(store, primaryType, payload, recordId, requestType) {
var root = this.keyForAttribute(primaryType.typeKey),
partial = payload[root];
updatePayloadWithEmbedded(store, this, primaryType, partial, payload);
return this._super(store, primaryType, payload, recordId, requestType);
},
/**
Extract embedded objects out of a standard payload
and add them as sideloaded objects instead.
@method extractArray
*/
extractArray: function(store, type, payload) {
var root = this.keyForAttribute(type.typeKey),
partials = payload[Ember.String.pluralize(root)];
forEach(partials, function(partial) {
updatePayloadWithEmbedded(store, this, type, partial, payload);
}, this);
return this._super(store, type, payload);
}
});
function updatePayloadWithEmbedded(store, serializer, type, partial, payload) {
var attrs = get(serializer, 'attrs');
if (!attrs) {
return;
}
type.eachRelationship(function(key, relationship) {
var expandedKey, embeddedTypeKey, attribute, ids,
config = attrs[key],
serializer = store.serializerFor(relationship.type.typeKey),
primaryKey = get(serializer, "primaryKey");
if (relationship.kind !== "hasMany") {
return;
}
if (config && (config.embedded === 'always' || config.embedded === 'load')) {
// underscore forces the embedded records to be side loaded.
// it is needed when main type === relationship.type
embeddedTypeKey = '_' + Ember.String.pluralize(relationship.type.typeKey);
expandedKey = this.keyForRelationship(key, relationship.kind);
attribute = this.keyForAttribute(key);
ids = [];
if (!partial[attribute]) {
return;
}
payload[embeddedTypeKey] = payload[embeddedTypeKey] || [];
forEach(partial[attribute], function(data) {
var embeddedType = store.modelFor(relationship.type.typeKey);
updatePayloadWithEmbedded(store, serializer, embeddedType, data, payload);
ids.push(data[primaryKey]);
payload[embeddedTypeKey].push(data);
});
partial[expandedKey] = ids;
delete partial[attribute];
}
}, serializer);
}
})();
(function() {
/**
@module ember-data
*/
var forEach = Ember.EnumerableUtils.forEach;
/**
The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate
with a JSON API that uses an underscored naming convention instead of camelcasing.
It has been designed to work out of the box with the
[active_model_serializers](http://github.com/rails-api/active_model_serializers)
Ruby gem.
This adapter extends the DS.RESTAdapter by making consistent use of the camelization,
decamelization and pluralization methods to normalize the serialized JSON into a
format that is compatible with a conventional Rails backend and Ember Data.
## JSON Structure
The ActiveModelAdapter expects the JSON returned from your server to follow
the REST adapter conventions substituting underscored keys for camelcased ones.
### Conventional Names
Attribute names in your JSON payload should be the underscored versions of
the attributes in your Ember.js models.
For example, if you have a `Person` model:
```js
App.FamousPerson = DS.Model.extend({
firstName: DS.attr('string'),
lastName: DS.attr('string'),
occupation: DS.attr('string')
});
```
The JSON returned should look like this:
```js
{
"famous_person": {
"first_name": "Barack",
"last_name": "Obama",
"occupation": "President"
}
}
```
@class ActiveModelAdapter
@constructor
@namespace DS
@extends DS.Adapter
**/
DS.ActiveModelAdapter = DS.RESTAdapter.extend({
defaultSerializer: '_ams',
/**
The ActiveModelAdapter overrides the `pathForType` method to build
underscored URLs by decamelizing and pluralizing the object type name.
```js
this.pathForType("famousPerson");
//=> "famous_people"
```
@method pathForType
@param {String} type
@returns String
*/
pathForType: function(type) {
var decamelized = Ember.String.decamelize(type);
return Ember.String.pluralize(decamelized);
},
/**
The ActiveModelAdapter overrides the `ajaxError` method
to return a DS.InvalidError for all 422 Unprocessable Entity
responses.
A 422 HTTP response from the server generally implies that the request
was well formed but the API was unable to process it because the
content was not semantically correct or meaningful per the API.
For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918
https://tools.ietf.org/html/rfc4918#section-11.2
@method ajaxError
@param jqXHR
@returns error
*/
ajaxError: function(jqXHR) {
var error = this._super(jqXHR);
if (jqXHR && jqXHR.status === 422) {
var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"],
errors = {};
forEach(Ember.keys(jsonErrors), function(key) {
errors[Ember.String.camelize(key)] = jsonErrors[key];
});
return new DS.InvalidError(errors);
} else {
return error;
}
}
});
})();
(function() {
})();
(function() {
Ember.onLoad('Ember.Application', function(Application) {
Application.initializer({
name: "activeModelAdapter",
initialize: function(container, application) {
application.register('serializer:_ams', DS.ActiveModelSerializer);
application.register('adapter:_ams', DS.ActiveModelAdapter);
}
});
});
})();
(function() {
})();
})();
| schoren/cdnjs | ajax/libs/ember-data.js/1.0.0-beta.4/ember-data.debug.js | JavaScript | mit | 254,958 |
(function($){
(function () {
if($.event.special.mousewheel){return;}
var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'],
toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ?
['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'],
slice = Array.prototype.slice,
nullLowestDeltaTimeout, lowestDelta;
if ( $.event.fixHooks ) {
for ( var i = toFix.length; i; ) {
$.event.fixHooks[ toFix[--i] ] = $.event.mouseHooks;
}
}
$.event.special.mousewheel = {
version: '3.1.6',
setup: function() {
if ( this.addEventListener ) {
for ( var i = toBind.length; i; ) {
this.addEventListener( toBind[--i], handler, false );
}
} else {
this.onmousewheel = handler;
}
},
teardown: function() {
if ( this.removeEventListener ) {
for ( var i = toBind.length; i; ) {
this.removeEventListener( toBind[--i], handler, false );
}
} else {
this.onmousewheel = null;
}
}
};
$.fn.extend({
mousewheel: function(fn) {
return fn ? this.on('mousewheel', fn) : this.trigger('mousewheel');
},
unmousewheel: function(fn) {
return this.off('mousewheel', fn);
}
});
function handler(event) {
var orgEvent = event || window.event,
args = slice.call(arguments, 1),
delta = 0,
deltaX = 0,
deltaY = 0,
absDelta = 0;
event = $.event.fix(orgEvent);
event.type = 'mousewheel';
// Old school scrollwheel delta
if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; }
if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; }
if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; }
if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; }
// Firefox < 17 horizontal scrolling related to DOMMouseScroll event
if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) {
deltaX = deltaY * -1;
deltaY = 0;
}
// Set delta to be deltaY or deltaX if deltaY is 0 for backwards compatabilitiy
delta = deltaY === 0 ? deltaX : deltaY;
// New school wheel delta (wheel event)
if ( 'deltaY' in orgEvent ) {
deltaY = orgEvent.deltaY * -1;
delta = deltaY;
}
if ( 'deltaX' in orgEvent ) {
deltaX = orgEvent.deltaX;
if ( deltaY === 0 ) { delta = deltaX * -1; }
}
// No change actually happened, no reason to go any further
if ( deltaY === 0 && deltaX === 0 ) { return; }
// Store lowest absolute delta to normalize the delta values
absDelta = Math.max( Math.abs(deltaY), Math.abs(deltaX) );
if ( !lowestDelta || absDelta < lowestDelta ) {
lowestDelta = absDelta;
}
// Get a whole, normalized value for the deltas
delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta);
deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta);
deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta);
// Add information to the event object
event.deltaX = deltaX;
event.deltaY = deltaY;
event.deltaFactor = lowestDelta;
// Add event and delta to the front of the arguments
args.unshift(event, delta, deltaX, deltaY);
// Clearout lowestDelta after sometime to better
// handle multiple device types that give different
// a different lowestDelta
// Ex: trackpad = 3 and mouse wheel = 120
if (nullLowestDeltaTimeout) { clearTimeout(nullLowestDeltaTimeout); }
nullLowestDeltaTimeout = setTimeout(nullLowestDelta, 200);
return ($.event.dispatch || $.event.handle).apply(this, args);
}
function nullLowestDelta() {
lowestDelta = null;
}
})();
(function(){
if($.event.special.mwheelIntent){return;}
var mwheelI = {
pos: [-260, -260]
},
minDif = 3,
doc = document,
root = doc.documentElement,
body = doc.body,
longDelay, shortDelay
;
if(!body){
$(function(){
body = doc.body;
});
}
function unsetPos(){
if(this === mwheelI.elem){
mwheelI.pos = [-260, -260];
mwheelI.elem = false;
minDif = 3;
}
}
$.event.special.mwheelIntent = {
setup: function(){
var jElm = $(this).on('mousewheel', $.event.special.mwheelIntent.handler);
if( this !== doc && this !== root && this !== body ){
jElm.on('mouseleave', unsetPos);
}
jElm = null;
return true;
},
teardown: function(){
$(this)
.off('mousewheel', $.event.special.mwheelIntent.handler)
.off('mouseleave', unsetPos)
;
return true;
},
handler: function(e, d){
var pos = [e.clientX, e.clientY];
if( this === mwheelI.elem || Math.abs(mwheelI.pos[0] - pos[0]) > minDif || Math.abs(mwheelI.pos[1] - pos[1]) > minDif ){
mwheelI.elem = this;
mwheelI.pos = pos;
minDif = 250;
clearTimeout(shortDelay);
shortDelay = setTimeout(function(){
minDif = 10;
}, 200);
clearTimeout(longDelay);
longDelay = setTimeout(function(){
minDif = 3;
}, 1500);
e = $.extend({}, e, {type: 'mwheelIntent'});
return ($.event.dispatch || $.event.handle).apply(this, arguments);
}
}
};
$.fn.extend({
mwheelIntent: function(fn) {
return fn ? this.on("mwheelIntent", fn) : this.trigger("mwheelIntent");
},
unmwheelIntent: function(fn) {
return this.off("mwheelIntent", fn);
}
});
$(function(){
body = doc.body;
//assume that document is always scrollable, doesn't hurt if not
$(doc).on('mwheelIntent.mwheelIntentDefault', $.noop);
});
})();
(function(){
if($.event.special.mousepress){return;}
var removeTimer = function(elem, full){
var timer = elem.data('mousepresstimer');
if(timer){
clearTimeout(timer);
}
if(full){
elem.off('mouseup.mousepressext mouseleave.mousepressext');
}
elem = null;
};
$.event.special.mousepress = {
setup: function(){
var timer;
$(this).on('mousedown.mousepressext', function(e){
var elem = $(this);
var startIntervall = function(delay){
var steps = 0;
removeTimer(elem);
elem.data('mousepresstimer', setInterval(function(){
$.event.special.mousepress.handler(elem[0], e);
steps++;
if(steps > 3 && delay > 45){
startIntervall(delay - 40);
}
}, delay));
};
var target = $(e.target).trigger('mousepressstart', [e]);
removeTimer(elem);
elem.data('mousepresstimer', setTimeout(function(){
startIntervall(180);
}, 200));
elem.on('mouseup.mousepressext mouseleave.mousepressext', function(e){
removeTimer(elem, true);
target.trigger('mousepressend', [e]);
elem = null;
target = null;
});
});
},
teardown: function(){
removeTimer($(this).off('.mousepressext'), true);
},
handler: function(elem, e){
return $.event.dispatch.call(elem, {type: 'mousepress', target: e.target, pageX: e.pageX, pageY: e.pageY});
}
};
})();
})(webshims.$);
webshims.register('forms-picker', function($, webshims, window, document, undefined, options){
"use strict";
var picker = webshims.picker;
var actions = picker._actions;
var moduleOpts = options;
var getDateArray = function(date){
var ret = [date.getFullYear(), moduleOpts.addZero(date.getMonth() + 1), moduleOpts.addZero(date.getDate())];
ret.month = ret[0]+'-'+ret[1];
ret.date = ret[0]+'-'+ret[1]+'-'+ret[2];
ret.time = moduleOpts.addZero(date.getHours()) +':'+ moduleOpts.addZero(date.getMinutes());
ret['datetime-local'] = ret.date +'T'+ ret.time;
return ret;
};
var today = getDateArray(new Date());
var _setFocus = function(element, _noFocus){
element = $(element || this.activeButton);
this.activeButton.attr({tabindex: '-1', 'aria-selected': 'false'});
this.activeButton = element.attr({tabindex: '0', 'aria-selected': 'true'});
this.index = this.buttons.index(this.activeButton[0]);
clearTimeout(this.timer);
picker._genericSetFocus.apply(this, arguments);
};
var _initialFocus = function(){
var sel;
if(this.popover.navedInitFocus){
sel = this.popover.navedInitFocus.sel || this.popover.navedInitFocus;
if((!this.activeButton || !this.activeButton[0]) && this.buttons[sel]){
this.activeButton = this.buttons[sel]();
} else if(sel){
this.activeButton = $(sel, this.element);
}
if(!this.activeButton[0] && this.popover.navedInitFocus.alt){
this.activeButton = this.buttons[this.popover.navedInitFocus.alt]();
}
}
if(!this.activeButton || !this.activeButton[0]){
this.activeButton = this.buttons.filter('.checked-value');
}
if(!this.activeButton[0]){
this.activeButton = this.buttons.filter('.this-value');
}
if(!this.activeButton[0]){
this.activeButton = this.buttons.eq(0);
}
this.setFocus(this.activeButton, this.opts.noFocus);
};
var formcfg = webshims.formcfg;
var curCfg = formcfg.__active || formcfg[''];
var stopPropagation = function(e){
e.stopImmediatePropagation();
};
var steps = options.steps;
var getMonthNameHTML = function(index, year, prefix){
var dateCfg = curCfg.date;
var str = [];
if(!prefix){
prefix = '';
}
$.each({monthNames: 'monthname', monthDigits: 'month-digit', monthNamesShort: 'monthname-short'}, function(prop, cName){
var name = [prefix + dateCfg[prop][index]];
if(year){
name.push(year);
if(dateCfg.showMonthAfterYear){
name.reverse();
}
}
str.push('<span class="'+ cName +'">'+ name.join(' ') +'</span>');
});
return str.join('');
};
var setJump = ('inputMode' in document.createElement('input')) || !((/ipad|iphone/i).test(navigator.userAgent));
var widgetProtos = {
_addBindings: function(){
var isFocused;
var that = this;
var o = this.options;
var eventTimer = (function(){
var events = {};
return {
init: function(name, curVal, fn){
if (!events[name]) {
events[name] = {
fn: fn
};
$(that.orig).on(name, function(){
events[name].val = $.prop(that.orig, 'value');
});
}
events[name].val = curVal;
},
call: function(name, val){
if (events[name] && events[name].val != val) {
clearTimeout(events[name].timer);
events[name].val = val;
events[name].fn(val, that);
}
}
};
})();
var initChangeEvents = function(){
eventTimer.init('input', $.prop(that.orig, 'value'), that.options.input);
eventTimer.init('change', $.prop(that.orig, 'value'), that.options.change);
};
var step = {};
var preventBlur = function(e){
if (preventBlur.prevent) {
e.preventDefault();
$(isFocused || that.element.getShadowFocusElement()).trigger('focus');
stopPropagation(e);
return true;
}
};
(function(){
var timer;
var call = function(e){
var val;
clearTimeout(timer);
val = that.parseValue();
if (that.type == 'color') {
that.inputElements.val(val);
}
$.prop(that.orig, 'value', val);
eventTimer.call('input', val);
if (!e || e.type != 'wsupdatevalue') {
eventTimer.call('change', val);
}
};
var onFocus = function(e){
clearTimeout(timer);
$(e.target).trigger('wswidgetfocusin');
};
var onBlur = function(e){
clearTimeout(timer);
timer = setTimeout(call, 0);
$(e.target).trigger('wswidgetfocusout');
if (e.type == 'ws__change') {
stopPropagation(e);
if (!o.splitInput) {
call();
}
}
};
that.element.on('wsupdatevalue', call);
that.inputElements.add(that.buttonWrapper).add(that.element).on({
'ws__focusin': onFocus,
'ws__blur ws__focusout ws__change': onBlur
});
setTimeout(function(){
if (that.popover) {
that.popover.element.on('wspopoverhide', onBlur);
that.popover.element.children().on({
'focusin': onFocus,
'focusout': onBlur
});
}
}, 0);
})();
var isDisabled = false;
var spinEvents = {};
var spinElement = o.splitInput ? this.inputElements.filter('.ws-spin') : this.inputElements.eq(0);
var elementEvts = {
ws__blur: function(e){
if (!preventBlur(e) && !o.disabled && !o.readonly) {
if (!preventBlur.prevent) {
isFocused = false;
}
}
stopPropagation(e);
},
ws__focus: function(e){
if (!isFocused) {
initChangeEvents();
isFocused = this;
}
},
keypress: function(e){
if (e.isDefaultPrevented()) {
return;
}
var chr;
var stepped = true;
var code = e.keyCode;
if (!e.ctrlKey && !e.metaKey && curCfg[that.type + 'Signs']) {
chr = String.fromCharCode(e.charCode == null ? code : e.charCode);
stepped = !(chr < " " || (curCfg[that.type + 'Signs'] + '0123456789').indexOf(chr) > -1);
}
else {
stepped = false;
}
if (stepped) {
e.preventDefault();
}
},
ws__input: (this.type == 'color' || !this.isValid) ? $.noop : (function(){
var timer;
var delay = that.type == 'number' && !o.nogrouping ? 99 : 199;
var check = function(){
var val = that.parseValue(true);
if (val && that.isValid(val)) {
that.setInput(val, true);
}
};
return function(){
clearTimeout(timer);
timer = setTimeout(check, delay);
};
})(),
'ws__input keydown keypress': (function(){
var timer;
var isStopped = false;
var releaseTab = function(){
if (isStopped === true) {
isStopped = 'semi';
timer = setTimeout(releaseTab, 250);
}
else {
isStopped = false;
}
};
var stopTab = function(){
isStopped = true;
clearTimeout(timer);
timer = setTimeout(releaseTab, 300);
};
var select = function(){
var elem = this;
setTimeout(function(){
elem.focus();
if(elem.select){
elem.select();
}
}, 4);
stopTab();
};
return function(e){
if (o.splitInput && o.jumpInputs) {
if (e.type == 'ws__input') {
if ($.prop(this, 'value').length === $.prop(this, 'maxLength')) {
try {
$(this).next().next('input, select').each(select);
}
catch (er) {}
}
}
else
if (!e.shiftKey && !e.crtlKey && e.keyCode == 9 && (isStopped === true || (isStopped && !$.prop(this, 'value')))) {
e.preventDefault();
}
}
};
})()
};
var mouseDownInit = function(){
if (!o.disabled && !isFocused) {
that.element.getShadowFocusElement().trigger('focus');
}
preventBlur.set();
return false;
};
preventBlur.set = (function(){
var timer;
var reset = function(){
preventBlur.prevent = false;
};
return function(){
clearTimeout(timer);
preventBlur.prevent = true;
setTimeout(reset, 9);
};
})();
if(o.splitInput && setJump && o.jumpInputs == null){
o.jumpInputs = true;
}
this.buttonWrapper.on('mousedown', mouseDownInit);
this.setInput = function(value, isLive){
that.value(value, false, isLive);
eventTimer.call('input', value);
};
this.setChange = function(value){
that.setInput(value);
eventTimer.call('change', value);
};
this.inputElements.on(elementEvts);
if (steps[this.type]) {
['stepUp', 'stepDown'].forEach(function(name){
step[name] = function(factor){
if (!o.disabled && !o.readonly) {
if (!isFocused) {
mouseDownInit();
}
var ret = false;
if (!factor) {
factor = 1;
}
if(o.stepfactor){
factor *= o.stepfactor;
}
if(factor > 0 && !isNaN(that.minAsNumber) && (isNaN(that.valueAsNumber) || that.valueAsNumber < that.minAsNumber) && that.elemHelper.prop('valueAsNumber') <= that.minAsNumber){
ret = that.asValue(that.minAsNumber);
} else if(factor < 0 && !isNaN(that.maxAsNumber) && (isNaN(that.valueAsNumber) || that.valueAsNumber > that.minAsNumber) && that.elemHelper.prop('valueAsNumber') <= that.maxAsNumber){
ret = that.asValue(that.maxAsNumber);
}
if(ret === false){
try {
that.elemHelper[name](factor);
ret = that.elemHelper.prop('value');
} catch (er) {
if (!o.value && that.maxAsNumber >= that.minAsNumber) {
ret = o.defValue;
}
}
}
if (ret !== false && o.value != ret) {
that.value(ret);
if(o.toFixed && o.type == 'number'){
that.element[0].value = that.toFixed(that.element[0].value, true);
}
eventTimer.call('input', ret);
}
return ret;
}
};
});
if (!o.noSpinbtn) {
spinEvents.mwheelIntent = function(e, delta){
if (delta && isFocused && !o.disabled) {
step[delta > 0 ? 'stepUp' : 'stepDown']();
e.preventDefault();
}
};
spinEvents.keydown = function(e){
if (o.list || e.isDefaultPrevented() || (e.altKey && e.keyCode == 40) || $.attr(this, 'list')) {
return;
}
var stepped = true;
var code = e.keyCode;
if (code == 38) {
step.stepUp();
}
else
if (code == 40) {
step.stepDown();
}
else {
stepped = false;
}
if (stepped) {
e.preventDefault();
}
};
spinElement.on(spinEvents);
}
$(this.buttonWrapper)
.on('mousepressstart mousepressend', '.step-up, .step-down', function(e){
var fn = 'removeClass';
if(e.type == 'mousepressstart' && !isDisabled){
fn = 'addClass';
}
$(this)[fn]('mousepress-ui');
})
.on('mousedown mousepress', '.step-up', function(e){
if(e.type == 'mousedown'){
isDisabled = (o.disabled || o.readOnly || $.find.matchesSelector(that.orig, ':disabled'));
}
if(!isDisabled){
step.stepUp();
}
})
.on('mousedown mousepress', '.step-down', function(e){
if(!isDisabled && !o.disabled && !o.readOnly){
step.stepDown();
}
})
;
initChangeEvents();
}
},
_getSelectionEnd: function(val){
var oldVal, selectionEnd;
if((oldVal = this.element[0].value) && this.element.is(':focus') && (selectionEnd = this.element.prop('selectionEnd')) < oldVal.length){
if(this.type == 'number'){
oldVal = oldVal.substr(0, selectionEnd).split(curCfg.numberFormat[',']);
val = val.substr(0, selectionEnd).split(curCfg.numberFormat[',']);
if(oldVal.length < val.length){
selectionEnd++;
} else if(oldVal.length > val.length){
selectionEnd--;
}
}
return selectionEnd;
}
},
initDataList: function(){
var listTimer;
var that = this;
var updateList = function(){
$(that.orig)
.jProp('list')
.off('updateDatalist', updateList)
.on('updateDatalist', updateList)
;
clearTimeout(listTimer);
listTimer = setTimeout(function(){
if(that.list){
that.list();
}
}, 9);
};
$(this.orig).onTrigger('listdatalistchange', updateList);
},
getOptions: function(){
var options = {};
var datalist = $(this.orig).jProp('list');
datalist.find('option').each(function(){
options[$.prop(this, 'value')] = $.prop(this, 'label');
});
return [options, datalist.data('label')];
}
};
$.extend($.fn.wsBaseWidget.wsProto, widgetProtos);
$.extend($.fn.spinbtnUI.wsProto, widgetProtos);
$(formcfg).on('change', function(e, data){
curCfg = formcfg.__active;
});
webshims.ListBox = function (element, popover, opts){
this.element = $('ul', element);
this.popover = popover;
this.opts = opts || {};
this.buttons = $('button:not(:disabled)', this.element);
this.ons(this);
this._initialFocus();
};
webshims.ListBox.prototype = {
setFocus: _setFocus,
_initialFocus: _initialFocus,
prev: function(){
var index = this.index - 1;
if(index < 0){
if(this.opts.prev){
this.popover.navedInitFocus = 'last';
this.popover.actionFn(this.opts.prev);
this.popover.navedInitFocus = false;
}
} else {
this.setFocus(this.buttons.eq(index));
}
},
next: function(){
var index = this.index + 1;
if(index >= this.buttons.length){
if(this.opts.next){
this.popover.navedInitFocus = 'first';
this.popover.actionFn(this.opts.next);
this.popover.navedInitFocus = false;
}
} else {
this.setFocus(this.buttons.eq(index));
}
},
ons: function(that){
this.element
.on({
'keydown': function(e){
var handled;
var key = e.keyCode;
if(e.ctrlKey){return;}
if(key == 36 || key == 33){
that.setFocus(that.buttons.eq(0));
handled = true;
} else if(key == 34 || key == 35){
that.setFocus(that.buttons.eq(that.buttons.length - 1));
handled = true;
} else if(key == 38 || key == 37){
that.prev();
handled = true;
} else if(key == 40 || key == 39){
that.next();
handled = true;
}
if(handled){
return false;
}
}
})
;
}
};
webshims.Grid = function (element, popover, opts){
this.element = $('tbody', element);
this.popover = popover;
this.opts = opts || {};
this.buttons = $('button:not(:disabled):not(.othermonth)', this.element);
this.ons(this);
this._initialFocus();
if(this.popover.openedByFocus){
this.popover.activeElement = this.activeButton;
}
};
webshims.Grid.prototype = {
setFocus: _setFocus,
_initialFocus: _initialFocus,
first: function(){
this.setFocus(this.buttons.eq(0));
},
last: function(){
this.setFocus(this.buttons.eq(this.buttons.length - 1));
},
upPage: function(){
$('.ws-picker-header > button:not(:disabled)', this.popover.element).trigger('click');
},
downPage: function(){
this.activeButton.filter(':not([data-action="changeInput"])').trigger('click');
},
ons: function(that){
this.element
.on({
'keydown': function(e){
var handled, sKey;
var key = e.keyCode;
if(e.shiftKey){return;}
sKey = e.ctrlKey || e.altKey; //|| e.metaKey
if((sKey && key == 40)){
handled = 'downPage';
} else if((sKey && key == 38)){
handled = 'upPage';
} else if(key == 33 || (sKey && key == 37)){
handled = 'prevPage';
} else if(key == 34 || (sKey && key == 39)){
handled = 'nextPage';
} else if(e.keyCode == 36 || e.keyCode == 33){
handled = 'first';
} else if(e.keyCode == 35){
handled = 'last';
} else if(e.keyCode == 38){
handled = 'up';
} else if(e.keyCode == 37){
handled = 'prev';
} else if(e.keyCode == 40){
handled = 'down';
} else if(e.keyCode == 39){
handled = 'next';
}
if(handled){
that[handled]();
return false;
}
}
})
;
}
};
$.each({
prevPage: {get: 'last', action: 'prev'},
nextPage: {get: 'first', action: 'next'}
}, function(name, val){
webshims.Grid.prototype[name] = function(){
if(this.opts[val.action]){
this.popover.navedInitFocus = {
sel: 'button[data-id="'+ this.activeButton.attr('data-id') +'"]:not(:disabled,.othermonth)',
alt: val.get
};
this.popover.actionFn(this.opts[val.action]);
this.popover.navedInitFocus = false;
}
};
});
$.each({
up: {traverse: 'prevAll', get: 'last', action: 'prev', reverse: true},
down: {traverse: 'nextAll', get: 'first', action: 'next'}
}, function(name, val){
webshims.Grid.prototype[name] = function(){
var cellIndex = this.activeButton.closest('td').prop('cellIndex');
var sel = 'td:nth-child('+(cellIndex + 1)+') button:not(:disabled,.othermonth)';
var button = this.activeButton.closest('tr')[val.traverse]();
if(val.reverse){
button = $(button.get().reverse());
}
button = button.find(sel)[val.get]();
if(!button[0]){
if(this.opts[val.action]){
this.popover.navedInitFocus = sel+':'+val.get;
this.popover.actionFn(this.opts[val.action]);
this.popover.navedInitFocus = false;
}
} else {
this.setFocus(button.eq(0));
}
};
});
$.each({
prev: {traverse: 'prevAll',get: 'last', reverse: true},
next: {traverse: 'nextAll', get: 'first'}
}, function(name, val){
webshims.Grid.prototype[name] = function(){
var sel = 'button:not(:disabled,.othermonth)';
var button = this.activeButton.closest('td')[val.traverse]('td');
if(val.reverse){
button = $(button.get().reverse());
}
button = button.find(sel)[val.get]();
if(!button[0]){
button = this.activeButton.closest('tr')[val.traverse]('tr');
if(val.reverse){
button = $(button.get().reverse());
}
button = button.find(sel)[val.get]();
}
if(!button[0]){
if(this.opts[name]){
this.popover.navedInitFocus = val.get;
this.popover.actionFn(this.opts[name]);
this.popover.navedInitFocus = false;
}
} else {
this.setFocus(button.eq(0));
}
};
});
//taken from jquery ui
picker.getWeek = function(date){
var time;
var checkDate = new Date(date.getTime());
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
time = checkDate.getTime();
checkDate.setMonth(0);
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
};
picker.getYearList = function(value, data){
var j, i, val, disabled, lis, prevDisabled, nextDisabled, classStr, classArray, start;
var o = data.options;
var size = o.size;
var max = o.max.split('-');
var min = o.min.split('-');
var cols = o.cols || 4;
var currentValue = o.value.split('-');
var xthCorrect = 0;
var enabled = 0;
var str = '';
var rowNum = 0;
var triggerValueValidation = (data.orig && ('validatevalue' in $.data(data.orig)));
if(!data.options.useDecadeBase){
if(!max[0] && min[0]){
data.options.useDecadeBase = 'min';
} else if(max[0] && !min[0]){
data.options.useDecadeBase = 'max';
}
}
if(data.options.useDecadeBase == 'max' && max[0]){
xthCorrect = 11 - (max[0] % 12);
} else if(data.options.useDecadeBase == 'min' && min[0]){
xthCorrect = 0 - (min[0] % 12);
}
value = value[0] * 1;
start = value - ((value + xthCorrect) % (12 * size));
for(j = 0; j < size; j++){
if(j){
start += 12;
} else {
prevDisabled = picker.isInRange([start-1], max, min) ? {'data-action': 'setYearList','value': start-1} : false;
}
str += '<div class="year-list picker-list ws-index-'+ j +'"><div class="ws-picker-header"><select data-action="setYearList" class="decade-select">'+ picker.createYearSelect(value, max, min, '', {start: start, step: 12 * size, label: start+' – '+(start + 11)}).join('') +'</select><button disabled="disabled"><span>'+ start +' – '+(start + 11)+'</span></button></div>';
lis = [];
for(i = 0; i < 12; i++){
val = start + i ;
classArray = [];
if( !picker.isInRange([val], max, min) || (triggerValueValidation && $(data.orig).triggerHandler('validatevalue', [{value: val, valueAsDate: null, isPartial: [val]}]))){
disabled = ' disabled=""';
} else {
disabled = '';
enabled++;
}
if(val == today[0]){
classArray.push('this-value');
}
if(currentValue[0] == val){
classArray.push('checked-value');
}
classStr = classArray.length ? ' class="'+ (classArray.join(' ')) +'"' : '';
if(i && !(i % cols)){
rowNum++;
lis.push('</tr><tr class="ws-row-'+ rowNum +'">');
}
lis.push('<td class="ws-item-'+ i +'" role="presentation"><button data-id="year-'+ i +'" type="button"'+ disabled + classStr +' data-action="setMonthList" value="'+val+'" tabindex="-1" role="gridcell">'+val+'</button></td>');
}
if(j == size - 1){
nextDisabled = picker.isInRange([val+1], max, min) ? {'data-action': 'setYearList','value': val+1} : false;
}
str += '<div class="picker-grid"><table role="grid" aria-label="'+ start +' – '+(start + 11)+'"><tbody><tr class="ws-row-0">'+ (lis.join(''))+ '</tr></tbody></table></div></div>';
}
return {
enabled: enabled,
main: str,
next: nextDisabled,
prev: prevDisabled,
type: 'Grid'
};
};
picker.getMonthList = function(value, data){
var j, i, name, val, disabled, lis, prevDisabled, nextDisabled, classStr, classArray;
var o = data.options;
var size = o.size;
var max = o.maxS;
var min = o.minS;
var cols = o.cols || 4;
var currentValue = o.value.split('-');
var enabled = 0;
var rowNum = 0;
var str = '';
var action = data.type == 'month' ? 'changeInput' : 'setDayList' ;
var triggerValueValidation = (data.orig && ('validatevalue' in $.data(data.orig)));
var isPartial = action != 'changeInput';
value = value[0] - Math.floor((size - 1) / 2);
for(j = 0; j < size; j++){
if(j){
value++;
} else {
prevDisabled = picker.isInRange([value-1], max, min) ? {'data-action': 'setMonthList','value': value-1} : false;
}
if(j == size - 1){
nextDisabled = picker.isInRange([value+1], max, min) ? {'data-action': 'setMonthList','value': value+1} : false;
}
lis = [];
if( !picker.isInRange([value, '01'], max, min) && !picker.isInRange([value, '12'], max, min)){
disabled = ' disabled=""';
} else {
disabled = '';
}
if(o.minView >= 1){
disabled = ' disabled=""';
}
str += '<div class="month-list picker-list ws-index-'+ j +'"><div class="ws-picker-header">';
str += '<select data-action="setMonthList" class="year-select">'+ picker.createYearSelect(value, max, min).join('') +'</select> <button data-action="setYearList"'+disabled+' value="'+ value +'" tabindex="-1"><span>'+ value +'</span></button>';
str += '</div>';
for(i = 0; i < 12; i++){
val = curCfg.date.monthkeys[i+1];
name = getMonthNameHTML(i);
classArray = [];
if(!picker.isInRange([value, val], max, min) || (triggerValueValidation && $(data.orig).triggerHandler('validatevalue', [{value: value+'-'+val, valueAsDate: data.asDate(value+'-'+val), isPartial: isPartial && [value, val]}]))){
disabled = ' disabled=""';
} else {
disabled = '';
enabled++;
}
if(value == today[0] && today[1] == val){
classArray.push('this-value');
}
if(currentValue[0] == value && currentValue[1] == val){
classArray.push('checked-value');
}
classStr = (classArray.length) ? ' class="'+ (classArray.join(' ')) +'"' : '';
if(i && !(i % cols)){
rowNum++;
lis.push('</tr><tr class="ws-row-'+ rowNum +'">');
}
lis.push('<td class="ws-item-'+ i +'" role="presentation"><button data-id="month-'+ i +'" type="button"'+ disabled + classStr +' data-action="'+ action +'" value="'+value+'-'+val+'" tabindex="-1" role="gridcell" aria-label="'+ curCfg.date.monthNames[i] +'">'+name+'</button></td>');
}
str += '<div class="picker-grid"><table role="grid" aria-label="'+value+'"><tbody><tr class="ws-row-0">'+ (lis.join(''))+ '</tr></tbody></table></div></div>';
}
return {
enabled: enabled,
main: str,
prev: prevDisabled,
next: nextDisabled,
type: 'Grid'
};
};
picker.getDayList = function(value, data){
var j, i, k, day, nDay, disabled, prevDisabled, nextDisabled, yearNext, yearPrev, addTr, week, rowNum;
var lastMonth, curMonth, otherMonth, dateArray, monthName, fullMonthName, buttonStr, date2, classArray;
var o = data.options;
var size = o.size;
var max = o.maxS;
var min = o.minS;
var currentValue = o.value.split('T')[0].split('-');
var dateCfg = curCfg.date;
var str = [];
var date = new Date(value[0], value[1] - 1, 1);
var action = (data.type == 'datetime-local') ? 'setTimeList' : 'changeInput';
var triggerValueValidation = (data.orig && ('validatevalue' in $.data(data.orig)));
var isPartial = action != 'changeInput';
date.setMonth(date.getMonth() - Math.floor((size - 1) / 2));
yearNext = [ (value[0] * 1) + 1, value[1] ];
yearNext = picker.isInRange(yearNext, max, min) ? {'data-action': 'setDayList','value': yearNext.join('-')} : false;
yearPrev = [ (value[0] * 1) - 1, value[1] ];
yearPrev = picker.isInRange(yearPrev, max, min) ? {'data-action': 'setDayList','value': yearPrev.join('-')} : false;
for(j = 0; j < size; j++){
date.setDate(1);
lastMonth = date.getMonth();
rowNum = 0;
if(!j){
date2 = new Date(date.getTime());
date2.setDate(-1);
dateArray = getDateArray(date2);
prevDisabled = picker.isInRange(dateArray, max, min) ? {'data-action': 'setDayList','value': dateArray[0]+'-'+dateArray[1]} : false;
}
dateArray = getDateArray(date);
str.push('<div class="day-list picker-list ws-index-'+ j +'"><div class="ws-picker-header">');
monthName = ['<select data-action="setDayList" class="month-select" tabindex="0">'+ picker.createMonthSelect(dateArray, max, min).join('') +'</select>', '<select data-action="setDayList" class="year-select" tabindex="0">'+ picker.createYearSelect(dateArray[0], max, min, '-'+dateArray[1]).join('') +'</select>'];
if(curCfg.date.showMonthAfterYear){
monthName.reverse();
}
str.push( monthName.join(' ') );
fullMonthName = [dateCfg.monthNames[(dateArray[1] * 1) - 1], dateArray[0]];
if(dateCfg.showMonthAfterYear){
fullMonthName.reverse();
}
str.push(
'<button data-action="setMonthList"'+ (o.minView >= 2 ? ' disabled="" ' : '') +' value="'+ dateArray.date +'" tabindex="-1">'+ getMonthNameHTML((dateArray[1] * 1) - 1, dateArray[0]) +'</button>'
);
str.push('</div><div class="picker-grid"><table role="grid" aria-label="'+ fullMonthName.join(' ') +'"><thead><tr>');
str.push('<th class="week-header ws-week">'+ dateCfg.weekHeader +'</th>');
for(k = dateCfg.firstDay; k < dateCfg.dayNamesMin.length; k++){
str.push('<th class="day-'+ k +'"><abbr title="'+ dateCfg.dayNames[k] +'">'+ dateCfg.dayNamesMin[k] +'</abbr></th>');
}
k = dateCfg.firstDay;
while(k--){
str.push('<th class="day-'+ k +'"><abbr title="'+ dateCfg.dayNames[k] +'">'+ dateCfg.dayNamesMin[k] +'</abbr></th>');
}
str.push('</tr></thead><tbody><tr class="ws-row-0">');
week = picker.getWeek(date);
str.push('<td class="week-cell ws-week" role="gridcell" aria-disabled="true">'+ week +'</td>');
for (i = 0; i < 99; i++) {
addTr = (i && !(i % 7));
curMonth = date.getMonth();
otherMonth = lastMonth != curMonth;
day = date.getDay();
classArray = [];
if(addTr && otherMonth && rowNum >= 5){
str.push('</tr>');
break;
}
if(addTr){
rowNum++;
str.push('</tr><tr class="ws-row-'+ rowNum + ((otherMonth) ? ' other-month-row' : '')+'">');
week++;
if(week > 52){
week = picker.getWeek(date);
}
str.push('<td class="week-cell ws-week" role="gridcell" aria-disabled="true">'+ week +'</td>');
}
if(!i){
if(day != curCfg.date.firstDay){
nDay = day - curCfg.date.firstDay;
if(nDay < 0){
nDay += 7;
}
date.setDate(date.getDate() - nDay);
day = date.getDay();
curMonth = date.getMonth();
otherMonth = lastMonth != curMonth;
}
}
dateArray = getDateArray(date);
buttonStr = '<td role="presentation" class="day-'+ day +'"><button data-id="day-'+ date.getDate() +'" role="gridcell" data-action="'+action+'" value="'+ (dateArray.join('-')) +'" type="button"';
if(otherMonth){
classArray.push('othermonth');
} else {
classArray.push('day-'+date.getDate());
}
if(dateArray[0] == today[0] && today[1] == dateArray[1] && today[2] == dateArray[2]){
classArray.push('this-value');
}
if(currentValue[0] == dateArray[0] && dateArray[1] == currentValue[1] && dateArray[2] == currentValue[2]){
classArray.push('checked-value');
}
if(classArray.length){
buttonStr += ' class="'+ classArray.join(' ') +'"';
}
if(!picker.isInRange(dateArray, max, min) || (triggerValueValidation && $(data.orig).triggerHandler('validatevalue', [{value: dateArray.join('-'), valueAsDate: date, isPartial: isPartial && dateArray}]))){
buttonStr += ' disabled=""';
}
str.push(buttonStr+' tabindex="-1">'+ date.getDate() +'</button></td>');
date.setDate(date.getDate() + 1);
}
str.push('</tbody></table></div></div>');
if(j == size - 1){
dateArray = getDateArray(date);
dateArray[2] = 1;
nextDisabled = picker.isInRange(dateArray, max, min) ? {'data-action': 'setDayList','value': dateArray.date} : false;
}
}
return {
enabled: 9,
main: str.join(''),
prev: prevDisabled,
next: nextDisabled,
yearPrev: yearPrev,
yearNext: yearNext,
type: 'Grid'
};
};
// var createDatimeValue =
picker.getTimeList = function(value, data){
var label, tmpValue, iVal, hVal, valPrefix;
var str = '<div class="time-list picker-list ws-index-0">';
var i = 0;
var rowNum = 0;
var len = 23;
var attrs = {
min: $.prop(data.orig, 'min'),
max: $.prop(data.orig, 'max'),
step: $.prop(data.orig, 'step')
};
var triggerValueValidation = (data.orig && ('validatevalue' in $.data(data.orig)));
var gridLabel = '';
if(data.type == 'time'){
label = '<button type="button" disabled="">'+ $.trim($(data.orig).jProp('labels').text() || '').replace(/[\:\*]/g, '')+'</button>';
} else {
tmpValue = value[2].split('T');
value[2] = tmpValue[0];
if(tmpValue[1]){
value[3] = tmpValue[1];
}
gridLabel = ' aria-label="'+ value[2] +'. '+ (curCfg.date.monthNames[(value[1] * 1) - 1]) +' '+ value[0] +'"';
label = getMonthNameHTML((value[1] * 1) - 1, value[0], value[2] +'. ');
label = '<button tabindex="-1" data-action="setDayList" value="'+value[0]+'-'+value[1]+'-'+value[2]+'" type="button">'+label+'</button>';
valPrefix = value[0] +'-'+value[1]+'-'+value[2]+'T';
}
str += '<div class="ws-picker-header">'+label+'</div>';
str += '<div class="picker-grid"><table role="grid"'+ gridLabel +'><tbody><tr>';
for(; i <= len; i++){
iVal = moduleOpts.addZero(''+i) +':00';
hVal = valPrefix ?
valPrefix+iVal :
iVal
;
if(i && !(i % 4)){
rowNum++;
str += '</tr><tr class="ws-row-'+ rowNum +'">';
}
str += '<td role="presentation"><button role="gridcell" data-action="changeInput" value="'+ hVal +'" type="button" tabindex="-1"';
if(!data.isValid(hVal, attrs) || (triggerValueValidation && $(data.orig).triggerHandler('validatevalue', [{value: hVal, valueAsDate: data.asDate(hVal), partial: false}]))){
str += ' disabled=""';
}
if(value == iVal){
str += ' class="checked-value"';
}
str += '>'+ webshims._format.time(iVal) +'</button></td>';
}
str += '</tr></tbody></table></div></div>';
return {
enabled: 9,
main: str,
prev: false,
next: false,
type: 'Grid'
};
};
picker.isInRange = function(values, max, min){
var i;
var ret = true;
for(i = 0; i < values.length; i++){
if(min[i] && min[i] > values[i]){
ret = false;
break;
} else if( !(min[i] && min[i] == values[i]) ){
break;
}
}
if(ret){
for(i = 0; i < values.length; i++){
if((max[i] && max[i] < values[i])){
ret = false;
break;
} else if( !(max[i] && max[i] == values[i]) ){
break;
}
}
}
return ret;
};
picker.createMonthSelect = function(value, max, min, monthNames){
if(!monthNames){
monthNames = curCfg.date.monthNames;
}
var selected;
var i = 0;
var options = [];
var tempVal = value[1]-1;
for(; i < monthNames.length; i++){
selected = tempVal == i ? ' selected=""' : '';
if(selected || picker.isInRange([value[0], i+1], max, min)){
options.push('<option value="'+ value[0]+'-'+moduleOpts.addZero(i+1) + '"'+selected+'>'+ monthNames[i] +'</option>');
}
}
return options;
};
(function(){
var retNames = function(name){
return 'get'+name+'List';
};
var retSetNames = function(name){
return 'set'+name+'List';
};
var stops = {
date: 'Day',
week: 'Day',
month: 'Month',
'datetime-local': 'Time',
time: 'Time'
};
var setDirButtons = function(content, popover, dir){
if(content[dir]){
//set content and idl attribute (content for css + idl for IE8-)
popover[dir+'Element']
.attr(content[dir])
.prop({disabled: false})
.prop(content[dir])
;
} else {
popover[dir+'Element']
.removeAttr('data-action')
.prop({disabled: true})
;
}
};
$.each({'setYearList' : ['Year', 'Month', 'Day', 'Time'], 'setMonthList': ['Month', 'Day', 'Time'], 'setDayList': ['Day', 'Time'], 'setTimeList': ['Time']}, function(setName, names){
var getNames = names.map(retNames);
var setNames = names.map(retSetNames);
actions[setName] = function(val, popover, data, startAt){
val = ''+val;
var o = data.options;
var values = val.split('-');
if(!startAt){
startAt = 0;
}
$.each(getNames, function(i, item){
if(i >= startAt){
var content = picker[item](values, data);
if( values.length < 2 || content.enabled > 1 || content.prev || content.next || stops[data.type] === names[i]){
popover.element
.attr({'data-currentview': setNames[i]})
.addClass('ws-size-'+o.size)
.data('pickercontent', {
data: data,
content: content,
values: values
})
;
popover.bodyElement.html(content.main);
setDirButtons(content, popover, 'prev');
setDirButtons(content, popover, 'next');
setDirButtons(content, popover, 'yearPrev');
setDirButtons(content, popover, 'yearNext');
$(o.orig).trigger('pickerchange');
if(webshims[content.type]){
new webshims[content.type](popover.bodyElement.children(), popover, content);
}
popover.element
.filter('[data-vertical="bottom"]')
.triggerHandler('pospopover')
;
return false;
}
}
});
};
});
})();
picker.showPickerContent = function(data, popover){
var options = data.options;
var init = data._popoverinit;
data._popoverinit = true;
if(!init){
picker.commonInit(data, popover);
picker.commonDateInit(data, popover);
}
popover.element.triggerHandler('updatepickercontent');
if(!init || options.restartView) {
actions.setYearList( options.defValue || options.value, popover, data, options.startView);
} else {
actions[popover.element.attr('data-currentview') || 'setYearList']( options.defValue || options.value, popover, data, 0);
}
data._popoverinit = true;
};
picker.commonDateInit = function(data, popover){
if(data._commonDateInit){return;}
data._commonDateInit = true;
var o = data.options;
var actionfn = function(e){
if(!$(this).hasClass('othermonth') || $(this).css('cursor') == 'pointer'){
popover.actionFn({
'data-action': $.attr(this, 'data-action'),
value: $(this).val() || $.attr(this, 'value')
});
}
return false;
};
var id = new Date().getTime();
var generateList = function(o, max, min){
var options = [];
var label = '';
var labelId = '';
o.options = data.getOptions() || {};
$('div.ws-options', popover.contentElement).remove();
$.each(o.options[0], function(val, label){
var disabled = picker.isInRange(val.split('-'), o.maxS, o.minS) ?
'' :
' disabled="" '
;
if(label){
label = ' <span class="ws-label">'+ label +'</span>';
}
options.push('<li role="presentation"><button value="'+ val +'" '+disabled+' data-action="changeInput" tabindex="-1" role="option"><span class="ws-value">'+ data.formatValue(val, false) +'</span>'+ label +'</button></li>');
});
if(options.length){
id++;
if(o.options[1]){
labelId = 'datalist-'+id;
label = '<h5 id="'+labelId+'">'+ o.options[1] +'</h5>';
labelId = ' aria-labelledbyid="'+ labelId +'" ';
}
new webshims.ListBox($('<div class="ws-options">'+label+'<ul role="listbox" '+ labelId +'>'+ options.join('') +'</div>').insertAfter(popover.bodyElement)[0], popover, {noFocus: true});
}
};
var updateContent = function(){
var tmpMinMax;
if(popover.isDirty){
popover.isDirty = false;
tmpMinMax = o.max.split('T');
o.maxS = tmpMinMax[0].split('-');
if(tmpMinMax[1]){
o.maxS.push(tmpMinMax[1]);
}
tmpMinMax = o.min.split('T');
o.minS = tmpMinMax[0].split('-');
if(tmpMinMax[1]){
o.minS.push(tmpMinMax[1]);
}
$('button', popover.buttonRow).each(function(){
var text;
if($(this).hasClass('ws-empty')){
text = curCfg.date.clear;
if(!text){
text = formcfg[''].date.clear || 'clear';
webshims.warn("could not get clear text from form cfg");
}
} else if($(this).hasClass('ws-current')){
text = (curCfg[data.type] || {}).currentText;
if(!text){
text = (formcfg[''][[data.type]] || {}).currentText || (curCfg.date || {}).currentText || 'current';
webshims.warn("could not get currentText from form cfg for "+data.type);
}
if(today[data.type] && data.type != 'time'){
$.prop(this, 'disabled', (!picker.isInRange(today[data.type].split('-'), o.maxS, o.minS) || !!$(data.orig).triggerHandler('validatevalue', [{value: today[data.type], valueAsDate: new Date(), isPartial: false}])));
}
}
if(text){
$(this).text(text).attr({'aria-label': text});
}
});
popover.nextElement
.attr({'aria-label': curCfg.date.nextText})
;
popover.prevElement
.attr({'aria-label': curCfg.date.prevText})
;
popover.yearNextElement
.attr({'aria-label': curCfg.date.nextText})
;
popover.yearPrevElement
.attr({'aria-label': curCfg.date.prevText})
;
popover.contentElement.attr({
dir: curCfg.date.isRTL ? 'rtl' : 'ltr',
lang: webshims.formcfg.__activeName
});
generateList(o, o.maxS, o.minS);
if(popover.isVisible){
picker.showPickerContent(data, popover);
}
}
$('button.ws-empty', popover.buttonRow).prop('disabled', $.prop(data.orig, 'required'));
popover.isDirty = false;
};
if(data.type == 'time'){
o.minView = 3;
o.startView = 3;
}
if(!o.minView){
o.minView = 0;
}
if(o.startView < o.minView){
o.startView = o.minView;
webshims.warn("wrong config for minView/startView.");
}
if(!o.size){
o.size = 1;
}
popover.actionFn = function(obj){
var changeChangeBehavior;
if(actions[obj['data-action']]){
if(obj['data-action'] == 'changeInput' && o.inlinePicker && o.updateOnInput){
data._handledValue = true;
if(o.size > 1){
changeChangeBehavior = $('button[value="'+obj.value+'"]', popover.bodyElement);
if(changeChangeBehavior.filter(':not(.othermonth)').length){
$('button.checked-value', popover.bodyElement).removeClass('checked-value');
changeChangeBehavior.addClass('checked-value').trigger('focus');
o.updateOnInput = false;
} else {
changeChangeBehavior = false;
}
}
}
actions[obj['data-action']](obj.value, popover, data, 0);
if(data._handledValue){
delete data._handledValue;
if(changeChangeBehavior){
o.updateOnInput = true;
}
}
} else {
webshims.warn('no action for '+ obj['data-action']);
}
};
popover.contentElement.html('<div class="prev-controls ws-picker-controls"><button class="ws-super-prev ws-year-btn" tabindex="0" type="button"></button><button class="ws-prev" tabindex="0" type="button"></button></div> <div class="next-controls ws-picker-controls"><button class="ws-next" tabindex="0" type="button"></button><button class="ws-super-next ws-year-btn" tabindex="0" type="button"></button></div><div class="ws-picker-body"></div><div class="ws-button-row"><button type="button" class="ws-current" data-action="changeInput" value="'+today[data.type]+'" tabindex="0"></button> <button type="button" data-action="changeInput" value="" class="ws-empty" tabindex="0"></button></div>');
popover.nextElement = $('button.ws-next', popover.contentElement);
popover.prevElement = $('button.ws-prev', popover.contentElement);
popover.yearNextElement = $('button.ws-super-next', popover.contentElement);
popover.yearPrevElement = $('button.ws-super-prev', popover.contentElement);
popover.bodyElement = $('div.ws-picker-body', popover.contentElement);
popover.buttonRow = $('div.ws-button-row', popover.contentElement);
popover.element.on('updatepickercontent', updateContent);
popover.contentElement
.wsTouchClick('button[data-action]', actionfn)
.on('change', 'select[data-action]', actionfn)
;
$(o.orig).on('input', function(){
var currentView;
if(o.updateOnInput && popover.isVisible && o.value && (currentView = popover.element.attr('data-currentview'))){
actions[currentView]( data.options.value , popover, data, 0);
}
});
$(document).onTrigger('wslocalechange', data._propertyChange);
if(o.updateOnInput == null && (o.inlinePicker || o.noChangeDismiss)){
o.updateOnInput = true;
}
if(o.inlinePicker){
popover.element.attr('data-class', $.prop(data.orig, 'className'));
popover.element.attr('data-id', $.prop(data.orig, 'id'));
}
$(o.orig).trigger('pickercreated');
};
});
| zhengyongbo/cdnjs | ajax/libs/webshim/1.15.6/dev/shims/forms-picker.js | JavaScript | mit | 50,169 |
/** @preserve jsPDF 0.9.0rc2 ( ${buildDate} ${commitID} )
Copyright (c) 2010-2012 James Hall, james@snapshotmedia.co.uk, https://github.com/MrRio/jsPDF
Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
MIT license.
*/
/*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
* ====================================================================
*/
/**
Creates new jsPDF document object instance
@class
@param orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")
@param unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"
@param format One of 'a0', 'a1', 'a2', 'a3', 'a4' (Default) etc to 'a10', 'b0' to 'b10', 'c0' to 'c10', 'letter', 'government-letter', 'legal', 'junior-legal', 'ledger' or 'tabloid'
@returns {jsPDF}
@name jsPDF
*/
var jsPDF = (function () {
'use strict';
/*jslint browser:true, plusplus: true, bitwise: true, nomen: true */
/*global document: false, btoa, atob, zpipe, Uint8Array, ArrayBuffer, Blob, saveAs, adler32cs, Deflater */
// this will run on <=IE9, possibly some niche browsers
// new webkit-based, FireFox, IE10 already have native version of this.
if (typeof btoa === 'undefined') {
window.btoa = function (data) {
// DO NOT ADD UTF8 ENCODING CODE HERE!!!!
// UTF8 encoding encodes bytes over char code 128
// and, essentially, turns an 8-bit binary streams
// (that base64 can deal with) into 7-bit binary streams.
// (by default server does not know that and does not recode the data back to 8bit)
// You destroy your data.
// binary streams like jpeg image data etc, while stored in JavaScript strings,
// (which are 16bit arrays) are in 8bit format already.
// You do NOT need to char-encode that before base64 encoding.
// if you, by act of fate
// have string which has individual characters with code
// above 255 (pure unicode chars), encode that BEFORE you base64 here.
// you can use absolutely any approch there, as long as in the end,
// base64 gets an 8bit (char codes 0 - 255) stream.
// when you get it on the server after un-base64, you must
// UNencode it too, to get back to 16, 32bit or whatever original bin stream.
// Note, Yes, JavaScript strings are, in most cases UCS-2 -
// 16-bit character arrays. This does not mean, however,
// that you always have to UTF8 it before base64.
// it means that if you have actual characters anywhere in
// that string that have char code above 255, you need to
// recode *entire* string from 16-bit (or 32bit) to 8-bit array.
// You can do binary split to UTF16 (BE or LE)
// you can do utf8, you can split the thing by hand and prepend BOM to it,
// but whatever you do, make sure you mirror the opposite on
// the server. If server does not expect to post-process un-base64
// 8-bit binary stream, think very very hard about messing around with encoding.
// so, long story short:
// DO NOT ADD UTF8 ENCODING CODE HERE!!!!
/* @preserve
====================================================================
base64 encoder
MIT, GPL
version: 1109.2015
discuss at: http://phpjs.org/functions/base64_encode
+ original by: Tyler Akins (http://rumkin.com)
+ improved by: Bayron Guevara
+ improved by: Thunder.m
+ improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
+ bugfixed by: Pellentesque Malesuada
+ improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
+ improved by: Rafal Kukawski (http://kukawski.pl)
+ Daniel Dotsenko, Willow Systems Corp, willow-systems.com
====================================================================
*/
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
b64a = b64.split(''),
o1,
o2,
o3,
h1,
h2,
h3,
h4,
bits,
i = 0,
ac = 0,
enc = "",
tmp_arr = [],
r;
do { // pack three octets into four hexets
o1 = data.charCodeAt(i++);
o2 = data.charCodeAt(i++);
o3 = data.charCodeAt(i++);
bits = o1 << 16 | o2 << 8 | o3;
h1 = bits >> 18 & 0x3f;
h2 = bits >> 12 & 0x3f;
h3 = bits >> 6 & 0x3f;
h4 = bits & 0x3f;
// use hexets to index into b64, and append result to encoded string
tmp_arr[ac++] = b64a[h1] + b64a[h2] + b64a[h3] + b64a[h4];
} while (i < data.length);
enc = tmp_arr.join('');
r = data.length % 3;
return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
// end of base64 encoder MIT, GPL
};
}
if (typeof atob === 'undefined') {
window.atob = function (data) {
// http://kevin.vanzonneveld.net
// + original by: Tyler Akins (http://rumkin.com)
// + improved by: Thunder.m
// + input by: Aman Gupta
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + bugfixed by: Onno Marsman
// + bugfixed by: Pellentesque Malesuada
// + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// + input by: Brett Zamir (http://brett-zamir.me)
// + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
// * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
// * returns 1: 'Kevin van Zonneveld'
// mozilla has this native
// - but breaks in 2.0.0.12!
//if (typeof this.window['atob'] == 'function') {
// return atob(data);
//}
var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
o1,
o2,
o3,
h1,
h2,
h3,
h4,
bits,
i = 0,
ac = 0,
dec = "",
tmp_arr = [];
if (!data) {
return data;
}
data += '';
do { // unpack four hexets into three octets using index points in b64
h1 = b64.indexOf(data.charAt(i++));
h2 = b64.indexOf(data.charAt(i++));
h3 = b64.indexOf(data.charAt(i++));
h4 = b64.indexOf(data.charAt(i++));
bits = h1 << 18 | h2 << 12 | h3 << 6 | h4;
o1 = bits >> 16 & 0xff;
o2 = bits >> 8 & 0xff;
o3 = bits & 0xff;
if (h3 === 64) {
tmp_arr[ac++] = String.fromCharCode(o1);
} else if (h4 === 64) {
tmp_arr[ac++] = String.fromCharCode(o1, o2);
} else {
tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
}
} while (i < data.length);
dec = tmp_arr.join('');
return dec;
};
}
var getObjectLength = typeof Object.keys === 'function' ?
function (object) {
return Object.keys(object).length;
} :
function (object) {
var i = 0, e;
for (e in object) {
if (object.hasOwnProperty(e)) {
i++;
}
}
return i;
},
/**
PubSub implementation
@class
@name PubSub
*/
PubSub = function (context) {
/** @preserve
-----------------------------------------------------------------------------------------------
JavaScript PubSub library
2012 (c) ddotsenko@willowsystems.com
based on Peter Higgins (dante@dojotoolkit.org)
Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.
Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
http://dojofoundation.org/license for more information.
-----------------------------------------------------------------------------------------------
*/
/**
@private
@fieldOf PubSub
*/
this.topics = {};
/**
Stores what will be `this` within the callback functions.
@private
@fieldOf PubSub#
*/
this.context = context;
/**
Allows caller to emit an event and pass arguments to event listeners.
@public
@function
@param topic {String} Name of the channel on which to voice this event
@param args Any number of arguments you want to pass to the listeners of this event.
@methodOf PubSub#
@name publish
*/
this.publish = function (topic, args) {
if (this.topics[topic]) {
var currentTopic = this.topics[topic],
toremove = [],
fn,
i,
l,
pair,
emptyFunc = function () {};
args = Array.prototype.slice.call(arguments, 1);
for (i = 0, l = currentTopic.length; i < l; i++) {
pair = currentTopic[i]; // this is a [function, once_flag] array
fn = pair[0];
if (pair[1]) { /* 'run once' flag set */
pair[0] = emptyFunc;
toremove.push(i);
}
fn.apply(this.context, args);
}
for (i = 0, l = toremove.length; i < l; i++) {
currentTopic.splice(toremove[i], 1);
}
}
};
/**
Allows listener code to subscribe to channel and be called when data is available
@public
@function
@param topic {String} Name of the channel on which to voice this event
@param callback {Function} Executable (function pointer) that will be ran when event is voiced on this channel.
@param once {Boolean} (optional. False by default) Flag indicating if the function is to be triggered only once.
@returns {Object} A token object that cen be used for unsubscribing.
@methodOf PubSub#
@name subscribe
*/
this.subscribe = function (topic, callback, once) {
if (!this.topics[topic]) {
this.topics[topic] = [[callback, once]];
} else {
this.topics[topic].push([callback, once]);
}
return {
"topic": topic,
"callback": callback
};
};
/**
Allows listener code to unsubscribe from a channel
@public
@function
@param token {Object} A token object that was returned by `subscribe` method
@methodOf PubSub#
@name unsubscribe
*/
this.unsubscribe = function (token) {
if (this.topics[token.topic]) {
var currentTopic = this.topics[token.topic], i, l;
for (i = 0, l = currentTopic.length; i < l; i++) {
if (currentTopic[i][0] === token.callback) {
currentTopic.splice(i, 1);
}
}
}
};
};
/**
@constructor
@private
*/
function jsPDF(orientation, unit, format, compressPdf) { /** String orientation, String unit, String format, Boolean compressed */
// Default parameter values
if (typeof orientation === 'undefined') {
orientation = 'p';
} else {
orientation = orientation.toString().toLowerCase();
}
if (typeof unit === 'undefined') { unit = 'mm'; }
if (typeof format === 'undefined') { format = 'a4'; }
if (typeof compressPdf === 'undefined' && typeof zpipe === 'undefined') { compressPdf = false; }
var format_as_string = format.toString().toLowerCase(),
version = '0.9.0rc2',
content = [],
content_length = 0,
compress = compressPdf,
pdfVersion = '1.3', // PDF Version
pageFormats = { // Size in pt of various paper formats
'a0': [2383.94, 3370.39],
'a1': [1683.78, 2383.94],
'a2': [1190.55, 1683.78],
'a3': [841.89, 1190.55],
'a4': [595.28, 841.89],
'a5': [419.53, 595.28],
'a6': [297.64, 419.53],
'a7': [209.76, 297.64],
'a8': [147.4 , 209.76],
'a9': [104.88, 147.4],
'a10': [73.7, 104.88],
'b0': [2834.65, 4008.19],
'b1': [2004.09, 2834.65],
'b2': [1417.32, 2004.09],
'b3': [1000.63, 1417.32],
'b4': [708.66, 1000.63],
'b5': [498.9, 708.66],
'b6': [354.33, 498.9],
'b7': [249.45, 354.33],
'b8': [175.75, 249.45],
'b9': [124.72, 175.75],
'b10': [87.87, 124.72],
'c0': [2599.37, 3676.54],
'c1': [1836.85, 2599.37],
'c2': [1298.27, 1836.85],
'c3': [918.43, 1298.27],
'c4': [649.13, 918.43],
'c5': [459.21, 649.13],
'c6': [323.15, 459.21],
'c7': [229.61, 323.15],
'c8': [161.57, 229.61],
'c9': [113.39, 161.57],
'c10': [79.37, 113.39],
'letter': [612, 792],
'government-letter': [576, 756],
'legal': [612, 1008],
'junior-legal': [576, 360],
'ledger': [1224, 792],
'tabloid': [792, 1224]
},
textColor = '0 g',
drawColor = '0 G',
page = 0,
pages = [],
objectNumber = 2, // 'n' Current object number
outToPages = false, // switches where out() prints. outToPages true = push to pages obj. outToPages false = doc builder content
offsets = [], // List of offsets. Activated and reset by buildDocument(). Pupulated by various calls buildDocument makes.
fonts = {}, // collection of font objects, where key is fontKey - a dynamically created label for a given font.
fontmap = {}, // mapping structure fontName > fontStyle > font key - performance layer. See addFont()
activeFontSize = 16,
activeFontKey, // will be string representing the KEY of the font as combination of fontName + fontStyle
lineWidth = 0.200025, // 2mm
lineHeightProportion = 1.15,
pageHeight,
pageWidth,
k, // Scale factor
documentProperties = {'title': '', 'subject': '', 'author': '', 'keywords': '', 'creator': ''},
lineCapID = 0,
lineJoinID = 0,
API = {},
events = new PubSub(API),
tmp,
plugin,
/////////////////////
// Private functions
/////////////////////
// simplified (speedier) replacement for sprintf's %.2f conversion
f2 = function (number) {
return number.toFixed(2);
},
// simplified (speedier) replacement for sprintf's %.3f conversion
f3 = function (number) {
return number.toFixed(3);
},
// simplified (speedier) replacement for sprintf's %02d
padd2 = function (number) {
var n = (number).toFixed(0);
if (number < 10) {
return '0' + n;
} else {
return n;
}
},
// simplified (speedier) replacement for sprintf's %02d
padd10 = function (number) {
var n = (number).toFixed(0);
if (n.length < 10) {
return new Array( 11 - n.length ).join('0') + n;
} else {
return n;
}
},
out = function (string) {
if (outToPages) { /* set by beginPage */
pages[page].push(string);
} else {
content.push(string);
content_length += string.length + 1; // +1 is for '\n' that will be used to join contents of content
}
},
newObject = function () {
// Begin a new object
objectNumber++;
offsets[objectNumber] = content_length;
out(objectNumber + ' 0 obj');
return objectNumber;
},
putStream = function (str) {
out('stream');
out(str);
out('endstream');
},
wPt,
hPt,
kids,
i,
putPages = function () {
wPt = pageWidth * k;
hPt = pageHeight * k;
// outToPages = false as set in endDocument(). out() writes to content.
var n, p, arr, uint, i, deflater, adler32;
for (n = 1; n <= page; n++) {
newObject();
out('<</Type /Page');
out('/Parent 1 0 R');
out('/Resources 2 0 R');
out('/Contents ' + (objectNumber + 1) + ' 0 R>>');
out('endobj');
// Page content
p = pages[n].join('\n');
newObject();
if (compress) {
arr = [];
for (i = 0; i < p.length; ++i) {
arr[i] = p.charCodeAt(i);
}
adler32 = adler32cs.from(p);
deflater = new Deflater(6);
deflater.append(new Uint8Array(arr));
p = deflater.flush();
arr = [new Uint8Array([120, 156]), new Uint8Array(p),
new Uint8Array([adler32 & 0xFF, (adler32 >> 8) & 0xFF, (adler32 >> 16) & 0xFF, (adler32 >> 24) & 0xFF])];
p = '';
for (i in arr) {
if (arr.hasOwnProperty(i)) {
p += String.fromCharCode.apply(null, arr[i]);
}
}
out('<</Length ' + p.length + ' /Filter [/FlateDecode]>>');
} else {
out('<</Length ' + p.length + '>>');
}
putStream(p);
out('endobj');
}
offsets[1] = content_length;
out('1 0 obj');
out('<</Type /Pages');
kids = '/Kids [';
for (i = 0; i < page; i++) {
kids += (3 + 2 * i) + ' 0 R ';
}
out(kids + ']');
out('/Count ' + page);
out('/MediaBox [0 0 ' + f2(wPt) + ' ' + f2(hPt) + ']');
out('>>');
out('endobj');
},
putFont = function (font) {
font.objectNumber = newObject();
out('<</BaseFont/' + font.PostScriptName + '/Type/Font');
if (typeof font.encoding === 'string') {
out('/Encoding/' + font.encoding);
}
out('/Subtype/Type1>>');
out('endobj');
},
putFonts = function () {
var fontKey;
for (fontKey in fonts) {
if (fonts.hasOwnProperty(fontKey)) {
putFont(fonts[fontKey]);
}
}
},
putXobjectDict = function () {
// Loop through images, or other data objects
events.publish('putXobjectDict');
},
putResourceDictionary = function () {
out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
out('/Font <<');
// Do this for each font, the '1' bit is the index of the font
var fontKey;
for (fontKey in fonts) {
if (fonts.hasOwnProperty(fontKey)) {
out('/' + fontKey + ' ' + fonts[fontKey].objectNumber + ' 0 R');
}
}
out('>>');
out('/XObject <<');
putXobjectDict();
out('>>');
},
putResources = function () {
putFonts();
events.publish('putResources');
// Resource dictionary
offsets[2] = content_length;
out('2 0 obj');
out('<<');
putResourceDictionary();
out('>>');
out('endobj');
events.publish('postPutResources');
},
addToFontDictionary = function (fontKey, fontName, fontStyle) {
// this is mapping structure for quick font key lookup.
// returns the KEY of the font (ex: "F1") for a given pair of font name and type (ex: "Arial". "Italic")
var undef;
if (fontmap[fontName] === undef) {
fontmap[fontName] = {}; // fontStyle is a var interpreted and converted to appropriate string. don't wrap in quotes.
}
fontmap[fontName][fontStyle] = fontKey;
},
/**
FontObject describes a particular font as member of an instnace of jsPDF
It's a collection of properties like 'id' (to be used in PDF stream),
'fontName' (font's family name), 'fontStyle' (font's style variant label)
@class
@public
@property id {String} PDF-document-instance-specific label assinged to the font.
@property PostScriptName {String} PDF specification full name for the font
@property encoding {Object} Encoding_name-to-Font_metrics_object mapping.
@name FontObject
*/
FontObject = {},
addFont = function (PostScriptName, fontName, fontStyle, encoding) {
var fontKey = 'F' + (getObjectLength(fonts) + 1).toString(10),
// This is FontObject
font = fonts[fontKey] = {
'id': fontKey,
// , 'objectNumber': will be set by putFont()
'PostScriptName': PostScriptName,
'fontName': fontName,
'fontStyle': fontStyle,
'encoding': encoding,
'metadata': {}
};
addToFontDictionary(fontKey, fontName, fontStyle);
events.publish('addFont', font);
return fontKey;
},
addFonts = function () {
var HELVETICA = "helvetica",
TIMES = "times",
COURIER = "courier",
NORMAL = "normal",
BOLD = "bold",
ITALIC = "italic",
BOLD_ITALIC = "bolditalic",
encoding = 'StandardEncoding',
standardFonts = [
['Helvetica', HELVETICA, NORMAL],
['Helvetica-Bold', HELVETICA, BOLD],
['Helvetica-Oblique', HELVETICA, ITALIC],
['Helvetica-BoldOblique', HELVETICA, BOLD_ITALIC],
['Courier', COURIER, NORMAL],
['Courier-Bold', COURIER, BOLD],
['Courier-Oblique', COURIER, ITALIC],
['Courier-BoldOblique', COURIER, BOLD_ITALIC],
['Times-Roman', TIMES, NORMAL],
['Times-Bold', TIMES, BOLD],
['Times-Italic', TIMES, ITALIC],
['Times-BoldItalic', TIMES, BOLD_ITALIC]
],
i,
l,
fontKey,
parts;
for (i = 0, l = standardFonts.length; i < l; i++) {
fontKey = addFont(
standardFonts[i][0],
standardFonts[i][1],
standardFonts[i][2],
encoding
);
// adding aliases for standard fonts, this time matching the capitalization
parts = standardFonts[i][0].split('-');
addToFontDictionary(fontKey, parts[0], parts[1] || '');
}
events.publish('addFonts', {'fonts': fonts, 'dictionary': fontmap});
},
/**
@public
@function
@param text {String}
@param flags {Object} Encoding flags.
@returns {String} Encoded string
*/
to8bitStream = function (text, flags) {
/* PDF 1.3 spec:
"For text strings encoded in Unicode, the first two bytes must be 254 followed by
255, representing the Unicode byte order marker, U+FEFF. (This sequence conflicts
with the PDFDocEncoding character sequence thorn ydieresis, which is unlikely
to be a meaningful beginning of a word or phrase.) The remainder of the
string consists of Unicode character codes, according to the UTF-16 encoding
specified in the Unicode standard, version 2.0. Commonly used Unicode values
are represented as 2 bytes per character, with the high-order byte appearing first
in the string."
In other words, if there are chars in a string with char code above 255, we
recode the string to UCS2 BE - string doubles in length and BOM is prepended.
HOWEVER!
Actual *content* (body) text (as opposed to strings used in document properties etc)
does NOT expect BOM. There, it is treated as a literal GID (Glyph ID)
Because of Adobe's focus on "you subset your fonts!" you are not supposed to have
a font that maps directly Unicode (UCS2 / UTF16BE) code to font GID, but you could
fudge it with "Identity-H" encoding and custom CIDtoGID map that mimics Unicode
code page. There, however, all characters in the stream are treated as GIDs,
including BOM, which is the reason we need to skip BOM in content text (i.e. that
that is tied to a font).
To signal this "special" PDFEscape / to8bitStream handling mode,
API.text() function sets (unless you overwrite it with manual values
given to API.text(.., flags) )
flags.autoencode = true
flags.noBOM = true
*/
/*
`flags` properties relied upon:
.sourceEncoding = string with encoding label.
"Unicode" by default. = encoding of the incoming text.
pass some non-existing encoding name
(ex: 'Do not touch my strings! I know what I am doing.')
to make encoding code skip the encoding step.
.outputEncoding = Either valid PDF encoding name
(must be supported by jsPDF font metrics, otherwise no encoding)
or a JS object, where key = sourceCharCode, value = outputCharCode
missing keys will be treated as: sourceCharCode === outputCharCode
.noBOM
See comment higher above for explanation for why this is important
.autoencode
See comment higher above for explanation for why this is important
*/
var i, l, undef, sourceEncoding, encodingBlock, outputEncoding, newtext, isUnicode, ch, bch;
if (flags === undef) {
flags = {};
}
sourceEncoding = flags.sourceEncoding ? sourceEncoding : 'Unicode';
outputEncoding = flags.outputEncoding;
// This 'encoding' section relies on font metrics format
// attached to font objects by, among others,
// "Willow Systems' standard_font_metrics plugin"
// see jspdf.plugin.standard_font_metrics.js for format
// of the font.metadata.encoding Object.
// It should be something like
// .encoding = {'codePages':['WinANSI....'], 'WinANSI...':{code:code, ...}}
// .widths = {0:width, code:width, ..., 'fof':divisor}
// .kerning = {code:{previous_char_code:shift, ..., 'fof':-divisor},...}
if ((flags.autoencode || outputEncoding) &&
fonts[activeFontKey].metadata &&
fonts[activeFontKey].metadata[sourceEncoding] &&
fonts[activeFontKey].metadata[sourceEncoding].encoding
) {
encodingBlock = fonts[activeFontKey].metadata[sourceEncoding].encoding;
// each font has default encoding. Some have it clearly defined.
if (!outputEncoding && fonts[activeFontKey].encoding) {
outputEncoding = fonts[activeFontKey].encoding;
}
// Hmmm, the above did not work? Let's try again, in different place.
if (!outputEncoding && encodingBlock.codePages) {
outputEncoding = encodingBlock.codePages[0]; // let's say, first one is the default
}
if (typeof outputEncoding === 'string') {
outputEncoding = encodingBlock[outputEncoding];
}
// we want output encoding to be a JS Object, where
// key = sourceEncoding's character code and
// value = outputEncoding's character code.
if (outputEncoding) {
isUnicode = false;
newtext = [];
for (i = 0, l = text.length; i < l; i++) {
ch = outputEncoding[text.charCodeAt(i)];
if (ch) {
newtext.push(
String.fromCharCode(ch)
);
} else {
newtext.push(
text[i]
);
}
// since we are looping over chars anyway, might as well
// check for residual unicodeness
if (newtext[i].charCodeAt(0) >> 8) { /* more than 255 */
isUnicode = true;
}
}
text = newtext.join('');
}
}
i = text.length;
// isUnicode may be set to false above. Hence the triple-equal to undefined
while (isUnicode === undef && i !== 0) {
if (text.charCodeAt(i - 1) >> 8) { /* more than 255 */
isUnicode = true;
}
i--;
}
if (!isUnicode) {
return text;
} else {
newtext = flags.noBOM ? [] : [254, 255];
for (i = 0, l = text.length; i < l; i++) {
ch = text.charCodeAt(i);
bch = ch >> 8; // divide by 256
if (bch >> 8) { /* something left after dividing by 256 second time */
throw new Error("Character at position " + i.toString(10) + " of string '" + text + "' exceeds 16bits. Cannot be encoded into UCS-2 BE");
}
newtext.push(bch);
newtext.push(ch - (bch << 8));
}
return String.fromCharCode.apply(undef, newtext);
}
},
// Replace '/', '(', and ')' with pdf-safe versions
pdfEscape = function (text, flags) {
// doing to8bitStream does NOT make this PDF display unicode text. For that
// we also need to reference a unicode font and embed it - royal pain in the rear.
// There is still a benefit to to8bitStream - PDF simply cannot handle 16bit chars,
// which JavaScript Strings are happy to provide. So, while we still cannot display
// 2-byte characters property, at least CONDITIONALLY converting (entire string containing)
// 16bit chars to (USC-2-BE) 2-bytes per char + BOM streams we ensure that entire PDF
// is still parseable.
// This will allow immediate support for unicode in document properties strings.
return to8bitStream(text, flags).replace(/\\/g, '\\\\').replace(/\(/g, '\\(').replace(/\)/g, '\\)');
},
putInfo = function () {
out('/Producer (jsPDF ' + version + ')');
if (documentProperties.title) {
out('/Title (' + pdfEscape(documentProperties.title) + ')');
}
if (documentProperties.subject) {
out('/Subject (' + pdfEscape(documentProperties.subject) + ')');
}
if (documentProperties.author) {
out('/Author (' + pdfEscape(documentProperties.author) + ')');
}
if (documentProperties.keywords) {
out('/Keywords (' + pdfEscape(documentProperties.keywords) + ')');
}
if (documentProperties.creator) {
out('/Creator (' + pdfEscape(documentProperties.creator) + ')');
}
var created = new Date();
out('/CreationDate (D:' +
[
created.getFullYear(),
padd2(created.getMonth() + 1),
padd2(created.getDate()),
padd2(created.getHours()),
padd2(created.getMinutes()),
padd2(created.getSeconds())
].join('') +
')'
);
},
putCatalog = function () {
out('/Type /Catalog');
out('/Pages 1 0 R');
// @TODO: Add zoom and layout modes
out('/OpenAction [3 0 R /FitH null]');
out('/PageLayout /OneColumn');
events.publish('putCatalog');
},
putTrailer = function () {
out('/Size ' + (objectNumber + 1));
out('/Root ' + objectNumber + ' 0 R');
out('/Info ' + (objectNumber - 1) + ' 0 R');
},
beginPage = function () {
page++;
// Do dimension stuff
outToPages = true;
pages[page] = [];
},
_addPage = function () {
beginPage();
// Set line width
out(f2(lineWidth * k) + ' w');
// Set draw color
out(drawColor);
// resurrecting non-default line caps, joins
if (lineCapID !== 0) {
out(lineCapID.toString(10) + ' J');
}
if (lineJoinID !== 0) {
out(lineJoinID.toString(10) + ' j');
}
events.publish('addPage', {'pageNumber': page});
},
/**
Returns a document-specific font key - a label assigned to a
font name + font type combination at the time the font was added
to the font inventory.
Font key is used as label for the desired font for a block of text
to be added to the PDF document stream.
@private
@function
@param fontName {String} can be undefined on "falthy" to indicate "use current"
@param fontStyle {String} can be undefined on "falthy" to indicate "use current"
@returns {String} Font key.
*/
getFont = function (fontName, fontStyle) {
var key, undef;
if (fontName === undef) {
fontName = fonts[activeFontKey].fontName;
}
if (fontStyle === undef) {
fontStyle = fonts[activeFontKey].fontStyle;
}
try {
key = fontmap[fontName][fontStyle]; // returns a string like 'F3' - the KEY corresponding tot he font + type combination.
} catch (e) {
key = undef;
}
if (!key) {
throw new Error("Unable to look up font label for font '" + fontName + "', '" + fontStyle + "'. Refer to getFontList() for available fonts.");
}
return key;
},
buildDocument = function () {
outToPages = false; // switches out() to content
content = [];
offsets = [];
// putHeader()
out('%PDF-' + pdfVersion);
putPages();
putResources();
// Info
newObject();
out('<<');
putInfo();
out('>>');
out('endobj');
// Catalog
newObject();
out('<<');
putCatalog();
out('>>');
out('endobj');
// Cross-ref
var o = content_length, i;
out('xref');
out('0 ' + (objectNumber + 1));
out('0000000000 65535 f ');
for (i = 1; i <= objectNumber; i++) {
out(padd10(offsets[i]) + ' 00000 n ');
}
// Trailer
out('trailer');
out('<<');
putTrailer();
out('>>');
out('startxref');
out(o);
out('%%EOF');
outToPages = true;
return content.join('\n');
},
getStyle = function (style) {
// see Path-Painting Operators of PDF spec
var op = 'S'; // stroke
if (style === 'F') {
op = 'f'; // fill
} else if (style === 'FD' || style === 'DF') {
op = 'B'; // both
}
return op;
},
/**
Generates the PDF document.
Possible values:
datauristring (alias dataurlstring) - Data-Url-formatted data returned as string.
datauri (alias datauri) - Data-Url-formatted data pushed into current window's location (effectively reloading the window with contents of the PDF).
If `type` argument is undefined, output is raw body of resulting PDF returned as a string.
@param {String} type A string identifying one of the possible output types.
@param {Object} options An object providing some additional signalling to PDF generator.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name output
*/
output = function (type, options) {
var undef, data, length, array, i, blob;
switch (type) {
case undef:
return buildDocument();
case 'save':
if (navigator.getUserMedia) {
if (window.URL === undefined) {
return API.output('dataurlnewwindow');
} else if (window.URL.createObjectURL === undefined) {
return API.output('dataurlnewwindow');
}
}
data = buildDocument();
// Need to add the file to BlobBuilder as a Uint8Array
length = data.length;
array = new Uint8Array(new ArrayBuffer(length));
for (i = 0; i < length; i++) {
array[i] = data.charCodeAt(i);
}
blob = new Blob([array], {type: "application/pdf"});
saveAs(blob, options);
break;
case 'datauristring':
case 'dataurlstring':
return 'data:application/pdf;base64,' + btoa(buildDocument());
case 'datauri':
case 'dataurl':
document.location.href = 'data:application/pdf;base64,' + btoa(buildDocument());
break;
case 'dataurlnewwindow':
window.open('data:application/pdf;base64,' + btoa(buildDocument()));
break;
default:
throw new Error('Output type "' + type + '" is not supported.');
}
// @TODO: Add different output options
};
if (unit === 'pt') {
k = 1;
} else if (unit === 'mm') {
k = 72 / 25.4;
} else if (unit === 'cm') {
k = 72 / 2.54;
} else if (unit === 'in') {
k = 72;
} else {
throw ('Invalid unit: ' + unit);
}
// Dimensions are stored as user units and converted to points on output
if (pageFormats.hasOwnProperty(format_as_string)) {
pageHeight = pageFormats[format_as_string][1] / k;
pageWidth = pageFormats[format_as_string][0] / k;
} else {
try {
pageHeight = format[1];
pageWidth = format[0];
} catch (err) {
throw ('Invalid format: ' + format);
}
}
if (orientation === 'p' || orientation === 'portrait') {
orientation = 'p';
if (pageWidth > pageHeight) {
tmp = pageWidth;
pageWidth = pageHeight;
pageHeight = tmp;
}
} else if (orientation === 'l' || orientation === 'landscape') {
orientation = 'l';
if (pageHeight > pageWidth) {
tmp = pageWidth;
pageWidth = pageHeight;
pageHeight = tmp;
}
} else {
throw ('Invalid orientation: ' + orientation);
}
//---------------------------------------
// Public API
/*
Object exposing internal API to plugins
@public
*/
API.internal = {
'pdfEscape': pdfEscape,
'getStyle': getStyle,
/**
Returns {FontObject} describing a particular font.
@public
@function
@param fontName {String} (Optional) Font's family name
@param fontStyle {String} (Optional) Font's style variation name (Example:"Italic")
@returns {FontObject}
*/
'getFont': function () { return fonts[getFont.apply(API, arguments)]; },
'getFontSize': function () { return activeFontSize; },
'getLineHeight': function () { return activeFontSize * lineHeightProportion; },
'btoa': btoa,
'write': function (string1, string2, string3, etc) {
out(
arguments.length === 1 ? string1 : Array.prototype.join.call(arguments, ' ')
);
},
'getCoordinateString': function (value) {
return f2(value * k);
},
'getVerticalCoordinateString': function (value) {
return f2((pageHeight - value) * k);
},
'collections': {},
'newObject': newObject,
'putStream': putStream,
'events': events,
// ratio that you use in multiplication of a given "size" number to arrive to 'point'
// units of measurement.
// scaleFactor is set at initialization of the document and calculated against the stated
// default measurement units for the document.
// If default is "mm", k is the number that will turn number in 'mm' into 'points' number.
// through multiplication.
'scaleFactor': k,
'pageSize': {'width': pageWidth, 'height': pageHeight},
'output': function (type, options) {
return output(type, options);
},
'getNumberOfPages': function () {return pages.length - 1; },
'pages': pages
};
/**
Adds (and transfers the focus to) new page to the PDF document.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name addPage
*/
API.addPage = function () {
_addPage();
return this;
};
/**
Adds text to page. Supports adding multiline text when 'text' argument is an Array of Strings.
@function
@param {String|Array} text String or array of strings to be added to the page. Each line is shifted one line down per font, spacing settings declared before this call.
@param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Object} flags Collection of settings signalling how the text must be encoded. Defaults are sane. If you think you want to pass some flags, you likely can read the source.
@returns {jsPDF}
@methodOf jsPDF#
@name text
*/
API.text = function (text, x, y, flags) {
/**
* Inserts something like this into PDF
BT
/F1 16 Tf % Font name + size
16 TL % How many units down for next line in multiline text
0 g % color
28.35 813.54 Td % position
(line one) Tj
T* (line two) Tj
T* (line three) Tj
ET
*/
var undef, _first, _second, _third, newtext, str, i;
// Pre-August-2012 the order of arguments was function(x, y, text, flags)
// in effort to make all calls have similar signature like
// function(data, coordinates... , miscellaneous)
// this method had its args flipped.
// code below allows backward compatibility with old arg order.
if (typeof text === 'number') {
_first = y;
_second = text;
_third = x;
text = _first;
x = _second;
y = _third;
}
// If there are any newlines in text, we assume
// the user wanted to print multiple lines, so break the
// text up into an array. If the text is already an array,
// we assume the user knows what they are doing.
if (typeof text === 'string' && text.match(/[\n\r]/)) {
text = text.split(/\r\n|\r|\n/g);
}
if (typeof flags === 'undefined') {
flags = {'noBOM': true, 'autoencode': true};
} else {
if (flags.noBOM === undef) {
flags.noBOM = true;
}
if (flags.autoencode === undef) {
flags.autoencode = true;
}
}
if (typeof text === 'string') {
str = pdfEscape(text, flags);
} else if (text instanceof Array) { /* Array */
// we don't want to destroy original text array, so cloning it
newtext = text.concat();
// we do array.join('text that must not be PDFescaped")
// thus, pdfEscape each component separately
for (i = newtext.length - 1; i !== -1; i--) {
newtext[i] = pdfEscape(newtext[i], flags);
}
str = newtext.join(") Tj\nT* (");
} else {
throw new Error('Type of text must be string or Array. "' + text + '" is not recognized.');
}
// Using "'" ("go next line and render text" mark) would save space but would complicate our rendering code, templates
// BT .. ET does NOT have default settings for Tf. You must state that explicitely every time for BT .. ET
// if you want text transformation matrix (+ multiline) to work reliably (which reads sizes of things from font declarations)
// Thus, there is NO useful, *reliable* concept of "default" font for a page.
// The fact that "default" (reuse font used before) font worked before in basic cases is an accident
// - readers dealing smartly with brokenness of jsPDF's markup.
out(
'BT\n/' +
activeFontKey + ' ' + activeFontSize + ' Tf\n' + // font face, style, size
(activeFontSize * lineHeightProportion) + ' TL\n' + // line spacing
textColor +
'\n' + f2(x * k) + ' ' + f2((pageHeight - y) * k) + ' Td\n(' +
str +
') Tj\nET'
);
return this;
};
API.line = function (x1, y1, x2, y2) {
out(
f2(x1 * k) + ' ' + f2((pageHeight - y1) * k) + ' m ' +
f2(x2 * k) + ' ' + f2((pageHeight - y2) * k) + ' l S'
);
return this;
};
/**
Adds series of curves (straight lines or cubic bezier curves) to canvas, starting at `x`, `y` coordinates.
All data points in `lines` are relative to last line origin.
`x`, `y` become x1,y1 for first line / curve in the set.
For lines you only need to specify [x2, y2] - (ending point) vector against x1, y1 starting point.
For bezier curves you need to specify [x2,y2,x3,y3,x4,y4] - vectors to control points 1, 2, ending point. All vectors are against the start of the curve - x1,y1.
@example .lines([[2,2],[-2,2],[1,1,2,2,3,3],[2,1]], 212,110, 10) // line, line, bezier curve, line
@param {Array} lines Array of *vector* shifts as pairs (lines) or sextets (cubic bezier curves).
@param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} scale (Defaults to [1.0,1.0]) x,y Scaling factor for all vectors. Elements can be any floating number Sub-one makes drawing smaller. Over-one grows the drawing. Negative flips the direction.
@param {String} style One of 'S' (the default), 'F', 'FD' or 'DF'. 'S' draws just the curve. 'F' fills the region defined by the curves. 'DF' or 'FD' draws the curves and fills the region.
@param {Boolean} closed If true, the path is closed with a straight line from the end of the last curve to the starting point.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name lines
*/
API.lines = function (lines, x, y, scale, style, closed) {
var undef, _first, _second, _third, scalex, scaley, i, l, leg, x2, y2, x3, y3, x4, y4;
// Pre-August-2012 the order of arguments was function(x, y, lines, scale, style)
// in effort to make all calls have similar signature like
// function(content, coordinateX, coordinateY , miscellaneous)
// this method had its args flipped.
// code below allows backward compatibility with old arg order.
if (typeof lines === 'number') {
_first = y;
_second = lines;
_third = x;
lines = _first;
x = _second;
y = _third;
}
style = getStyle(style);
scale = scale === undef ? [1, 1] : scale;
// starting point
out(f3(x * k) + ' ' + f3((pageHeight - y) * k) + ' m ');
scalex = scale[0];
scaley = scale[1];
l = lines.length;
//, x2, y2 // bezier only. In page default measurement "units", *after* scaling
//, x3, y3 // bezier only. In page default measurement "units", *after* scaling
// ending point for all, lines and bezier. . In page default measurement "units", *after* scaling
x4 = x; // last / ending point = starting point for first item.
y4 = y; // last / ending point = starting point for first item.
for (i = 0; i < l; i++) {
leg = lines[i];
if (leg.length === 2) {
// simple line
x4 = leg[0] * scalex + x4; // here last x4 was prior ending point
y4 = leg[1] * scaley + y4; // here last y4 was prior ending point
out(f3(x4 * k) + ' ' + f3((pageHeight - y4) * k) + ' l');
} else {
// bezier curve
x2 = leg[0] * scalex + x4; // here last x4 is prior ending point
y2 = leg[1] * scaley + y4; // here last y4 is prior ending point
x3 = leg[2] * scalex + x4; // here last x4 is prior ending point
y3 = leg[3] * scaley + y4; // here last y4 is prior ending point
x4 = leg[4] * scalex + x4; // here last x4 was prior ending point
y4 = leg[5] * scaley + y4; // here last y4 was prior ending point
out(
f3(x2 * k) + ' ' +
f3((pageHeight - y2) * k) + ' ' +
f3(x3 * k) + ' ' +
f3((pageHeight - y3) * k) + ' ' +
f3(x4 * k) + ' ' +
f3((pageHeight - y4) * k) + ' c'
);
}
}
if (closed == true) {
out(' h');
}
// stroking / filling / both the path
out(style);
return this;
};
/**
Adds a rectangle to PDF
@param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} w Width (in units declared at inception of PDF document)
@param {Number} h Height (in units declared at inception of PDF document)
@param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name rect
*/
API.rect = function (x, y, w, h, style) {
var op = getStyle(style);
out([
f2(x * k),
f2((pageHeight - y) * k),
f2(w * k),
f2(-h * k),
're',
op
].join(' '));
return this;
};
/**
Adds a triangle to PDF
@param {Number} x1 Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y1 Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} x2 Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y2 Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} x3 Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y3 Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name triangle
*/
API.triangle = function (x1, y1, x2, y2, x3, y3, style) {
this.lines(
[
[ x2 - x1, y2 - y1 ], // vector to point 2
[ x3 - x2, y3 - y2 ], // vector to point 3
[ x1 - x3, y1 - y3 ] // closing vector back to point 1
],
x1,
y1, // start of path
[1, 1],
style,
true
);
return this;
};
/**
Adds a rectangle with rounded corners to PDF
@param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} w Width (in units declared at inception of PDF document)
@param {Number} h Height (in units declared at inception of PDF document)
@param {Number} rx Radius along x axis (in units declared at inception of PDF document)
@param {Number} rx Radius along y axis (in units declared at inception of PDF document)
@param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name roundedRect
*/
API.roundedRect = function (x, y, w, h, rx, ry, style) {
var MyArc = 4 / 3 * (Math.SQRT2 - 1);
this.lines(
[
[ (w - 2 * rx), 0 ],
[ (rx * MyArc), 0, rx, ry - (ry * MyArc), rx, ry ],
[ 0, (h - 2 * ry) ],
[ 0, (ry * MyArc), -(rx * MyArc), ry, -rx, ry],
[ (-w + 2 * rx), 0],
[ -(rx * MyArc), 0, -rx, -(ry * MyArc), -rx, -ry],
[ 0, (-h + 2 * ry)],
[ 0, -(ry * MyArc), (rx * MyArc), -ry, rx, -ry]
],
x + rx,
y, // start of path
[1, 1],
style
);
return this;
};
/**
Adds an ellipse to PDF
@param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} rx Radius along x axis (in units declared at inception of PDF document)
@param {Number} rx Radius along y axis (in units declared at inception of PDF document)
@param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name ellipse
*/
API.ellipse = function (x, y, rx, ry, style) {
var op = getStyle(style),
lx = 4 / 3 * (Math.SQRT2 - 1) * rx,
ly = 4 / 3 * (Math.SQRT2 - 1) * ry;
out([
f2((x + rx) * k),
f2((pageHeight - y) * k),
'm',
f2((x + rx) * k),
f2((pageHeight - (y - ly)) * k),
f2((x + lx) * k),
f2((pageHeight - (y - ry)) * k),
f2(x * k),
f2((pageHeight - (y - ry)) * k),
'c'
].join(' '));
out([
f2((x - lx) * k),
f2((pageHeight - (y - ry)) * k),
f2((x - rx) * k),
f2((pageHeight - (y - ly)) * k),
f2((x - rx) * k),
f2((pageHeight - y) * k),
'c'
].join(' '));
out([
f2((x - rx) * k),
f2((pageHeight - (y + ly)) * k),
f2((x - lx) * k),
f2((pageHeight - (y + ry)) * k),
f2(x * k),
f2((pageHeight - (y + ry)) * k),
'c'
].join(' '));
out([
f2((x + lx) * k),
f2((pageHeight - (y + ry)) * k),
f2((x + rx) * k),
f2((pageHeight - (y + ly)) * k),
f2((x + rx) * k),
f2((pageHeight - y) * k),
'c',
op
].join(' '));
return this;
};
/**
Adds an circle to PDF
@param {Number} x Coordinate (in units declared at inception of PDF document) against left edge of the page
@param {Number} y Coordinate (in units declared at inception of PDF document) against upper edge of the page
@param {Number} r Radius (in units declared at inception of PDF document)
@param {String} style (Defaults to active fill/stroke style) A string signalling if stroke, fill or both are to be applied.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name circle
*/
API.circle = function (x, y, r, style) {
return this.ellipse(x, y, r, r, style);
};
/**
Adds a properties to the PDF document
@param {Object} A property_name-to-property_value object structure.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setProperties
*/
API.setProperties = function (properties) {
// copying only those properties we can render.
var property;
for (property in documentProperties) {
if (documentProperties.hasOwnProperty(property) && properties[property]) {
documentProperties[property] = properties[property];
}
}
return this;
};
/**
Sets font size for upcoming text elements.
@param {Number} size Font size in points.
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setFontSize
*/
API.setFontSize = function (size) {
activeFontSize = size;
return this;
};
/**
Sets text font face, variant for upcoming text elements.
See output of jsPDF.getFontList() for possible font names, styles.
@param {String} fontName Font name or family. Example: "times"
@param {String} fontStyle Font style or variant. Example: "italic"
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setFont
*/
API.setFont = function (fontName, fontStyle) {
activeFontKey = getFont(fontName, fontStyle);
// if font is not found, the above line blows up and we never go further
return this;
};
/**
Switches font style or variant for upcoming text elements,
while keeping the font face or family same.
See output of jsPDF.getFontList() for possible font names, styles.
@param {String} style Font style or variant. Example: "italic"
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setFontStyle
*/
API.setFontStyle = API.setFontType = function (style) {
var undef;
activeFontKey = getFont(undef, style);
// if font is not found, the above line blows up and we never go further
return this;
};
/**
Returns an object - a tree of fontName to fontStyle relationships available to
active PDF document.
@public
@function
@returns {Object} Like {'times':['normal', 'italic', ... ], 'arial':['normal', 'bold', ... ], ... }
@methodOf jsPDF#
@name getFontList
*/
API.getFontList = function () {
// TODO: iterate over fonts array or return copy of fontmap instead in case more are ever added.
var list = {},
fontName,
fontStyle,
tmp;
for (fontName in fontmap) {
if (fontmap.hasOwnProperty(fontName)) {
list[fontName] = tmp = [];
for (fontStyle in fontmap[fontName]) {
if (fontmap[fontName].hasOwnProperty(fontStyle)) {
tmp.push(fontStyle);
}
}
}
}
return list;
};
/**
Sets line width for upcoming lines.
@param {Number} width Line width (in units declared at inception of PDF document)
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setLineWidth
*/
API.setLineWidth = function (width) {
out((width * k).toFixed(2) + ' w');
return this;
};
/**
Sets the stroke color for upcoming elements.
Depending on the number of arguments given, Gray, RGB, or CMYK
color space is implied.
When only ch1 is given, "Gray" color space is implied and it
must be a value in the range from 0.00 (solid black) to to 1.00 (white)
if values are communicated as String types, or in range from 0 (black)
to 255 (white) if communicated as Number type.
The RGB-like 0-255 range is provided for backward compatibility.
When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
value must be in the range from 0.00 (minimum intensity) to to 1.00
(max intensity) if values are communicated as String types, or
from 0 (min intensity) to to 255 (max intensity) if values are communicated
as Number types.
The RGB-like 0-255 range is provided for backward compatibility.
When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
value must be a in the range from 0.00 (0% concentration) to to
1.00 (100% concentration)
Because JavaScript treats fixed point numbers badly (rounds to
floating point nearest to binary representation) it is highly advised to
communicate the fractional numbers as String types, not JavaScript Number type.
@param {Number|String} ch1 Color channel value
@param {Number|String} ch2 Color channel value
@param {Number|String} ch3 Color channel value
@param {Number|String} ch4 Color channel value
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setDrawColor
*/
API.setDrawColor = function (ch1, ch2, ch3, ch4) {
var color;
if (ch2 === undefined || (ch4 === undefined && ch1 === ch2 === ch3)) {
// Gray color space.
if (typeof ch1 === 'string') {
color = ch1 + ' G';
} else {
color = f2(ch1 / 255) + ' G';
}
} else if (ch4 === undefined) {
// RGB
if (typeof ch1 === 'string') {
color = [ch1, ch2, ch3, 'RG'].join(' ');
} else {
color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'RG'].join(' ');
}
} else {
// CMYK
if (typeof ch1 === 'string') {
color = [ch1, ch2, ch3, ch4, 'K'].join(' ');
} else {
color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'K'].join(' ');
}
}
out(color);
return this;
};
/**
Sets the fill color for upcoming elements.
Depending on the number of arguments given, Gray, RGB, or CMYK
color space is implied.
When only ch1 is given, "Gray" color space is implied and it
must be a value in the range from 0.00 (solid black) to to 1.00 (white)
if values are communicated as String types, or in range from 0 (black)
to 255 (white) if communicated as Number type.
The RGB-like 0-255 range is provided for backward compatibility.
When only ch1,ch2,ch3 are given, "RGB" color space is implied and each
value must be in the range from 0.00 (minimum intensity) to to 1.00
(max intensity) if values are communicated as String types, or
from 0 (min intensity) to to 255 (max intensity) if values are communicated
as Number types.
The RGB-like 0-255 range is provided for backward compatibility.
When ch1,ch2,ch3,ch4 are given, "CMYK" color space is implied and each
value must be a in the range from 0.00 (0% concentration) to to
1.00 (100% concentration)
Because JavaScript treats fixed point numbers badly (rounds to
floating point nearest to binary representation) it is highly advised to
communicate the fractional numbers as String types, not JavaScript Number type.
@param {Number|String} ch1 Color channel value
@param {Number|String} ch2 Color channel value
@param {Number|String} ch3 Color channel value
@param {Number|String} ch4 Color channel value
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setFillColor
*/
API.setFillColor = function (ch1, ch2, ch3, ch4) {
var color;
if (ch2 === undefined || (ch4 === undefined && ch1 === ch2 === ch3)) {
// Gray color space.
if (typeof ch1 === 'string') {
color = ch1 + ' g';
} else {
color = f2(ch1 / 255) + ' g';
}
} else if (ch4 === undefined) {
// RGB
if (typeof ch1 === 'string') {
color = [ch1, ch2, ch3, 'rg'].join(' ');
} else {
color = [f2(ch1 / 255), f2(ch2 / 255), f2(ch3 / 255), 'rg'].join(' ');
}
} else {
// CMYK
if (typeof ch1 === 'string') {
color = [ch1, ch2, ch3, ch4, 'k'].join(' ');
} else {
color = [f2(ch1), f2(ch2), f2(ch3), f2(ch4), 'k'].join(' ');
}
}
out(color);
return this;
};
/**
Sets the text color for upcoming elements.
If only one, first argument is given,
treats the value as gray-scale color value.
@param {Number} r Red channel color value in range 0-255 or {String} r color value in hexadecimal, example: '#FFFFFF'
@param {Number} g Green channel color value in range 0-255
@param {Number} b Blue channel color value in range 0-255
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setTextColor
*/
API.setTextColor = function (r, g, b) {
var patt = /#[0-9A-Fa-f]{6}/;
if ((typeof r == 'string') && patt.test(r)) {
var hex = r.replace('#','');
var bigint = parseInt(hex, 16);
r = (bigint >> 16) & 255;
g = (bigint >> 8) & 255;
b = bigint & 255;
}
if ((r === 0 && g === 0 && b === 0) || (typeof g === 'undefined')) {
textColor = f3(r / 255) + ' g';
} else {
textColor = [f3(r / 255), f3(g / 255), f3(b / 255), 'rg'].join(' ');
}
return this;
};
/**
Is an Object providing a mapping from human-readable to
integer flag values designating the varieties of line cap
and join styles.
@returns {Object}
@fieldOf jsPDF#
@name CapJoinStyles
*/
API.CapJoinStyles = {
0: 0,
'butt': 0,
'but': 0,
'miter': 0,
1: 1,
'round': 1,
'rounded': 1,
'circle': 1,
2: 2,
'projecting': 2,
'project': 2,
'square': 2,
'bevel': 2
};
/**
Sets the line cap styles
See {jsPDF.CapJoinStyles} for variants
@param {String|Number} style A string or number identifying the type of line cap
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setLineCap
*/
API.setLineCap = function (style) {
var id = this.CapJoinStyles[style];
if (id === undefined) {
throw new Error("Line cap style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
}
lineCapID = id;
out(id.toString(10) + ' J');
return this;
};
/**
Sets the line join styles
See {jsPDF.CapJoinStyles} for variants
@param {String|Number} style A string or number identifying the type of line join
@function
@returns {jsPDF}
@methodOf jsPDF#
@name setLineJoin
*/
API.setLineJoin = function (style) {
var id = this.CapJoinStyles[style];
if (id === undefined) {
throw new Error("Line join style of '" + style + "' is not recognized. See or extend .CapJoinStyles property for valid styles");
}
lineJoinID = id;
out(id.toString(10) + ' j');
return this;
};
// Output is both an internal (for plugins) and external function
API.output = output;
/**
* Saves as PDF document. An alias of jsPDF.output('save', 'filename.pdf')
* @param {String} filename The filename including extension.
*
* @function
* @returns {jsPDF}
* @methodOf jsPDF#
* @name save
*/
API.save = function (filename) {
API.output('save', filename);
};
// applying plugins (more methods) ON TOP of built-in API.
// this is intentional as we allow plugins to override
// built-ins
for (plugin in jsPDF.API) {
if (jsPDF.API.hasOwnProperty(plugin)) {
if (plugin === 'events' && jsPDF.API.events.length) {
(function (events, newEvents) {
// jsPDF.API.events is a JS Array of Arrays
// where each Array is a pair of event name, handler
// Events were added by plugins to the jsPDF instantiator.
// These are always added to the new instance and some ran
// during instantiation.
var eventname, handler_and_args, i;
for (i = newEvents.length - 1; i !== -1; i--) {
// subscribe takes 3 args: 'topic', function, runonce_flag
// if undefined, runonce is false.
// users can attach callback directly,
// or they can attach an array with [callback, runonce_flag]
// that's what the "apply" magic is for below.
eventname = newEvents[i][0];
handler_and_args = newEvents[i][1];
events.subscribe.apply(
events,
[eventname].concat(
typeof handler_and_args === 'function' ?
[ handler_and_args ] :
handler_and_args
)
);
}
}(events, jsPDF.API.events));
} else {
API[plugin] = jsPDF.API[plugin];
}
}
}
/////////////////////////////////////////
// continuing initilisation of jsPDF Document object
/////////////////////////////////////////
// Add the first page automatically
addFonts();
activeFontKey = 'F1';
_addPage();
events.publish('initialized');
return API;
}
/**
jsPDF.API is a STATIC property of jsPDF class.
jsPDF.API is an object you can add methods and properties to.
The methods / properties you add will show up in new jsPDF objects.
One property is prepopulated. It is the 'events' Object. Plugin authors can add topics, callbacks to this object. These will be reassigned to all new instances of jsPDF.
Examples:
jsPDF.API.events['initialized'] = function(){ 'this' is API object }
jsPDF.API.events['addFont'] = function(added_font_object){ 'this' is API object }
@static
@public
@memberOf jsPDF
@name API
@example
jsPDF.API.mymethod = function(){
// 'this' will be ref to internal API object. see jsPDF source
// , so you can refer to built-in methods like so:
// this.line(....)
// this.text(....)
}
var pdfdoc = new jsPDF()
pdfdoc.mymethod() // <- !!!!!!
*/
jsPDF.API = {'events': []};
return jsPDF;
}()); | Afreenjoarder/finalproject | public/assets/global/plugins/amcharts/amcharts/exporting/jspdf.js | JavaScript | mit | 80,837 |
var ElementType = require("domelementtype");
var isTag = exports.isTag = ElementType.isTag;
exports.testElement = function(options, element){
for(var key in options){
if(!options.hasOwnProperty(key));
else if(key === "tag_name"){
if(!isTag(element) || !options.tag_name(element.name)){
return false;
}
} else if(key === "tag_type"){
if(!options.tag_type(element.type)) return false;
} else if(key === "tag_contains"){
if(isTag(element) || !options.tag_contains(element.data)){
return false;
}
} else if(!element.attribs || !options[key](element.attribs[key])){
return false;
}
}
return true;
};
var Checks = {
tag_name: function(name){
if(typeof name === "function"){
return function(elem){ return isTag(elem) && name(elem.name); };
} else if(name === "*"){
return isTag;
} else {
return function(elem){ return isTag(elem) && elem.name === name; };
}
},
tag_type: function(type){
if(typeof type === "function"){
return function(elem){ return type(elem.type); };
} else {
return function(elem){ return elem.type === type; };
}
},
tag_contains: function(data){
if(typeof data === "function"){
return function(elem){ return !isTag(elem) && data(elem.data); };
} else {
return function(elem){ return !isTag(elem) && elem.data === data; };
}
}
};
function getAttribCheck(attrib, value){
if(typeof value === "function"){
return function(elem){ return elem.attribs && value(elem.attribs[attrib]); };
} else {
return function(elem){ return elem.attribs && elem.attribs[attrib] === value; };
}
}
function combineFuncs(a, b){
return function(elem){
return a(elem) || b(elem);
};
}
exports.getElements = function(options, element, recurse, limit){
var funcs = Object.keys(options).map(function(key){
var value = options[key];
return key in Checks ? Checks[key](value) : getAttribCheck(key, value);
});
return funcs.length === 0 ? [] : this.filter(
funcs.reduce(combineFuncs),
element, recurse, limit
);
};
exports.getElementById = function(id, element, recurse){
if(!Array.isArray(element)) element = [element];
return this.findOne(getAttribCheck("id", id), element, recurse !== false);
};
exports.getElementsByTagName = function(name, element, recurse, limit){
return this.filter(Checks.tag_name(name), element, recurse, limit);
};
exports.getElementsByTagType = function(type, element, recurse, limit){
return this.filter(Checks.tag_type(type), element, recurse, limit);
};
| huyuezheng/blog | node_modules/cheerio/node_modules/htmlparser2/node_modules/domutils/lib/legacy.js | JavaScript | mit | 2,489 |
/*
* tst.werror.js: tests basic functionality of the WError class.
*/
var mod_assert = require('assert');
var mod_verror = require('../lib/verror');
var VError = mod_verror.VError;
var WError = mod_verror.WError;
var err, suberr, stack, substack;
/*
* Remove full paths and relative line numbers from stack traces so that we can
* compare against "known-good" output.
*/
function cleanStack(stacktxt)
{
var re = new RegExp(__filename + ':\\d+:\\d+', 'gm');
stacktxt = stacktxt.replace(re, 'tst.werror.js');
return (stacktxt);
}
/*
* Save the generic parts of all stack traces so we can avoid hardcoding
* Node-specific implementation details in our testing of stack traces.
*/
var nodestack = new Error().stack.split('\n').slice(2).join('\n');
/* no arguments */
err = new WError();
mod_assert.equal(err.name, 'WError');
mod_assert.ok(err instanceof Error);
mod_assert.ok(err instanceof WError);
mod_assert.equal(err.message, '');
mod_assert.equal(err.toString(), 'WError');
mod_assert.ok(err.cause() === undefined);
stack = cleanStack(err.stack);
mod_assert.equal(stack, [
'WError',
' at Object.<anonymous> (tst.werror.js)'
].join('\n') + '\n' + nodestack);
/* options-argument form */
err = new WError({});
mod_assert.equal(err.message, '');
mod_assert.equal(err.toString(), 'WError');
mod_assert.ok(err.cause() === undefined);
/* simple message */
err = new WError('my error');
mod_assert.equal(err.message, 'my error');
mod_assert.equal(err.toString(), 'WError: my error');
mod_assert.ok(err.cause() === undefined);
stack = cleanStack(err.stack);
mod_assert.equal(stack, [
'WError: my error',
' at Object.<anonymous> (tst.werror.js)'
].join('\n') + '\n' + nodestack);
err = new WError({}, 'my error');
mod_assert.equal(err.message, 'my error');
mod_assert.equal(err.toString(), 'WError: my error');
mod_assert.ok(err.cause() === undefined);
/* printf-style message */
err = new WError('%s error: %3d problems', 'very bad', 15);
mod_assert.equal(err.message, 'very bad error: 15 problems');
mod_assert.equal(err.toString(), 'WError: very bad error: 15 problems');
mod_assert.ok(err.cause() === undefined);
err = new WError({}, '%s error: %3d problems', 'very bad', 15);
mod_assert.equal(err.message, 'very bad error: 15 problems');
mod_assert.equal(err.toString(), 'WError: very bad error: 15 problems');
mod_assert.ok(err.cause() === undefined);
/* caused by another error, with no additional message */
suberr = new Error('root cause');
err = new WError(suberr);
mod_assert.equal(err.message, '');
mod_assert.equal(err.toString(), 'WError; caused by Error: root cause');
mod_assert.ok(err.cause() === suberr);
err = new WError({ 'cause': suberr });
mod_assert.equal(err.message, '');
mod_assert.equal(err.toString(), 'WError; caused by Error: root cause');
mod_assert.ok(err.cause() === suberr);
/* caused by another error, with annotation */
err = new WError(suberr, 'proximate cause: %d issues', 3);
mod_assert.equal(err.message, 'proximate cause: 3 issues');
mod_assert.equal(err.toString(), 'WError: proximate cause: 3 issues; ' +
'caused by Error: root cause');
mod_assert.ok(err.cause() === suberr);
stack = cleanStack(err.stack);
mod_assert.equal(stack, [
'WError: proximate cause: 3 issues; caused by Error: root cause',
' at Object.<anonymous> (tst.werror.js)'
].join('\n') + '\n' + nodestack);
err = new WError({ 'cause': suberr }, 'proximate cause: %d issues', 3);
mod_assert.equal(err.message, 'proximate cause: 3 issues');
mod_assert.equal(err.toString(), 'WError: proximate cause: 3 issues; ' +
'caused by Error: root cause');
mod_assert.ok(err.cause() === suberr);
stack = cleanStack(err.stack);
mod_assert.equal(stack, [
'WError: proximate cause: 3 issues; caused by Error: root cause',
' at Object.<anonymous> (tst.werror.js)'
].join('\n') + '\n' + nodestack);
/* caused by another WError, with annotation. */
suberr = err;
err = new WError(suberr, 'top');
mod_assert.equal(err.message, 'top');
mod_assert.equal(err.toString(), 'WError: top; caused by WError: ' +
'proximate cause: 3 issues; caused by Error: root cause');
mod_assert.ok(err.cause() === suberr);
err = new WError({ 'cause': suberr }, 'top');
mod_assert.equal(err.message, 'top');
mod_assert.equal(err.toString(), 'WError: top; caused by WError: ' +
'proximate cause: 3 issues; caused by Error: root cause');
mod_assert.ok(err.cause() === suberr);
/* caused by a VError */
suberr = new VError(new Error('root cause'), 'mid');
err = new WError(suberr, 'top');
mod_assert.equal(err.message, 'top');
mod_assert.equal(err.toString(),
'WError: top; caused by VError: mid: root cause');
mod_assert.ok(err.cause() === suberr);
/* null cause (for backwards compatibility with older versions) */
err = new WError(null, 'my error');
mod_assert.equal(err.message, 'my error');
mod_assert.equal(err.toString(), 'WError: my error');
mod_assert.ok(err.cause() === undefined);
stack = cleanStack(err.stack);
mod_assert.equal(stack, [
'WError: my error',
' at Object.<anonymous> (tst.werror.js)'
].join('\n') + '\n' + nodestack);
err = new WError({ 'cause': null }, 'my error');
mod_assert.equal(err.message, 'my error');
mod_assert.equal(err.toString(), 'WError: my error');
mod_assert.ok(err.cause() === undefined);
err = new WError(null);
mod_assert.equal(err.message, '');
mod_assert.equal(err.toString(), 'WError');
mod_assert.ok(err.cause() === undefined);
stack = cleanStack(err.stack);
mod_assert.equal(stack, [
'WError',
' at Object.<anonymous> (tst.werror.js)'
].join('\n') + '\n' + nodestack);
/* constructorOpt */
function makeErr(options) {
return (new WError(options, 'test error'));
}
err = makeErr({});
mod_assert.equal(err.toString(), 'WError: test error');
stack = cleanStack(err.stack);
mod_assert.equal(stack, [
'WError: test error',
' at makeErr (tst.werror.js)',
' at Object.<anonymous> (tst.werror.js)'
].join('\n') + '\n' + nodestack);
err = makeErr({ 'constructorOpt': makeErr });
mod_assert.equal(err.toString(), 'WError: test error');
stack = cleanStack(err.stack);
mod_assert.equal(stack, [
'WError: test error',
' at Object.<anonymous> (tst.werror.js)'
].join('\n') + '\n' + nodestack);
| kartik-nighania/BeagleBone_remote_seismometer_node | node_modules/serialport/node_modules/node-pre-gyp/node_modules/request/node_modules/http-signature/node_modules/jsprim/node_modules/verror/tests/tst.werror.js | JavaScript | mit | 6,241 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>CMSIS DSP Software Library: arm_mat_add_q15.c Source File</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javaScript" src="search/search.js"></script>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body onload='searchBox.OnSelectItem(0);'>
<!-- Generated by Doxygen 1.7.2 -->
<script type="text/javascript"><!--
var searchBox = new SearchBox("searchBox", "search",false,'Search');
--></script>
<div class="navigation" id="top">
<div class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="modules.html"><span>Modules</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li><a href="examples.html"><span>Examples</span></a></li>
<li id="searchli">
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</li>
</ul>
</div>
<div class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>Globals</span></a></li>
</ul>
</div>
<div class="header">
<div class="headertitle">
<h1>arm_mat_add_q15.c</h1> </div>
</div>
<div class="contents">
<a href="arm__mat__add__q15_8c.html">Go to the documentation of this file.</a><div class="fragment"><pre class="fragment"><a name="l00001"></a>00001 <span class="comment">/* ---------------------------------------------------------------------- </span>
<a name="l00002"></a>00002 <span class="comment">* Copyright (C) 2010 ARM Limited. All rights reserved. </span>
<a name="l00003"></a>00003 <span class="comment">* </span>
<a name="l00004"></a>00004 <span class="comment">* $Date: 15. July 2011 </span>
<a name="l00005"></a>00005 <span class="comment">* $Revision: V1.0.10 </span>
<a name="l00006"></a>00006 <span class="comment">* </span>
<a name="l00007"></a>00007 <span class="comment">* Project: CMSIS DSP Library </span>
<a name="l00008"></a>00008 <span class="comment">* Title: arm_mat_add_q15.c </span>
<a name="l00009"></a>00009 <span class="comment">* </span>
<a name="l00010"></a>00010 <span class="comment">* Description: Q15 matrix addition </span>
<a name="l00011"></a>00011 <span class="comment">* </span>
<a name="l00012"></a>00012 <span class="comment">* Target Processor: Cortex-M4/Cortex-M3/Cortex-M0</span>
<a name="l00013"></a>00013 <span class="comment">* </span>
<a name="l00014"></a>00014 <span class="comment">* Version 1.0.10 2011/7/15 </span>
<a name="l00015"></a>00015 <span class="comment">* Big Endian support added and Merged M0 and M3/M4 Source code. </span>
<a name="l00016"></a>00016 <span class="comment">* </span>
<a name="l00017"></a>00017 <span class="comment">* Version 1.0.3 2010/11/29 </span>
<a name="l00018"></a>00018 <span class="comment">* Re-organized the CMSIS folders and updated documentation. </span>
<a name="l00019"></a>00019 <span class="comment">* </span>
<a name="l00020"></a>00020 <span class="comment">* Version 1.0.2 2010/11/11 </span>
<a name="l00021"></a>00021 <span class="comment">* Documentation updated. </span>
<a name="l00022"></a>00022 <span class="comment">* </span>
<a name="l00023"></a>00023 <span class="comment">* Version 1.0.1 2010/10/05 </span>
<a name="l00024"></a>00024 <span class="comment">* Production release and review comments incorporated. </span>
<a name="l00025"></a>00025 <span class="comment">* </span>
<a name="l00026"></a>00026 <span class="comment">* Version 1.0.0 2010/09/20 </span>
<a name="l00027"></a>00027 <span class="comment">* Production release and review comments incorporated. </span>
<a name="l00028"></a>00028 <span class="comment">* </span>
<a name="l00029"></a>00029 <span class="comment">* Version 0.0.5 2010/04/26 </span>
<a name="l00030"></a>00030 <span class="comment">* incorporated review comments and updated with latest CMSIS layer </span>
<a name="l00031"></a>00031 <span class="comment">* </span>
<a name="l00032"></a>00032 <span class="comment">* Version 0.0.3 2010/03/10 </span>
<a name="l00033"></a>00033 <span class="comment">* Initial version </span>
<a name="l00034"></a>00034 <span class="comment">* -------------------------------------------------------------------- */</span>
<a name="l00035"></a>00035
<a name="l00036"></a>00036 <span class="preprocessor">#include "<a class="code" href="arm__math_8h.html">arm_math.h</a>"</span>
<a name="l00037"></a>00037
<a name="l00061"></a><a class="code" href="group___matrix_add.html#ga147e90b7c12a162735ab8824127a33ee">00061</a> <a class="code" href="arm__math_8h.html#a5e459c6409dfcd2927bb8a57491d7cf6" title="Error status returned by some functions in the library.">arm_status</a> <a class="code" href="group___matrix_add.html#ga147e90b7c12a162735ab8824127a33ee" title="Q15 matrix addition.">arm_mat_add_q15</a>(
<a name="l00062"></a>00062 <span class="keyword">const</span> <a class="code" href="structarm__matrix__instance__q15.html" title="Instance structure for the Q15 matrix structure.">arm_matrix_instance_q15</a> * pSrcA,
<a name="l00063"></a>00063 <span class="keyword">const</span> <a class="code" href="structarm__matrix__instance__q15.html" title="Instance structure for the Q15 matrix structure.">arm_matrix_instance_q15</a> * pSrcB,
<a name="l00064"></a>00064 <a class="code" href="structarm__matrix__instance__q15.html" title="Instance structure for the Q15 matrix structure.">arm_matrix_instance_q15</a> * pDst)
<a name="l00065"></a>00065 {
<a name="l00066"></a>00066 <a class="code" href="arm__math_8h.html#ab5a8fb21a5b3b983d5f54f31614052ea" title="16-bit fractional data type in 1.15 format.">q15_t</a> *pInA = pSrcA-><a class="code" href="structarm__matrix__instance__q15.html#a6da33a5553e634787d0f515cf8d724af">pData</a>; <span class="comment">/* input data matrix pointer A */</span>
<a name="l00067"></a>00067 <a class="code" href="arm__math_8h.html#ab5a8fb21a5b3b983d5f54f31614052ea" title="16-bit fractional data type in 1.15 format.">q15_t</a> *pInB = pSrcB-><a class="code" href="structarm__matrix__instance__q15.html#a6da33a5553e634787d0f515cf8d724af">pData</a>; <span class="comment">/* input data matrix pointer B */</span>
<a name="l00068"></a>00068 <a class="code" href="arm__math_8h.html#ab5a8fb21a5b3b983d5f54f31614052ea" title="16-bit fractional data type in 1.15 format.">q15_t</a> *pOut = pDst-><a class="code" href="structarm__matrix__instance__q15.html#a6da33a5553e634787d0f515cf8d724af">pData</a>; <span class="comment">/* output data matrix pointer */</span>
<a name="l00069"></a>00069 uint16_t numSamples; <span class="comment">/* total number of elements in the matrix */</span>
<a name="l00070"></a>00070 uint32_t blkCnt; <span class="comment">/* loop counters */</span>
<a name="l00071"></a>00071 <a class="code" href="arm__math_8h.html#a5e459c6409dfcd2927bb8a57491d7cf6" title="Error status returned by some functions in the library.">arm_status</a> <a class="code" href="arm__dotproduct__example__f32_8c.html#a88ccb294236ab22b00310c47164c53c3">status</a>; <span class="comment">/* status of matrix addition */</span>
<a name="l00072"></a>00072
<a name="l00073"></a>00073 <span class="preprocessor">#ifdef ARM_MATH_MATRIX_CHECK</span>
<a name="l00074"></a>00074 <span class="preprocessor"></span>
<a name="l00075"></a>00075
<a name="l00076"></a>00076 <span class="comment">/* Check for matrix mismatch condition */</span>
<a name="l00077"></a>00077 <span class="keywordflow">if</span>((pSrcA-><a class="code" href="structarm__matrix__instance__q15.html#a9bac6ed54be287c4d4f01a1a28be65f5">numRows</a> != pSrcB-><a class="code" href="structarm__matrix__instance__q15.html#a9bac6ed54be287c4d4f01a1a28be65f5">numRows</a>) ||
<a name="l00078"></a>00078 (pSrcA-><a class="code" href="structarm__matrix__instance__q15.html#acbbce67ba058d8e1c867c71d57288c97">numCols</a> != pSrcB-><a class="code" href="structarm__matrix__instance__q15.html#acbbce67ba058d8e1c867c71d57288c97">numCols</a>) ||
<a name="l00079"></a>00079 (pSrcA-><a class="code" href="structarm__matrix__instance__q15.html#a9bac6ed54be287c4d4f01a1a28be65f5">numRows</a> != pDst-><a class="code" href="structarm__matrix__instance__q15.html#a9bac6ed54be287c4d4f01a1a28be65f5">numRows</a>) || (pSrcA-><a class="code" href="structarm__matrix__instance__q15.html#acbbce67ba058d8e1c867c71d57288c97">numCols</a> != pDst-><a class="code" href="structarm__matrix__instance__q15.html#acbbce67ba058d8e1c867c71d57288c97">numCols</a>))
<a name="l00080"></a>00080 {
<a name="l00081"></a>00081 <span class="comment">/* Set status as ARM_MATH_SIZE_MISMATCH */</span>
<a name="l00082"></a>00082 status = <a class="code" href="arm__math_8h.html#a5e459c6409dfcd2927bb8a57491d7cf6a7071b92f1f6bc3c5c312a237ea91105b">ARM_MATH_SIZE_MISMATCH</a>;
<a name="l00083"></a>00083 }
<a name="l00084"></a>00084 <span class="keywordflow">else</span>
<a name="l00085"></a>00085 <span class="preprocessor">#endif </span><span class="comment">/* #ifdef ARM_MATH_MATRIX_CHECK */</span>
<a name="l00086"></a>00086
<a name="l00087"></a>00087 {
<a name="l00088"></a>00088 <span class="comment">/* Total number of samples in the input matrix */</span>
<a name="l00089"></a>00089 numSamples = (uint16_t) (pSrcA-><a class="code" href="structarm__matrix__instance__q15.html#a9bac6ed54be287c4d4f01a1a28be65f5">numRows</a> * pSrcA-><a class="code" href="structarm__matrix__instance__q15.html#acbbce67ba058d8e1c867c71d57288c97">numCols</a>);
<a name="l00090"></a>00090
<a name="l00091"></a>00091 <span class="preprocessor">#ifndef ARM_MATH_CM0</span>
<a name="l00092"></a>00092 <span class="preprocessor"></span>
<a name="l00093"></a>00093 <span class="comment">/* Run the below code for Cortex-M4 and Cortex-M3 */</span>
<a name="l00094"></a>00094
<a name="l00095"></a>00095 <span class="comment">/* Loop unrolling */</span>
<a name="l00096"></a>00096 blkCnt = (uint32_t) numSamples >> 2u;
<a name="l00097"></a>00097
<a name="l00098"></a>00098 <span class="comment">/* First part of the processing with loop unrolling. Compute 4 outputs at a time. </span>
<a name="l00099"></a>00099 <span class="comment"> ** a second loop below computes the remaining 1 to 3 samples. */</span>
<a name="l00100"></a>00100 <span class="keywordflow">while</span>(blkCnt > 0u)
<a name="l00101"></a>00101 {
<a name="l00102"></a>00102 <span class="comment">/* C(m,n) = A(m,n) + B(m,n) */</span>
<a name="l00103"></a>00103 <span class="comment">/* Add, Saturate and then store the results in the destination buffer. */</span>
<a name="l00104"></a>00104 *<a class="code" href="arm__math_8h.html#a9de2e0a5785be82866bcb96012282248" title="definition to read/write two 16 bit values.">__SIMD32</a>(pOut)++ = __QADD16(*<a class="code" href="arm__math_8h.html#a9de2e0a5785be82866bcb96012282248" title="definition to read/write two 16 bit values.">__SIMD32</a>(pInA)++, *<a class="code" href="arm__math_8h.html#a9de2e0a5785be82866bcb96012282248" title="definition to read/write two 16 bit values.">__SIMD32</a>(pInB)++);
<a name="l00105"></a>00105 *<a class="code" href="arm__math_8h.html#a9de2e0a5785be82866bcb96012282248" title="definition to read/write two 16 bit values.">__SIMD32</a>(pOut)++ = __QADD16(*<a class="code" href="arm__math_8h.html#a9de2e0a5785be82866bcb96012282248" title="definition to read/write two 16 bit values.">__SIMD32</a>(pInA)++, *<a class="code" href="arm__math_8h.html#a9de2e0a5785be82866bcb96012282248" title="definition to read/write two 16 bit values.">__SIMD32</a>(pInB)++);
<a name="l00106"></a>00106
<a name="l00107"></a>00107 <span class="comment">/* Decrement the loop counter */</span>
<a name="l00108"></a>00108 blkCnt--;
<a name="l00109"></a>00109 }
<a name="l00110"></a>00110
<a name="l00111"></a>00111 <span class="comment">/* If the blockSize is not a multiple of 4, compute any remaining output samples here. </span>
<a name="l00112"></a>00112 <span class="comment"> ** No loop unrolling is used. */</span>
<a name="l00113"></a>00113 blkCnt = (uint32_t) numSamples % 0x4u;
<a name="l00114"></a>00114
<a name="l00115"></a>00115 <span class="comment">/* q15 pointers of input and output are initialized */</span>
<a name="l00116"></a>00116
<a name="l00117"></a>00117 <span class="keywordflow">while</span>(blkCnt > 0u)
<a name="l00118"></a>00118 {
<a name="l00119"></a>00119 <span class="comment">/* C(m,n) = A(m,n) + B(m,n) */</span>
<a name="l00120"></a>00120 <span class="comment">/* Add, Saturate and then store the results in the destination buffer. */</span>
<a name="l00121"></a>00121 *pOut++ = (<a class="code" href="arm__math_8h.html#ab5a8fb21a5b3b983d5f54f31614052ea" title="16-bit fractional data type in 1.15 format.">q15_t</a>) __QADD16(*pInA++, *pInB++);
<a name="l00122"></a>00122
<a name="l00123"></a>00123 <span class="comment">/* Decrement the loop counter */</span>
<a name="l00124"></a>00124 blkCnt--;
<a name="l00125"></a>00125 }
<a name="l00126"></a>00126
<a name="l00127"></a>00127 <span class="preprocessor">#else</span>
<a name="l00128"></a>00128 <span class="preprocessor"></span>
<a name="l00129"></a>00129 <span class="comment">/* Run the below code for Cortex-M0 */</span>
<a name="l00130"></a>00130
<a name="l00131"></a>00131 <span class="comment">/* Initialize blkCnt with number of samples */</span>
<a name="l00132"></a>00132 blkCnt = (uint32_t) numSamples;
<a name="l00133"></a>00133
<a name="l00134"></a>00134
<a name="l00135"></a>00135 <span class="comment">/* q15 pointers of input and output are initialized */</span>
<a name="l00136"></a>00136 <span class="keywordflow">while</span>(blkCnt > 0u)
<a name="l00137"></a>00137 {
<a name="l00138"></a>00138 <span class="comment">/* C(m,n) = A(m,n) + B(m,n) */</span>
<a name="l00139"></a>00139 <span class="comment">/* Add, Saturate and then store the results in the destination buffer. */</span>
<a name="l00140"></a>00140 *pOut++ = (<a class="code" href="arm__math_8h.html#ab5a8fb21a5b3b983d5f54f31614052ea" title="16-bit fractional data type in 1.15 format.">q15_t</a>) __SSAT(((<a class="code" href="arm__math_8h.html#adc89a3547f5324b7b3b95adec3806bc0" title="32-bit fractional data type in 1.31 format.">q31_t</a>) * pInA++ + *pInB++), 16);
<a name="l00141"></a>00141
<a name="l00142"></a>00142 <span class="comment">/* Decrement the loop counter */</span>
<a name="l00143"></a>00143 blkCnt--;
<a name="l00144"></a>00144 }
<a name="l00145"></a>00145
<a name="l00146"></a>00146 <span class="preprocessor">#endif </span><span class="comment">/* #ifndef ARM_MATH_CM0 */</span>
<a name="l00147"></a>00147
<a name="l00148"></a>00148 <span class="comment">/* set status as ARM_MATH_SUCCESS */</span>
<a name="l00149"></a>00149 status = <a class="code" href="arm__math_8h.html#a5e459c6409dfcd2927bb8a57491d7cf6a9f8b2a10bd827fb4600e77d455902eb0">ARM_MATH_SUCCESS</a>;
<a name="l00150"></a>00150 }
<a name="l00151"></a>00151
<a name="l00152"></a>00152 <span class="comment">/* Return to application */</span>
<a name="l00153"></a>00153 <span class="keywordflow">return</span> (status);
<a name="l00154"></a>00154 }
<a name="l00155"></a>00155
</pre></div></div>
</div>
<!--- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
<a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark"> </span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark"> </span>Data Structures</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark"> </span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark"> </span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark"> </span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark"> </span>Typedefs</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(6)"><span class="SelectionMark"> </span>Enumerations</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(7)"><span class="SelectionMark"> </span>Enumerator</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(8)"><span class="SelectionMark"> </span>Defines</a></div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<hr class="footer"/><address class="footer"><small>Generated on Fri Jul 15 2011 13:16:16 for CMSIS DSP Software Library by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.2 </small></address>
</body>
</html>
| chcbaram/CupDrone_IDE | hardware/steammaker/CupDrone/system/CMSIS/CMSIS/Documentation/DSP_Lib/html/arm__mat__add__q15_8c_source.html | HTML | mit | 18,706 |
/**
* http://github.com/Widen/fine-uploader
*
* Multiple file upload component with progress-bar, drag-and-drop, support for all modern browsers.
*
* Copyright © 2013, Widen Enterprises info@fineupoader.com
*
* Version: -unstable-
*
* Licensed under GNU GPL v3, see license.txt.
*/
/*globals window, navigator, document, FormData, File, HTMLInputElement, XMLHttpRequest, Blob*/
var qq = function(element) {
"use strict";
return {
hide: function() {
element.style.display = 'none';
return this;
},
/** Returns the function which detaches attached event */
attach: function(type, fn) {
if (element.addEventListener){
element.addEventListener(type, fn, false);
} else if (element.attachEvent){
element.attachEvent('on' + type, fn);
}
return function() {
qq(element).detach(type, fn);
};
},
detach: function(type, fn) {
if (element.removeEventListener){
element.removeEventListener(type, fn, false);
} else if (element.attachEvent){
element.detachEvent('on' + type, fn);
}
return this;
},
contains: function(descendant) {
// compareposition returns false in this case
if (element === descendant) {
return true;
}
if (element.contains){
return element.contains(descendant);
} else {
/*jslint bitwise: true*/
return !!(descendant.compareDocumentPosition(element) & 8);
}
},
/**
* Insert this element before elementB.
*/
insertBefore: function(elementB) {
elementB.parentNode.insertBefore(element, elementB);
return this;
},
remove: function() {
element.parentNode.removeChild(element);
return this;
},
/**
* Sets styles for an element.
* Fixes opacity in IE6-8.
*/
css: function(styles) {
if (styles.opacity != null){
if (typeof element.style.opacity !== 'string' && typeof(element.filters) !== 'undefined'){
styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')';
}
}
qq.extend(element.style, styles);
return this;
},
hasClass: function(name) {
var re = new RegExp('(^| )' + name + '( |$)');
return re.test(element.className);
},
addClass: function(name) {
if (!qq(element).hasClass(name)){
element.className += ' ' + name;
}
return this;
},
removeClass: function(name) {
var re = new RegExp('(^| )' + name + '( |$)');
element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, "");
return this;
},
getByClass: function(className) {
var candidates,
result = [];
if (element.querySelectorAll){
return element.querySelectorAll('.' + className);
}
candidates = element.getElementsByTagName("*");
qq.each(candidates, function(idx, val) {
if (qq(val).hasClass(className)){
result.push(val);
}
});
return result;
},
children: function() {
var children = [],
child = element.firstChild;
while (child){
if (child.nodeType === 1){
children.push(child);
}
child = child.nextSibling;
}
return children;
},
setText: function(text) {
element.innerText = text;
element.textContent = text;
return this;
},
clearText: function() {
return qq(element).setText("");
}
};
};
qq.log = function(message, level) {
"use strict";
if (window.console) {
if (!level || level === 'info') {
window.console.log(message);
}
else
{
if (window.console[level]) {
window.console[level](message);
}
else {
window.console.log('<' + level + '> ' + message);
}
}
}
};
qq.isObject = function(variable) {
"use strict";
return variable && !variable.nodeType && Object.prototype.toString.call(variable) === '[object Object]';
};
qq.isFunction = function(variable) {
"use strict";
return typeof(variable) === "function";
};
qq.isArray = function(variable) {
"use strict";
return Object.prototype.toString.call(variable) === "[object Array]";
}
qq.isString = function(maybeString) {
"use strict";
return Object.prototype.toString.call(maybeString) === '[object String]';
};
qq.trimStr = function(string) {
if (String.prototype.trim) {
return string.trim();
}
return string.replace(/^\s+|\s+$/g,'');
};
qq.isFile = function(maybeFile) {
"use strict";
return window.File && Object.prototype.toString.call(maybeFile) === '[object File]'
};
qq.isFileList = function(maybeFileList) {
return window.FileList && Object.prototype.toString.call(maybeFileList) === '[object FileList]'
}
qq.isFileOrInput = function(maybeFileOrInput) {
"use strict";
return qq.isFile(maybeFileOrInput) || qq.isInput(maybeFileOrInput);
};
qq.isInput = function(maybeInput) {
if (window.HTMLInputElement) {
if (Object.prototype.toString.call(maybeInput) === '[object HTMLInputElement]') {
if (maybeInput.type && maybeInput.type.toLowerCase() === 'file') {
return true;
}
}
}
if (maybeInput.tagName) {
if (maybeInput.tagName.toLowerCase() === 'input') {
if (maybeInput.type && maybeInput.type.toLowerCase() === 'file') {
return true;
}
}
}
return false;
};
qq.isBlob = function(maybeBlob) {
"use strict";
return window.Blob && Object.prototype.toString.call(maybeBlob) === '[object Blob]';
};
qq.isXhrUploadSupported = function() {
"use strict";
var input = document.createElement('input');
input.type = 'file';
return (
input.multiple !== undefined &&
typeof File !== "undefined" &&
typeof FormData !== "undefined" &&
typeof (new XMLHttpRequest()).upload !== "undefined" );
};
qq.isFolderDropSupported = function(dataTransfer) {
"use strict";
return (dataTransfer.items && dataTransfer.items[0].webkitGetAsEntry);
};
qq.isFileChunkingSupported = function() {
"use strict";
return !qq.android() && //android's impl of Blob.slice is broken
qq.isXhrUploadSupported() &&
(File.prototype.slice !== undefined || File.prototype.webkitSlice !== undefined || File.prototype.mozSlice !== undefined);
};
qq.extend = function (first, second, extendNested) {
"use strict";
qq.each(second, function(prop, val) {
if (extendNested && qq.isObject(val)) {
if (first[prop] === undefined) {
first[prop] = {};
}
qq.extend(first[prop], val, true);
}
else {
first[prop] = val;
}
});
return first;
};
/**
* Searches for a given element in the array, returns -1 if it is not present.
* @param {Number} [from] The index at which to begin the search
*/
qq.indexOf = function(arr, elt, from){
"use strict";
if (arr.indexOf) {
return arr.indexOf(elt, from);
}
from = from || 0;
var len = arr.length;
if (from < 0) {
from += len;
}
for (; from < len; from+=1){
if (arr.hasOwnProperty(from) && arr[from] === elt){
return from;
}
}
return -1;
};
//this is a version 4 UUID
qq.getUniqueId = function(){
"use strict";
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
/*jslint eqeq: true, bitwise: true*/
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
};
//
// Browsers and platforms detection
qq.ie = function(){
"use strict";
return navigator.userAgent.indexOf('MSIE') !== -1;
};
qq.ie10 = function(){
"use strict";
return navigator.userAgent.indexOf('MSIE 10') !== -1;
};
qq.safari = function(){
"use strict";
return navigator.vendor !== undefined && navigator.vendor.indexOf("Apple") !== -1;
};
qq.chrome = function(){
"use strict";
return navigator.vendor !== undefined && navigator.vendor.indexOf('Google') !== -1;
};
qq.firefox = function(){
"use strict";
return (navigator.userAgent.indexOf('Mozilla') !== -1 && navigator.vendor !== undefined && navigator.vendor === '');
};
qq.windows = function(){
"use strict";
return navigator.platform === "Win32";
};
qq.android = function(){
"use strict";
return navigator.userAgent.toLowerCase().indexOf('android') !== -1;
};
qq.ios = function() {
"use strict";
return navigator.userAgent.indexOf("iPad") !== -1
|| navigator.userAgent.indexOf("iPod") !== -1
|| navigator.userAgent.indexOf("iPhone") !== -1;
};
//
// Events
qq.preventDefault = function(e){
"use strict";
if (e.preventDefault){
e.preventDefault();
} else{
e.returnValue = false;
}
};
/**
* Creates and returns element from html string
* Uses innerHTML to create an element
*/
qq.toElement = (function(){
"use strict";
var div = document.createElement('div');
return function(html){
div.innerHTML = html;
var element = div.firstChild;
div.removeChild(element);
return element;
};
}());
//key and value are passed to callback for each item in the object or array
qq.each = function(objOrArray, callback) {
"use strict";
var keyOrIndex, retVal;
if (objOrArray) {
if (qq.isArray(objOrArray)) {
for (keyOrIndex = 0; keyOrIndex < objOrArray.length; keyOrIndex++) {
retVal = callback(keyOrIndex, objOrArray[keyOrIndex]);
if (retVal === false) {
break;
}
}
}
else {
for (keyOrIndex in objOrArray) {
if (Object.prototype.hasOwnProperty.call(objOrArray, keyOrIndex)) {
retVal = callback(keyOrIndex, objOrArray[keyOrIndex]);
if (retVal === false) {
break;
}
}
}
}
}
};
//include any args that should be passed to the new function after the context arg
qq.bind = function(oldFunc, context) {
if (qq.isFunction(oldFunc)) {
var args = Array.prototype.slice.call(arguments, 2);
return function() {
if (arguments.length) {
args = args.concat(Array.prototype.slice.call(arguments))
}
return oldFunc.apply(context, args);
};
}
throw new Error("first parameter must be a function!");
};
/**
* obj2url() takes a json-object as argument and generates
* a querystring. pretty much like jQuery.param()
*
* how to use:
*
* `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');`
*
* will result in:
*
* `http://any.url/upload?otherParam=value&a=b&c=d`
*
* @param Object JSON-Object
* @param String current querystring-part
* @return String encoded querystring
*/
qq.obj2url = function(obj, temp, prefixDone){
"use strict";
/*jshint laxbreak: true*/
var i, len,
uristrings = [],
prefix = '&',
add = function(nextObj, i){
var nextTemp = temp
? (/\[\]$/.test(temp)) // prevent double-encoding
? temp
: temp+'['+i+']'
: i;
if ((nextTemp !== 'undefined') && (i !== 'undefined')) {
uristrings.push(
(typeof nextObj === 'object')
? qq.obj2url(nextObj, nextTemp, true)
: (Object.prototype.toString.call(nextObj) === '[object Function]')
? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj())
: encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj)
);
}
};
if (!prefixDone && temp) {
prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?';
uristrings.push(temp);
uristrings.push(qq.obj2url(obj));
} else if ((Object.prototype.toString.call(obj) === '[object Array]') && (typeof obj !== 'undefined') ) {
// we wont use a for-in-loop on an array (performance)
for (i = -1, len = obj.length; i < len; i+=1){
add(obj[i], i);
}
} else if ((typeof obj !== 'undefined') && (obj !== null) && (typeof obj === "object")){
// for anything else but a scalar, we will use for-in-loop
for (i in obj){
if (obj.hasOwnProperty(i)) {
add(obj[i], i);
}
}
} else {
uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj));
}
if (temp) {
return uristrings.join(prefix);
} else {
return uristrings.join(prefix)
.replace(/^&/, '')
.replace(/%20/g, '+');
}
};
qq.obj2FormData = function(obj, formData, arrayKeyName) {
"use strict";
if (!formData) {
formData = new FormData();
}
qq.each(obj, function(key, val) {
key = arrayKeyName ? arrayKeyName + '[' + key + ']' : key;
if (qq.isObject(val)) {
qq.obj2FormData(val, formData, key);
}
else if (qq.isFunction(val)) {
formData.append(key, val());
}
else {
formData.append(key, val);
}
});
return formData;
};
qq.obj2Inputs = function(obj, form) {
"use strict";
var input;
if (!form) {
form = document.createElement('form');
}
qq.obj2FormData(obj, {
append: function(key, val) {
input = document.createElement('input');
input.setAttribute('name', key);
input.setAttribute('value', val);
form.appendChild(input);
}
});
return form;
};
qq.setCookie = function(name, value, days) {
var date = new Date(),
expires = "";
if (days) {
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires="+date.toGMTString();
}
document.cookie = name+"="+value+expires+"; path=/";
};
qq.getCookie = function(name) {
var nameEQ = name + "=",
ca = document.cookie.split(';'),
cookie;
qq.each(ca, function(idx, part) {
var cookiePart = part;
while (cookiePart.charAt(0)==' ') {
cookiePart = cookiePart.substring(1, cookiePart.length);
}
if (cookiePart.indexOf(nameEQ) === 0) {
cookie = cookiePart.substring(nameEQ.length, cookiePart.length);
return false;
}
});
return cookie;
};
qq.getCookieNames = function(regexp) {
var cookies = document.cookie.split(';'),
cookieNames = [];
qq.each(cookies, function(idx, cookie) {
cookie = qq.trimStr(cookie);
var equalsIdx = cookie.indexOf("=");
if (cookie.match(regexp)) {
cookieNames.push(cookie.substr(0, equalsIdx));
}
});
return cookieNames;
};
qq.deleteCookie = function(name) {
qq.setCookie(name, "", -1);
};
qq.areCookiesEnabled = function() {
var randNum = Math.random() * 100000,
name = "qqCookieTest:" + randNum;
qq.setCookie(name, 1);
if (qq.getCookie(name)) {
qq.deleteCookie(name);
return true;
}
return false;
};
/**
* Not recommended for use outside of Fine Uploader since this falls back to an unchecked eval if JSON.parse is not
* implemented. For a more secure JSON.parse polyfill, use Douglas Crockford's json2.js.
*/
qq.parseJson = function(json) {
/*jshint evil: true*/
if (window.JSON && qq.isFunction(JSON.parse)) {
return JSON.parse(json);
} else {
return eval("(" + json + ")");
}
};
/**
* A generic module which supports object disposing in dispose() method.
* */
qq.DisposeSupport = function() {
"use strict";
var disposers = [];
return {
/** Run all registered disposers */
dispose: function() {
var disposer;
do {
disposer = disposers.shift();
if (disposer) {
disposer();
}
}
while (disposer);
},
/** Attach event handler and register de-attacher as a disposer */
attach: function() {
var args = arguments;
/*jslint undef:true*/
this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1)));
},
/** Add disposer to the collection */
addDisposer: function(disposeFunction) {
disposers.push(disposeFunction);
}
};
};
qq.version="-unstable-";qq.supportedFeatures = (function() {
var supportsUploading,
supportsAjaxFileUploading,
supportsFolderDrop,
supportsChunking,
supportsResume,
supportsUploadViaPaste,
supportsUploadCors,
supportsDeleteFileCors;
function testSupportsFileInputElement() {
var supported = true,
tempInput;
try {
tempInput = document.createElement('input');
tempInput.type = 'file';
qq(tempInput).hide();
if(tempInput.disabled) {
supported = false;
}
}
catch(ex) {
supported = false;
}
return supported;
}
//only way to test for Filesystem API support since webkit does not expose the DataTransfer interface
function isChrome21OrHigher() {
return qq.chrome() &&
navigator.userAgent.match(/Chrome\/[2][1-9]|Chrome\/[3-9][0-9]/) !== undefined;
}
//only way to test for complete Clipboard API support at this time
function isChrome14OrHigher() {
return qq.chrome() &&
navigator.userAgent.match(/Chrome\/[1][4-9]|Chrome\/[2-9][0-9]/) !== undefined;
}
supportsUploading = testSupportsFileInputElement();
supportsAjaxFileUploading = supportsUploading && qq.isXhrUploadSupported();
supportsFolderDrop = supportsAjaxFileUploading && isChrome21OrHigher();
supportsChunking = supportsAjaxFileUploading && qq.isFileChunkingSupported();
supportsResume = supportsAjaxFileUploading && supportsChunking && qq.areCookiesEnabled();
supportsUploadViaPaste = supportsAjaxFileUploading && isChrome14OrHigher();
supportsUploadCors = supportsUploading && (window.postMessage !== undefined || supportsAjaxFileUploading);
supportsDeleteFileCors = supportsAjaxFileUploading;
return {
uploading: supportsUploading,
ajaxUploading: supportsAjaxFileUploading,
fileDrop: supportsAjaxFileUploading, //NOTE: will also return true for touch-only devices. It's not currently possible to accurately test for touch-only devices
folderDrop: supportsFolderDrop,
chunking: supportsChunking,
resume: supportsResume,
uploadCustomHeaders: supportsAjaxFileUploading,
uploadNonMultipart: supportsAjaxFileUploading,
itemSizeValidation: supportsAjaxFileUploading,
uploadViaPaste: supportsUploadViaPaste,
progressBar: supportsAjaxFileUploading,
uploadCors: supportsUploadCors,
deleteFileCors: supportsDeleteFileCors,
canDetermineSize: supportsAjaxFileUploading
}
}());
/*globals qq*/
qq.Promise = function() {
"use strict";
var successValue, failureValue,
successCallbacks = [],
failureCallbacks = [],
doneCallbacks = [],
state = 0;
return {
then: function(onSuccess, onFailure) {
if (state === 0) {
if (onSuccess) {
successCallbacks.push(onSuccess);
}
if (onFailure) {
failureCallbacks.push(onFailure);
}
}
else if (state === -1 && onFailure) {
onFailure(failureValue);
}
else if (onSuccess) {
onSuccess(successValue);
}
return this;
},
done: function(callback) {
if (state === 0) {
doneCallbacks.push(callback);
}
else {
callback();
}
return this;
},
success: function(val) {
state = 1;
successValue = val;
if (successCallbacks.length) {
qq.each(successCallbacks, function(idx, callback) {
callback(val);
})
}
if(doneCallbacks.length) {
qq.each(doneCallbacks, function(idx, callback) {
callback();
})
}
return this;
},
failure: function(val) {
state = -1;
failureValue = val;
if (failureCallbacks.length) {
qq.each(failureCallbacks, function(idx, callback) {
callback(val);
})
}
if(doneCallbacks.length) {
qq.each(doneCallbacks, function(idx, callback) {
callback();
})
}
return this;
}
};
};
qq.isPromise = function(maybePromise) {
return maybePromise && maybePromise.then && maybePromise.done;
};/*globals qq*/
qq.UploadButton = function(o) {
"use strict";
var input,
disposeSupport = new qq.DisposeSupport(),
options = {
element: null,
// if set to true adds multiple attribute to file input
multiple: false,
acceptFiles: null,
// name attribute of file input
name: 'file',
onChange: function(input) {},
hoverClass: 'qq-upload-button-hover',
focusClass: 'qq-upload-button-focus'
};
function createInput() {
var input = document.createElement("input");
if (options.multiple){
input.setAttribute("multiple", "multiple");
}
if (options.acceptFiles) {
input.setAttribute("accept", options.acceptFiles);
}
input.setAttribute("type", "file");
input.setAttribute("name", options.name);
qq(input).css({
position: 'absolute',
// in Opera only 'browse' button
// is clickable and it is located at
// the right side of the input
right: 0,
top: 0,
fontFamily: 'Arial',
// 4 persons reported this, the max values that worked for them were 243, 236, 236, 118
fontSize: '118px',
margin: 0,
padding: 0,
cursor: 'pointer',
opacity: 0
});
options.element.appendChild(input);
disposeSupport.attach(input, 'change', function(){
options.onChange(input);
});
disposeSupport.attach(input, 'mouseover', function(){
qq(options.element).addClass(options.hoverClass);
});
disposeSupport.attach(input, 'mouseout', function(){
qq(options.element).removeClass(options.hoverClass);
});
disposeSupport.attach(input, 'focus', function(){
qq(options.element).addClass(options.focusClass);
});
disposeSupport.attach(input, 'blur', function(){
qq(options.element).removeClass(options.focusClass);
});
// IE and Opera, unfortunately have 2 tab stops on file input
// which is unacceptable in our case, disable keyboard access
if (window.attachEvent){
// it is IE or Opera
input.setAttribute('tabIndex', "-1");
}
return input;
}
qq.extend(options, o);
// make button suitable container for input
qq(options.element).css({
position: 'relative',
overflow: 'hidden',
// Make sure browse button is in the right side
// in Internet Explorer
direction: 'ltr'
});
input = createInput();
return {
getInput: function(){
return input;
},
reset: function(){
if (input.parentNode){
qq(input).remove();
}
qq(options.element).removeClass(options.focusClass);
input = createInput();
}
};
};
/*globals qq*/
qq.PasteSupport = function(o) {
"use strict";
var options, detachPasteHandler;
options = {
targetElement: null,
callbacks: {
log: function(message, level) {},
pasteReceived: function(blob) {}
}
};
function isImage(item) {
return item.type &&
item.type.indexOf("image/") === 0;
}
function registerPasteHandler() {
qq(options.targetElement).attach("paste", function(event) {
var clipboardData = event.clipboardData;
if (clipboardData) {
qq.each(clipboardData.items, function(idx, item) {
if (isImage(item)) {
var blob = item.getAsFile();
options.callbacks.pasteReceived(blob);
}
});
}
});
}
function unregisterPasteHandler() {
if (detachPasteHandler) {
detachPasteHandler();
}
}
qq.extend(options, o);
registerPasteHandler();
return {
reset: function() {
unregisterPasteHandler();
}
};
};qq.UploadData = function(uploaderProxy) {
var data = [],
byId = {},
byUuid = {},
byStatus = {},
api;
function getDataByIds(ids) {
if (qq.isArray(ids)) {
var entries = [];
qq.each(ids, function(idx, id) {
entries.push(data[byId[id]]);
});
return entries;
}
return data[byId[ids]];
}
function getDataByUuids(uuids) {
if (qq.isArray(uuids)) {
var entries = [];
qq.each(uuids, function(idx, uuid) {
entries.push(data[byUuid[uuid]]);
});
return entries;
}
return data[byUuid[uuids]];
}
function getDataByStatus(status) {
var statusResults = [],
statuses = [].concat(status);
qq.each(statuses, function(index, statusEnum) {
var statusResultIndexes = byStatus[statusEnum];
if (statusResultIndexes !== undefined) {
qq.each(statusResultIndexes, function(i, dataIndex) {
statusResults.push(data[dataIndex]);
});
}
});
return statusResults;
}
api = {
added: function(id) {
var uuid = uploaderProxy.getUuid(id),
name = uploaderProxy.getName(id),
size = uploaderProxy.getSize(id),
status = qq.status.SUBMITTING;
var index = data.push({
id: id,
name: name,
uuid: uuid,
size: size,
status: status
}) - 1;
byId[id] = index;
byUuid[uuid] = index;
if (byStatus[status] === undefined) {
byStatus[status] = [];
}
byStatus[status].push(index);
uploaderProxy.onStatusChange(id, undefined, status);
},
retrieve: function(optionalFilter) {
if (qq.isObject(optionalFilter) && data.length) {
if (optionalFilter.id !== undefined) {
return getDataByIds(optionalFilter.id);
}
else if (optionalFilter.uuid !== undefined) {
return getDataByUuids(optionalFilter.uuid);
}
else if (optionalFilter.status) {
return getDataByStatus(optionalFilter.status);
}
}
else {
return qq.extend([], data, true);
}
},
reset: function() {
data = [];
byId = {};
byUuid = {};
byStatus = {};
},
setStatus: function(id, newStatus) {
var dataIndex = byId[id],
oldStatus = data[dataIndex].status,
byStatusOldStatusIndex = qq.indexOf(byStatus[oldStatus], dataIndex);
byStatus[oldStatus].splice(byStatusOldStatusIndex, 1);
data[dataIndex].status = newStatus;
if (byStatus[newStatus] === undefined) {
byStatus[newStatus] = [];
}
byStatus[newStatus].push(dataIndex);
uploaderProxy.onStatusChange(id, oldStatus, newStatus);
},
uuidChanged: function(id, newUuid) {
var dataIndex = byId[id],
oldUuid = data[dataIndex].uuid;
data[dataIndex].uuid = newUuid;
byUuid[newUuid] = dataIndex;
delete byUuid[oldUuid];
}
};
return api;
};
qq.status = {
SUBMITTING: "submitting",
SUBMITTED: "submitted",
REJECTED: "rejected",
QUEUED: "queued",
CANCELED: "canceled",
UPLOADING: "uploading",
UPLOAD_RETRYING: "retrying upload",
UPLOAD_SUCCESSFUL: "upload successful",
UPLOAD_FAILED: "upload failed",
DELETE_FAILED: "delete failed",
DELETING: "deleting",
DELETED: "deleted"
};qq.FineUploaderBasic = function(o) {
this._options = {
debug: false,
button: null,
multiple: true,
maxConnections: 3,
disableCancelForFormUploads: false,
autoUpload: true,
request: {
endpoint: '/server/upload',
params: {},
paramsInBody: true,
customHeaders: {},
forceMultipart: true,
inputName: 'qqfile',
uuidName: 'qquuid',
totalFileSizeName: 'qqtotalfilesize'
},
validation: {
allowedExtensions: [],
sizeLimit: 0,
minSizeLimit: 0,
itemLimit: 0,
stopOnFirstInvalidFile: true,
acceptFiles: null
},
callbacks: {
onSubmit: function(id, name){},
onSubmitted: function(id, name){},
onComplete: function(id, name, responseJSON, maybeXhr){},
onCancel: function(id, name){},
onUpload: function(id, name){},
onUploadChunk: function(id, name, chunkData){},
onResume: function(id, fileName, chunkData){},
onProgress: function(id, name, loaded, total){},
onError: function(id, name, reason, maybeXhr) {},
onAutoRetry: function(id, name, attemptNumber) {},
onManualRetry: function(id, name) {},
onValidateBatch: function(fileOrBlobData) {},
onValidate: function(fileOrBlobData) {},
onSubmitDelete: function(id) {},
onDelete: function(id){},
onDeleteComplete: function(id, xhr, isError){},
onPasteReceived: function(blob) {},
onStatusChange: function(id, oldStatus, newStatus) {}
},
messages: {
typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.",
sizeError: "{file} is too large, maximum file size is {sizeLimit}.",
minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.",
emptyError: "{file} is empty, please select files again without it.",
noFilesError: "No files to upload.",
tooManyItemsError: "Too many items ({netItems}) would be uploaded. Item limit is {itemLimit}.",
retryFailTooManyItems: "Retry failed - you have reached your file limit.",
onLeave: "The files are being uploaded, if you leave now the upload will be cancelled."
},
retry: {
enableAuto: false,
maxAutoAttempts: 3,
autoAttemptDelay: 5,
preventRetryResponseProperty: 'preventRetry'
},
classes: {
buttonHover: 'qq-upload-button-hover',
buttonFocus: 'qq-upload-button-focus'
},
chunking: {
enabled: false,
partSize: 2000000,
paramNames: {
partIndex: 'qqpartindex',
partByteOffset: 'qqpartbyteoffset',
chunkSize: 'qqchunksize',
totalFileSize: 'qqtotalfilesize',
totalParts: 'qqtotalparts',
filename: 'qqfilename'
}
},
resume: {
enabled: false,
id: null,
cookiesExpireIn: 7, //days
paramNames: {
resuming: "qqresume"
}
},
formatFileName: function(fileOrBlobName) {
if (fileOrBlobName.length > 33) {
fileOrBlobName = fileOrBlobName.slice(0, 19) + '...' + fileOrBlobName.slice(-14);
}
return fileOrBlobName;
},
text: {
defaultResponseError: "Upload failure reason unknown",
sizeSymbols: ['kB', 'MB', 'GB', 'TB', 'PB', 'EB']
},
deleteFile : {
enabled: false,
endpoint: '/server/upload',
customHeaders: {},
params: {}
},
cors: {
expected: false,
sendCredentials: false
},
blobs: {
defaultName: 'misc_data',
paramNames: {
name: 'qqblobname'
}
},
paste: {
targetElement: null,
defaultName: 'pasted_image'
},
camera: {
ios: false
}
};
qq.extend(this._options, o, true);
this._handleCameraAccess();
this._wrapCallbacks();
this._disposeSupport = new qq.DisposeSupport();
this._filesInProgress = [];
this._storedIds = [];
this._autoRetries = [];
this._retryTimeouts = [];
this._preventRetries = [];
this._netUploadedOrQueued = 0;
this._netUploaded = 0;
this._uploadData = this._createUploadDataTracker();
this._paramsStore = this._createParamsStore("request");
this._deleteFileParamsStore = this._createParamsStore("deleteFile");
this._endpointStore = this._createEndpointStore("request");
this._deleteFileEndpointStore = this._createEndpointStore("deleteFile");
this._handler = this._createUploadHandler();
this._deleteHandler = this._createDeleteHandler();
if (this._options.button){
this._button = this._createUploadButton(this._options.button);
}
if (this._options.paste.targetElement) {
this._pasteHandler = this._createPasteHandler();
}
this._preventLeaveInProgress();
};
qq.FineUploaderBasic.prototype = {
log: function(str, level) {
if (this._options.debug && (!level || level === 'info')) {
qq.log('[FineUploader ' + qq.version + '] ' + str);
}
else if (level && level !== 'info') {
qq.log('[FineUploader ' + qq.version + '] ' + str, level);
}
},
setParams: function(params, id) {
/*jshint eqeqeq: true, eqnull: true*/
if (id == null) {
this._options.request.params = params;
}
else {
this._paramsStore.setParams(params, id);
}
},
setDeleteFileParams: function(params, id) {
/*jshint eqeqeq: true, eqnull: true*/
if (id == null) {
this._options.deleteFile.params = params;
}
else {
this._deleteFileParamsStore.setParams(params, id);
}
},
setEndpoint: function(endpoint, id) {
/*jshint eqeqeq: true, eqnull: true*/
if (id == null) {
this._options.request.endpoint = endpoint;
}
else {
this._endpointStore.setEndpoint(endpoint, id);
}
},
getInProgress: function() {
return this._filesInProgress.length;
},
getNetUploads: function() {
return this._netUploaded;
},
uploadStoredFiles: function(){
"use strict";
var idToUpload;
while(this._storedIds.length) {
idToUpload = this._storedIds.shift();
this._filesInProgress.push(idToUpload);
this._handler.upload(idToUpload);
}
},
clearStoredFiles: function(){
this._storedIds = [];
},
retry: function(id) {
if (this._onBeforeManualRetry(id)) {
this._netUploadedOrQueued++;
this._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
this._handler.retry(id);
return true;
}
else {
return false;
}
},
cancel: function(id) {
this._handler.cancel(id);
},
cancelAll: function() {
var storedIdsCopy = [],
self = this;
qq.extend(storedIdsCopy, this._storedIds);
qq.each(storedIdsCopy, function(idx, storedFileId) {
self.cancel(storedFileId);
});
this._handler.cancelAll();
},
reset: function() {
this.log("Resetting uploader...");
this._handler.reset();
this._filesInProgress = [];
this._storedIds = [];
this._autoRetries = [];
this._retryTimeouts = [];
this._preventRetries = [];
this._button.reset();
this._paramsStore.reset();
this._endpointStore.reset();
this._netUploadedOrQueued = 0;
this._netUploaded = 0;
this._uploadData.reset();
if (this._pasteHandler) {
this._pasteHandler.reset();
}
},
addFiles: function(filesOrInputs, params, endpoint) {
var self = this,
verifiedFilesOrInputs = [],
fileOrInputIndex, fileOrInput, fileIndex;
if (filesOrInputs) {
if (!qq.isFileList(filesOrInputs)) {
filesOrInputs = [].concat(filesOrInputs);
}
for (fileOrInputIndex = 0; fileOrInputIndex < filesOrInputs.length; fileOrInputIndex+=1) {
fileOrInput = filesOrInputs[fileOrInputIndex];
if (qq.isFileOrInput(fileOrInput)) {
if (qq.isInput(fileOrInput) && qq.supportedFeatures.ajaxUploading) {
for (fileIndex = 0; fileIndex < fileOrInput.files.length; fileIndex++) {
verifiedFilesOrInputs.push(fileOrInput.files[fileIndex]);
}
}
else {
verifiedFilesOrInputs.push(fileOrInput);
}
}
else {
self.log(fileOrInput + ' is not a File or INPUT element! Ignoring!', 'warn');
}
}
this.log('Received ' + verifiedFilesOrInputs.length + ' files or inputs.');
this._prepareItemsForUpload(verifiedFilesOrInputs, params, endpoint);
}
},
addBlobs: function(blobDataOrArray, params, endpoint) {
if (blobDataOrArray) {
var blobDataArray = [].concat(blobDataOrArray),
verifiedBlobDataList = [],
self = this;
qq.each(blobDataArray, function(idx, blobData) {
if (qq.isBlob(blobData) && !qq.isFileOrInput(blobData)) {
verifiedBlobDataList.push({
blob: blobData,
name: self._options.blobs.defaultName
});
}
else if (qq.isObject(blobData) && blobData.blob && blobData.name) {
verifiedBlobDataList.push(blobData);
}
else {
self.log("addBlobs: entry at index " + idx + " is not a Blob or a BlobData object", "error");
}
});
this._prepareItemsForUpload(verifiedBlobDataList, params, endpoint);
}
else {
this.log("undefined or non-array parameter passed into addBlobs", "error");
}
},
getUuid: function(id) {
return this._handler.getUuid(id);
},
getResumableFilesData: function() {
return this._handler.getResumableFilesData();
},
getSize: function(id) {
return this._handler.getSize(id);
},
getName: function(id) {
return this._handler.getName(id);
},
getFile: function(fileOrBlobId) {
return this._handler.getFile(fileOrBlobId);
},
deleteFile: function(id) {
this._onSubmitDelete(id);
},
setDeleteFileEndpoint: function(endpoint, id) {
/*jshint eqeqeq: true, eqnull: true*/
if (id == null) {
this._options.deleteFile.endpoint = endpoint;
}
else {
this._deleteFileEndpointStore.setEndpoint(endpoint, id);
}
},
doesExist: function(fileOrBlobId) {
return this._handler.isValid(fileOrBlobId);
},
getUploads: function(optionalFilter) {
return this._uploadData.retrieve(optionalFilter);
},
_handleCheckedCallback: function(details) {
var self = this,
callbackRetVal = details.callback();
if (qq.isPromise(callbackRetVal)) {
this.log(details.name + " - waiting for " + details.name + " promise to be fulfilled for " + details.identifier);
return callbackRetVal.then(
function(successParam) {
self.log(details.name + " promise success for " + details.identifier);
details.onSuccess(successParam);
},
function() {
if (details.onFailure) {
self.log(details.name + " promise failure for " + details.identifier);
details.onFailure();
}
else {
self.log(details.name + " promise failure for " + details.identifier);
}
});
}
if (callbackRetVal !== false) {
details.onSuccess(callbackRetVal);
}
else {
if (details.onFailure) {
this.log(details.name + " - return value was 'false' for " + details.identifier + ". Invoking failure callback.")
details.onFailure();
}
else {
this.log(details.name + " - return value was 'false' for " + details.identifier + ". Will not proceed.")
}
}
return callbackRetVal;
},
_createUploadButton: function(element){
var self = this;
var button = new qq.UploadButton({
element: element,
multiple: this._options.multiple && qq.supportedFeatures.ajaxUploading,
acceptFiles: this._options.validation.acceptFiles,
onChange: function(input){
self._onInputChange(input);
},
hoverClass: this._options.classes.buttonHover,
focusClass: this._options.classes.buttonFocus
});
this._disposeSupport.addDisposer(function() { button.dispose(); });
return button;
},
_createUploadHandler: function(){
var self = this;
return new qq.UploadHandler({
debug: this._options.debug,
forceMultipart: this._options.request.forceMultipart,
maxConnections: this._options.maxConnections,
customHeaders: this._options.request.customHeaders,
inputName: this._options.request.inputName,
uuidParamName: this._options.request.uuidName,
totalFileSizeParamName: this._options.request.totalFileSizeName,
cors: this._options.cors,
demoMode: this._options.demoMode,
paramsInBody: this._options.request.paramsInBody,
paramsStore: this._paramsStore,
endpointStore: this._endpointStore,
chunking: this._options.chunking,
resume: this._options.resume,
blobs: this._options.blobs,
log: function(str, level) {
self.log(str, level);
},
onProgress: function(id, name, loaded, total){
self._onProgress(id, name, loaded, total);
self._options.callbacks.onProgress(id, name, loaded, total);
},
onComplete: function(id, name, result, xhr){
self._onComplete(id, name, result, xhr);
self._options.callbacks.onComplete(id, name, result, xhr);
},
onCancel: function(id, name) {
return self._handleCheckedCallback({
name: "onCancel",
callback: qq.bind(self._options.callbacks.onCancel, self, id, name),
onSuccess: qq.bind(self._onCancel, self, id, name),
identifier: id
});
},
onUpload: function(id, name){
self._onUpload(id, name);
self._options.callbacks.onUpload(id, name);
},
onUploadChunk: function(id, name, chunkData){
self._options.callbacks.onUploadChunk(id, name, chunkData);
},
onResume: function(id, name, chunkData) {
return self._options.callbacks.onResume(id, name, chunkData);
},
onAutoRetry: function(id, name, responseJSON, xhr) {
self._preventRetries[id] = responseJSON[self._options.retry.preventRetryResponseProperty];
if (self._shouldAutoRetry(id, name, responseJSON)) {
self._maybeParseAndSendUploadError(id, name, responseJSON, xhr);
self._options.callbacks.onAutoRetry(id, name, self._autoRetries[id] + 1);
self._onBeforeAutoRetry(id, name);
self._retryTimeouts[id] = setTimeout(function() {
self._onAutoRetry(id, name, responseJSON)
}, self._options.retry.autoAttemptDelay * 1000);
return true;
}
else {
return false;
}
},
onUuidChanged: function(id, newUuid) {
self._uploadData.uuidChanged(id, newUuid);
}
});
},
_createDeleteHandler: function() {
var self = this;
return new qq.DeleteFileAjaxRequestor({
maxConnections: this._options.maxConnections,
customHeaders: this._options.deleteFile.customHeaders,
paramsStore: this._deleteFileParamsStore,
endpointStore: this._deleteFileEndpointStore,
demoMode: this._options.demoMode,
cors: this._options.cors,
log: function(str, level) {
self.log(str, level);
},
onDelete: function(id) {
self._onDelete(id);
self._options.callbacks.onDelete(id);
},
onDeleteComplete: function(id, xhr, isError) {
self._onDeleteComplete(id, xhr, isError);
self._options.callbacks.onDeleteComplete(id, xhr, isError);
}
});
},
_createPasteHandler: function() {
var self = this;
return new qq.PasteSupport({
targetElement: this._options.paste.targetElement,
callbacks: {
log: function(str, level) {
self.log(str, level);
},
pasteReceived: function(blob) {
self._handleCheckedCallback({
name: "onPasteReceived",
callback: qq.bind(self._options.callbacks.onPasteReceived, self, blob),
onSuccess: qq.bind(self._handlePasteSuccess, self, blob),
identifier: "pasted image"
});
}
}
});
},
_createUploadDataTracker: function() {
var self = this;
return new qq.UploadData({
getName: function(id) {
return self.getName(id);
},
getUuid: function(id) {
return self.getUuid(id);
},
getSize: function(id) {
return self.getSize(id);
},
onStatusChange: function(id, oldStatus, newStatus) {
self._options.callbacks.onStatusChange(id, oldStatus, newStatus);
}
});
},
_handlePasteSuccess: function(blob, extSuppliedName) {
var extension = blob.type.split("/")[1],
name = extSuppliedName;
/*jshint eqeqeq: true, eqnull: true*/
if (name == null) {
name = this._options.paste.defaultName;
}
name += '.' + extension;
this.addBlobs({
name: name,
blob: blob
});
},
_preventLeaveInProgress: function(){
var self = this;
this._disposeSupport.attach(window, 'beforeunload', function(e){
if (!self._filesInProgress.length){return;}
var e = e || window.event;
// for ie, ff
e.returnValue = self._options.messages.onLeave;
// for webkit
return self._options.messages.onLeave;
});
},
_onSubmit: function(id, name) {
this._netUploadedOrQueued++;
if (this._options.autoUpload) {
this._filesInProgress.push(id);
}
},
_onProgress: function(id, name, loaded, total) {
//nothing to do yet in core uploader
},
_onComplete: function(id, name, result, xhr) {
if (!result.success) {
this._uploadData.setStatus(id, qq.status.UPLOAD_FAILED);
this._netUploadedOrQueued--;
}
else {
this._uploadData.setStatus(id, qq.status.UPLOAD_SUCCESSFUL);
this._netUploaded++;
}
this._removeFromFilesInProgress(id);
this._maybeParseAndSendUploadError(id, name, result, xhr);
},
_onCancel: function(id, name) {
this._uploadData.setStatus(id, qq.status.CANCELED);
this._netUploadedOrQueued--;
this._removeFromFilesInProgress(id);
clearTimeout(this._retryTimeouts[id]);
var storedItemIndex = qq.indexOf(this._storedIds, id);
if (!this._options.autoUpload && storedItemIndex >= 0) {
this._storedIds.splice(storedItemIndex, 1);
}
},
_isDeletePossible: function() {
return (this._options.deleteFile.enabled &&
(!this._options.cors.expected || qq.supportedFeatures.deleteFileCors));
},
_onSubmitDelete: function(id, onSuccessCallback) {
if (this._isDeletePossible()) {
return this._handleCheckedCallback({
name: "onSubmitDelete",
callback: qq.bind(this._options.callbacks.onSubmitDelete, this, id),
onSuccess: onSuccessCallback || qq.bind(this._deleteHandler.sendDelete, this, id, this.getUuid(id)),
identifier: id
});
}
else {
this.log("Delete request ignored for ID " + id + ", delete feature is disabled or request not possible " +
"due to CORS on a user agent that does not support pre-flighting.", "warn");
return false;
}
},
_onDelete: function(id) {
this._uploadData.setStatus(id, qq.status.DELETING);
},
_onDeleteComplete: function(id, xhr, isError) {
var name = this._handler.getName(id);
if (isError) {
this._uploadData.setStatus(id, qq.status.DELETE_FAILED);
this.log("Delete request for '" + name + "' has failed.", "error");
this._options.callbacks.onError(id, name, "Delete request failed with response code " + xhr.status, xhr);
}
else {
this._uploadData.setStatus(id, qq.status.DELETED);
this._netUploadedOrQueued--;
this._netUploaded--;
this._handler.expunge(id);
this.log("Delete request for '" + name + "' has succeeded.");
}
},
_removeFromFilesInProgress: function(id) {
var index = qq.indexOf(this._filesInProgress, id);
if (index >= 0) {
this._filesInProgress.splice(index, 1);
}
},
_onUpload: function(id, name) {
this._uploadData.setStatus(id, qq.status.UPLOADING);
},
_onInputChange: function(input){
if (qq.supportedFeatures.ajaxUploading) {
this.addFiles(input.files);
}
else {
this.addFiles(input);
}
this._button.reset();
},
_onBeforeAutoRetry: function(id, name) {
this.log("Waiting " + this._options.retry.autoAttemptDelay + " seconds before retrying " + name + "...");
},
_onAutoRetry: function(id, name, responseJSON) {
this.log("Retrying " + name + "...");
this._autoRetries[id]++;
this._uploadData.setStatus(id, qq.status.UPLOAD_RETRYING);
this._handler.retry(id);
},
_shouldAutoRetry: function(id, name, responseJSON) {
if (!this._preventRetries[id] && this._options.retry.enableAuto) {
if (this._autoRetries[id] === undefined) {
this._autoRetries[id] = 0;
}
return this._autoRetries[id] < this._options.retry.maxAutoAttempts;
}
return false;
},
//return false if we should not attempt the requested retry
_onBeforeManualRetry: function(id) {
var itemLimit = this._options.validation.itemLimit;
if (this._preventRetries[id]) {
this.log("Retries are forbidden for id " + id, 'warn');
return false;
}
else if (this._handler.isValid(id)) {
var fileName = this._handler.getName(id);
if (this._options.callbacks.onManualRetry(id, fileName) === false) {
return false;
}
if (itemLimit > 0 && this._netUploadedOrQueued+1 > itemLimit) {
this._itemError("retryFailTooManyItems", "");
return false;
}
this.log("Retrying upload for '" + fileName + "' (id: " + id + ")...");
this._filesInProgress.push(id);
return true;
}
else {
this.log("'" + id + "' is not a valid file ID", 'error');
return false;
}
},
_maybeParseAndSendUploadError: function(id, name, response, xhr) {
//assuming no one will actually set the response code to something other than 200 and still set 'success' to true
if (!response.success){
if (xhr && xhr.status !== 200 && !response.error) {
this._options.callbacks.onError(id, name, "XHR returned response code " + xhr.status, xhr);
}
else {
var errorReason = response.error ? response.error : this._options.text.defaultResponseError;
this._options.callbacks.onError(id, name, errorReason, xhr);
}
}
},
_prepareItemsForUpload: function(items, params, endpoint) {
var validationDescriptors = this._getValidationDescriptors(items);
this._handleCheckedCallback({
name: "onValidateBatch",
callback: qq.bind(this._options.callbacks.onValidateBatch, this, validationDescriptors),
onSuccess: qq.bind(this._onValidateBatchCallbackSuccess, this, validationDescriptors, items, params, endpoint),
identifier: "batch validation"
});
},
_upload: function(blobOrFileContainer, params, endpoint) {
var id = this._handler.add(blobOrFileContainer),
name = this._handler.getName(id);
this._uploadData.added(id);
if (params) {
this.setParams(params, id);
}
if (endpoint) {
this.setEndpoint(endpoint, id);
}
this._handleCheckedCallback({
name: "onSubmit",
callback: qq.bind(this._options.callbacks.onSubmit, this, id, name),
onSuccess: qq.bind(this._onSubmitCallbackSuccess, this, id, name),
onFailure: qq.bind(this._fileOrBlobRejected, this, id, name),
identifier: id
});
},
_onSubmitCallbackSuccess: function(id, name) {
this._uploadData.setStatus(id, qq.status.SUBMITTED);
this._onSubmit(id, name);
this._options.callbacks.onSubmitted(id, name);
if (this._options.autoUpload) {
if (!this._handler.upload(id)) {
this._uploadData.setStatus(id, qq.status.QUEUED);
}
}
else {
this._storeForLater(id);
}
},
_storeForLater: function(id) {
this._storedIds.push(id);
},
_onValidateBatchCallbackSuccess: function(validationDescriptors, items, params, endpoint) {
var errorMessage,
itemLimit = this._options.validation.itemLimit,
proposedNetFilesUploadedOrQueued = this._netUploadedOrQueued + validationDescriptors.length;
if (itemLimit === 0 || proposedNetFilesUploadedOrQueued <= itemLimit) {
if (items.length > 0) {
this._handleCheckedCallback({
name: "onValidate",
callback: qq.bind(this._options.callbacks.onValidate, this, items[0]),
onSuccess: qq.bind(this._onValidateCallbackSuccess, this, items, 0, params, endpoint),
onFailure: qq.bind(this._onValidateCallbackFailure, this, items, 0, params, endpoint),
identifier: "Item '" + items[0].name + "', size: " + items[0].size
});
}
else {
this._itemError("noFilesError", "");
}
}
else {
errorMessage = this._options.messages.tooManyItemsError
.replace(/\{netItems\}/g, proposedNetFilesUploadedOrQueued)
.replace(/\{itemLimit\}/g, itemLimit);
this._batchError(errorMessage);
}
},
_onValidateCallbackSuccess: function(items, index, params, endpoint) {
var nextIndex = index+1,
validationDescriptor = this._getValidationDescriptor(items[index]),
validItem = false;
if (this._validateFileOrBlobData(items[index], validationDescriptor)) {
validItem = true;
this._upload(items[index], params, endpoint);
}
this._maybeProcessNextItemAfterOnValidateCallback(validItem, items, nextIndex, params, endpoint);
},
_onValidateCallbackFailure: function(items, index, params, endpoint) {
var nextIndex = index+ 1;
this._fileOrBlobRejected(undefined, items[0].name);
this._maybeProcessNextItemAfterOnValidateCallback(false, items, nextIndex, params, endpoint);
},
_maybeProcessNextItemAfterOnValidateCallback: function(validItem, items, index, params, endpoint) {
var self = this;
if (items.length > index) {
if (validItem || !this._options.validation.stopOnFirstInvalidFile) {
//use setTimeout to prevent a stack overflow with a large number of files in the batch & non-promissory callbacks
setTimeout(function() {
var validationDescriptor = self._getValidationDescriptor(items[index]);
self._handleCheckedCallback({
name: "onValidate",
callback: qq.bind(self._options.callbacks.onValidate, self, items[index]),
onSuccess: qq.bind(self._onValidateCallbackSuccess, self, items, index, params, endpoint),
onFailure: qq.bind(self._onValidateCallbackFailure, self, items, index, params, endpoint),
identifier: "Item '" + validationDescriptor.name + "', size: " + validationDescriptor.size
});
}, 0);
}
}
},
_validateFileOrBlobData: function(item, validationDescriptor) {
var name = validationDescriptor.name,
size = validationDescriptor.size,
valid = true;
if (this._options.callbacks.onValidate(validationDescriptor) === false) {
valid = false;
}
if (qq.isFileOrInput(item) && !this._isAllowedExtension(name)){
this._itemError('typeError', name);
valid = false;
}
else if (size === 0){
this._itemError('emptyError', name);
valid = false;
}
else if (size && this._options.validation.sizeLimit && size > this._options.validation.sizeLimit){
this._itemError('sizeError', name);
valid = false;
}
else if (size && size < this._options.validation.minSizeLimit){
this._itemError('minSizeError', name);
valid = false;
}
if (!valid) {
this._fileOrBlobRejected(undefined, name);
}
return valid;
},
_fileOrBlobRejected: function(id, name) {
if (id !== undefined) {
this._uploadData.setStatus(id, qq.status.REJECTED);
}
},
_itemError: function(code, nameOrNames) {
var message = this._options.messages[code],
allowedExtensions = [],
names = [].concat(nameOrNames),
name = names[0],
extensionsForMessage, placeholderMatch;
function r(name, replacement){ message = message.replace(name, replacement); }
qq.each(this._options.validation.allowedExtensions, function(idx, allowedExtension) {
/**
* If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the
* `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details.
*/
if (qq.isString(allowedExtension)) {
allowedExtensions.push(allowedExtension);
}
});
extensionsForMessage = allowedExtensions.join(', ').toLowerCase();
r('{file}', this._options.formatFileName(name));
r('{extensions}', extensionsForMessage);
r('{sizeLimit}', this._formatSize(this._options.validation.sizeLimit));
r('{minSizeLimit}', this._formatSize(this._options.validation.minSizeLimit));
placeholderMatch = message.match(/(\{\w+\})/g);
if (placeholderMatch !== null) {
qq.each(placeholderMatch, function(idx, placeholder) {
r(placeholder, names[idx]);
});
}
this._options.callbacks.onError(null, name, message, undefined);
return message;
},
_batchError: function(message) {
this._options.callbacks.onError(null, null, message, undefined);
},
_isAllowedExtension: function(fileName){
var allowed = this._options.validation.allowedExtensions,
valid = false;
if (!allowed.length) {
return true;
}
qq.each(allowed, function(idx, allowedExt) {
/**
* If an argument is not a string, ignore it. Added when a possible issue with MooTools hijacking the
* `allowedExtensions` array was discovered. See case #735 in the issue tracker for more details.
*/
if (qq.isString(allowedExt)) {
/*jshint eqeqeq: true, eqnull: true*/
var extRegex = new RegExp('\\.' + allowedExt + "$", 'i');
if (fileName.match(extRegex) != null) {
valid = true;
return false;
}
}
});
return valid;
},
_formatSize: function(bytes){
var i = -1;
do {
bytes = bytes / 1000;
i++;
} while (bytes > 999);
return Math.max(bytes, 0.1).toFixed(1) + this._options.text.sizeSymbols[i];
},
_wrapCallbacks: function() {
var self, safeCallback;
self = this;
safeCallback = function(name, callback, args) {
try {
return callback.apply(self, args);
}
catch (exception) {
self.log("Caught exception in '" + name + "' callback - " + exception.message, 'error');
}
};
for (var prop in this._options.callbacks) {
(function() {
var callbackName, callbackFunc;
callbackName = prop;
callbackFunc = self._options.callbacks[callbackName];
self._options.callbacks[callbackName] = function() {
return safeCallback(callbackName, callbackFunc, arguments);
};
}());
}
},
_parseFileOrBlobDataName: function(fileOrBlobData) {
var name;
if (qq.isFileOrInput(fileOrBlobData)) {
if (fileOrBlobData.value) {
// it is a file input
// get input value and remove path to normalize
name = fileOrBlobData.value.replace(/.*(\/|\\)/, "");
} else {
// fix missing properties in Safari 4 and firefox 11.0a2
name = (fileOrBlobData.fileName !== null && fileOrBlobData.fileName !== undefined) ? fileOrBlobData.fileName : fileOrBlobData.name;
}
}
else {
name = fileOrBlobData.name;
}
return name;
},
_parseFileOrBlobDataSize: function(fileOrBlobData) {
var size;
if (qq.isFileOrInput(fileOrBlobData)) {
if (!fileOrBlobData.value){
// fix missing properties in Safari 4 and firefox 11.0a2
size = (fileOrBlobData.fileSize !== null && fileOrBlobData.fileSize !== undefined) ? fileOrBlobData.fileSize : fileOrBlobData.size;
}
}
else {
size = fileOrBlobData.blob.size;
}
return size;
},
_getValidationDescriptor: function(fileOrBlobData) {
var name, size, fileDescriptor;
fileDescriptor = {};
name = this._parseFileOrBlobDataName(fileOrBlobData);
size = this._parseFileOrBlobDataSize(fileOrBlobData);
fileDescriptor.name = name;
if (size !== undefined) {
fileDescriptor.size = size;
}
return fileDescriptor;
},
_getValidationDescriptors: function(files) {
var self = this,
fileDescriptors = [];
qq.each(files, function(idx, file) {
fileDescriptors.push(self._getValidationDescriptor(file));
});
return fileDescriptors;
},
_createParamsStore: function(type) {
var paramsStore = {},
self = this;
return {
setParams: function(params, id) {
var paramsCopy = {};
qq.extend(paramsCopy, params);
paramsStore[id] = paramsCopy;
},
getParams: function(id) {
/*jshint eqeqeq: true, eqnull: true*/
var paramsCopy = {};
if (id != null && paramsStore[id]) {
qq.extend(paramsCopy, paramsStore[id]);
}
else {
qq.extend(paramsCopy, self._options[type].params);
}
return paramsCopy;
},
remove: function(fileId) {
return delete paramsStore[fileId];
},
reset: function() {
paramsStore = {};
}
};
},
_createEndpointStore: function(type) {
var endpointStore = {},
self = this;
return {
setEndpoint: function(endpoint, id) {
endpointStore[id] = endpoint;
},
getEndpoint: function(id) {
/*jshint eqeqeq: true, eqnull: true*/
if (id != null && endpointStore[id]) {
return endpointStore[id];
}
return self._options[type].endpoint;
},
remove: function(fileId) {
return delete endpointStore[fileId];
},
reset: function() {
endpointStore = {};
}
};
},
_handleCameraAccess: function() {
if (this._options.camera.ios && qq.ios()) {
this._options.multiple = false;
if (this._options.validation.acceptFiles === null) {
this._options.validation.acceptFiles = "image/*;capture=camera";
}
else {
this._options.validation.acceptFiles += ",image/*;capture=camera";
}
}
}
};
/*globals qq, document*/
qq.DragAndDrop = function(o) {
"use strict";
var options, dz,
droppedFiles = [],
disposeSupport = new qq.DisposeSupport();
options = {
dropZoneElements: [],
hideDropZonesBeforeEnter: false,
allowMultipleItems: true,
classes: {
dropActive: null
},
callbacks: new qq.DragAndDrop.callbacks()
};
qq.extend(options, o, true);
setupDragDrop();
function uploadDroppedFiles(files) {
options.callbacks.dropLog('Grabbed ' + files.length + " dropped files.");
dz.dropDisabled(false);
options.callbacks.processingDroppedFilesComplete(files);
}
function traverseFileTree(entry) {
var dirReader, i,
parseEntryPromise = new qq.Promise();
if (entry.isFile) {
entry.file(function(file) {
droppedFiles.push(file);
parseEntryPromise.success();
},
function(fileError) {
options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error");
parseEntryPromise.failure();
});
}
else if (entry.isDirectory) {
dirReader = entry.createReader();
dirReader.readEntries(function(entries) {
var entriesLeft = entries.length;
for (i = 0; i < entries.length; i+=1) {
traverseFileTree(entries[i]).done(function() {
entriesLeft-=1;
if (entriesLeft === 0) {
parseEntryPromise.success();
}
});
}
if (!entries.length) {
parseEntryPromise.success();
}
}, function(fileError) {
options.callbacks.dropLog("Problem parsing '" + entry.fullPath + "'. FileError code " + fileError.code + ".", "error");
parseEntryPromise.failure();
});
}
return parseEntryPromise;
}
function handleDataTransfer(dataTransfer) {
var i, items, entry,
pendingFolderPromises = [],
handleDataTransferPromise = new qq.Promise();
options.callbacks.processingDroppedFiles();
dz.dropDisabled(true);
if (dataTransfer.files.length > 1 && !options.allowMultipleItems) {
options.callbacks.processingDroppedFilesComplete([]);
options.callbacks.dropError('tooManyFilesError', "");
dz.dropDisabled(false);
handleDataTransferPromise.failure();
}
else {
droppedFiles = [];
if (qq.isFolderDropSupported(dataTransfer)) {
items = dataTransfer.items;
for (i = 0; i < items.length; i+=1) {
entry = items[i].webkitGetAsEntry();
if (entry) {
//due to a bug in Chrome's File System API impl - #149735
if (entry.isFile) {
droppedFiles.push(items[i].getAsFile());
}
else {
pendingFolderPromises.push(traverseFileTree(entry).done(function() {
pendingFolderPromises.pop();
if (pendingFolderPromises.length === 0) {
handleDataTransferPromise.success();
}
}));
}
}
}
}
else {
droppedFiles = dataTransfer.files;
}
if (pendingFolderPromises.length === 0) {
handleDataTransferPromise.success();
}
}
return handleDataTransferPromise;
}
function setupDropzone(dropArea){
dz = new qq.UploadDropZone({
element: dropArea,
onEnter: function(e){
qq(dropArea).addClass(options.classes.dropActive);
e.stopPropagation();
},
onLeaveNotDescendants: function(e){
qq(dropArea).removeClass(options.classes.dropActive);
},
onDrop: function(e){
if (options.hideDropZonesBeforeEnter) {
qq(dropArea).hide();
}
qq(dropArea).removeClass(options.classes.dropActive);
handleDataTransfer(e.dataTransfer).done(function() {
uploadDroppedFiles(droppedFiles);
});
}
});
disposeSupport.addDisposer(function() {
dz.dispose();
});
if (options.hideDropZonesBeforeEnter) {
qq(dropArea).hide();
}
}
function isFileDrag(dragEvent) {
var fileDrag;
qq.each(dragEvent.dataTransfer.types, function(key, val) {
if (val === 'Files') {
fileDrag = true;
return false;
}
});
return fileDrag;
}
function setupDragDrop(){
var dropZones = options.dropZoneElements;
qq.each(dropZones, function(idx, dropZone) {
setupDropzone(dropZone);
})
// IE <= 9 does not support the File API used for drag+drop uploads
if (dropZones.length && (!qq.ie() || qq.ie10())) {
disposeSupport.attach(document, 'dragenter', function(e) {
if (!dz.dropDisabled() && isFileDrag(e)) {
qq.each(dropZones, function(idx, dropZone) {
qq(dropZone).css({display: 'block'});
});
}
});
}
disposeSupport.attach(document, 'dragleave', function(e){
if (options.hideDropZonesBeforeEnter && qq.FineUploader.prototype._leaving_document_out(e)) {
qq.each(dropZones, function(idx, dropZone) {
qq(dropZone).hide();
});
}
});
disposeSupport.attach(document, 'drop', function(e){
if (options.hideDropZonesBeforeEnter) {
qq.each(dropZones, function(idx, dropZone) {
qq(dropZone).hide();
});
}
e.preventDefault();
});
}
return {
setupExtraDropzone: function(element) {
options.dropZoneElements.push(element);
setupDropzone(element);
},
removeDropzone: function(element) {
var i,
dzs = options.dropZoneElements;
for(i in dzs) {
if (dzs[i] === element) {
return dzs.splice(i, 1);
}
}
},
dispose: function() {
disposeSupport.dispose();
dz.dispose();
}
};
};
qq.DragAndDrop.callbacks = function() {
return {
processingDroppedFiles: function() {},
processingDroppedFilesComplete: function(files) {},
dropError: function(code, errorSpecifics) {
qq.log("Drag & drop error code '" + code + " with these specifics: '" + errorSpecifics + "'", "error");
},
dropLog: function(message, level) {
qq.log(message, level);
}
}
}
qq.UploadDropZone = function(o){
"use strict";
var options, element, preventDrop, dropOutsideDisabled, disposeSupport = new qq.DisposeSupport();
options = {
element: null,
onEnter: function(e){},
onLeave: function(e){},
// is not fired when leaving element by hovering descendants
onLeaveNotDescendants: function(e){},
onDrop: function(e){}
};
qq.extend(options, o);
element = options.element;
function dragover_should_be_canceled(){
return qq.safari() || (qq.firefox() && qq.windows());
}
function disableDropOutside(e){
// run only once for all instances
if (!dropOutsideDisabled ){
// for these cases we need to catch onDrop to reset dropArea
if (dragover_should_be_canceled){
disposeSupport.attach(document, 'dragover', function(e){
e.preventDefault();
});
} else {
disposeSupport.attach(document, 'dragover', function(e){
if (e.dataTransfer){
e.dataTransfer.dropEffect = 'none';
e.preventDefault();
}
});
}
dropOutsideDisabled = true;
}
}
function isValidFileDrag(e){
// e.dataTransfer currently causing IE errors
// IE9 does NOT support file API, so drag-and-drop is not possible
if (qq.ie() && !qq.ie10()) {
return false;
}
var effectTest, dt = e.dataTransfer,
// do not check dt.types.contains in webkit, because it crashes safari 4
isSafari = qq.safari();
// dt.effectAllowed is none in Safari 5
// dt.types.contains check is for firefox
effectTest = qq.ie10() ? true : dt.effectAllowed !== 'none';
return dt && effectTest && (dt.files || (!isSafari && dt.types.contains && dt.types.contains('Files')));
}
function isOrSetDropDisabled(isDisabled) {
if (isDisabled !== undefined) {
preventDrop = isDisabled;
}
return preventDrop;
}
function attachEvents(){
disposeSupport.attach(element, 'dragover', function(e){
if (!isValidFileDrag(e)) {
return;
}
var effect = qq.ie() ? null : e.dataTransfer.effectAllowed;
if (effect === 'move' || effect === 'linkMove'){
e.dataTransfer.dropEffect = 'move'; // for FF (only move allowed)
} else {
e.dataTransfer.dropEffect = 'copy'; // for Chrome
}
e.stopPropagation();
e.preventDefault();
});
disposeSupport.attach(element, 'dragenter', function(e){
if (!isOrSetDropDisabled()) {
if (!isValidFileDrag(e)) {
return;
}
options.onEnter(e);
}
});
disposeSupport.attach(element, 'dragleave', function(e){
if (!isValidFileDrag(e)) {
return;
}
options.onLeave(e);
var relatedTarget = document.elementFromPoint(e.clientX, e.clientY);
// do not fire when moving a mouse over a descendant
if (qq(this).contains(relatedTarget)) {
return;
}
options.onLeaveNotDescendants(e);
});
disposeSupport.attach(element, 'drop', function(e){
if (!isOrSetDropDisabled()) {
if (!isValidFileDrag(e)) {
return;
}
e.preventDefault();
options.onDrop(e);
}
});
}
disableDropOutside();
attachEvents();
return {
dropDisabled: function(isDisabled) {
return isOrSetDropDisabled(isDisabled);
},
dispose: function() {
disposeSupport.dispose();
}
};
};
/**
* Class that creates upload widget with drag-and-drop and file list
* @inherits qq.FineUploaderBasic
*/
qq.FineUploader = function(o){
// call parent constructor
qq.FineUploaderBasic.apply(this, arguments);
// additional options
qq.extend(this._options, {
element: null,
listElement: null,
dragAndDrop: {
extraDropzones: [],
hideDropzones: true,
disableDefaultDropzone: false
},
text: {
uploadButton: 'Upload a file',
cancelButton: 'Cancel',
retryButton: 'Retry',
deleteButton: 'Delete',
failUpload: 'Upload failed',
dragZone: 'Drop files here to upload',
dropProcessing: 'Processing dropped files...',
formatProgress: "{percent}% of {total_size}",
waitingForResponse: "Processing..."
},
template: '<div class="qq-uploader">' +
((!this._options.dragAndDrop || !this._options.dragAndDrop.disableDefaultDropzone) ? '<div class="qq-upload-drop-area"><span>{dragZoneText}</span></div>' : '') +
(!this._options.button ? '<div class="qq-upload-button"><div>{uploadButtonText}</div></div>' : '') +
'<span class="qq-drop-processing"><span>{dropProcessingText}</span><span class="qq-drop-processing-spinner"></span></span>' +
(!this._options.listElement ? '<ul class="qq-upload-list"></ul>' : '') +
'</div>',
// template for one item in file list
fileTemplate: '<li>' +
'<div class="qq-progress-bar"></div>' +
'<span class="qq-upload-spinner"></span>' +
'<span class="qq-upload-finished"></span>' +
'<span class="qq-upload-file"></span>' +
'<span class="qq-upload-size"></span>' +
'<a class="qq-upload-cancel" href="#">{cancelButtonText}</a>' +
'<a class="qq-upload-retry" href="#">{retryButtonText}</a>' +
'<a class="qq-upload-delete" href="#">{deleteButtonText}</a>' +
'<span class="qq-upload-status-text">{statusText}</span>' +
'</li>',
classes: {
button: 'qq-upload-button',
drop: 'qq-upload-drop-area',
dropActive: 'qq-upload-drop-area-active',
list: 'qq-upload-list',
progressBar: 'qq-progress-bar',
file: 'qq-upload-file',
spinner: 'qq-upload-spinner',
finished: 'qq-upload-finished',
retrying: 'qq-upload-retrying',
retryable: 'qq-upload-retryable',
size: 'qq-upload-size',
cancel: 'qq-upload-cancel',
deleteButton: 'qq-upload-delete',
retry: 'qq-upload-retry',
statusText: 'qq-upload-status-text',
success: 'qq-upload-success',
fail: 'qq-upload-fail',
successIcon: null,
failIcon: null,
dropProcessing: 'qq-drop-processing',
dropProcessingSpinner: 'qq-drop-processing-spinner'
},
failedUploadTextDisplay: {
mode: 'default', //default, custom, or none
maxChars: 50,
responseProperty: 'error',
enableTooltip: true
},
messages: {
tooManyFilesError: "You may only drop one file",
unsupportedBrowser: "Unrecoverable error - this browser does not permit file uploading of any kind."
},
retry: {
showAutoRetryNote: true,
autoRetryNote: "Retrying {retryNum}/{maxAuto}...",
showButton: false
},
deleteFile: {
forceConfirm: false,
confirmMessage: "Are you sure you want to delete {filename}?",
deletingStatusText: "Deleting...",
deletingFailedText: "Delete failed"
},
display: {
fileSizeOnSubmit: false,
prependFiles: false
},
paste: {
promptForName: false,
namePromptMessage: "Please name this image"
},
showMessage: function(message){
setTimeout(function() {
window.alert(message);
}, 0);
},
showConfirm: function(message, okCallback, cancelCallback) {
setTimeout(function() {
var result = window.confirm(message);
if (result) {
okCallback();
}
else if (cancelCallback) {
cancelCallback();
}
}, 0);
},
showPrompt: function(message, defaultValue) {
var promise = new qq.Promise(),
retVal = window.prompt(message, defaultValue);
/*jshint eqeqeq: true, eqnull: true*/
if (retVal != null && qq.trimStr(retVal).length > 0) {
promise.success(retVal);
}
else {
promise.failure("Undefined or invalid user-supplied value.");
}
return promise;
}
}, true);
// overwrite options with user supplied
qq.extend(this._options, o, true);
if (!qq.supportedFeatures.uploading || (this._options.cors.expected && !qq.supportedFeatures.uploadCors)) {
this._options.element.innerHTML = "<div>" + this._options.messages.unsupportedBrowser + "</div>"
}
else {
this._wrapCallbacks();
// overwrite the upload button text if any
// same for the Cancel button and Fail message text
this._options.template = this._options.template.replace(/\{dragZoneText\}/g, this._options.text.dragZone);
this._options.template = this._options.template.replace(/\{uploadButtonText\}/g, this._options.text.uploadButton);
this._options.template = this._options.template.replace(/\{dropProcessingText\}/g, this._options.text.dropProcessing);
this._options.fileTemplate = this._options.fileTemplate.replace(/\{cancelButtonText\}/g, this._options.text.cancelButton);
this._options.fileTemplate = this._options.fileTemplate.replace(/\{retryButtonText\}/g, this._options.text.retryButton);
this._options.fileTemplate = this._options.fileTemplate.replace(/\{deleteButtonText\}/g, this._options.text.deleteButton);
this._options.fileTemplate = this._options.fileTemplate.replace(/\{statusText\}/g, "");
this._element = this._options.element;
this._element.innerHTML = this._options.template;
this._listElement = this._options.listElement || this._find(this._element, 'list');
this._classes = this._options.classes;
if (!this._button) {
this._button = this._createUploadButton(this._find(this._element, 'button'));
}
this._bindCancelAndRetryEvents();
this._dnd = this._setupDragAndDrop();
if (this._options.paste.targetElement && this._options.paste.promptForName) {
this._setupPastePrompt();
}
this._totalFilesInBatch = 0;
this._filesInBatchAddedToUi = 0;
}
};
// inherit from Basic Uploader
qq.extend(qq.FineUploader.prototype, qq.FineUploaderBasic.prototype);
qq.extend(qq.FineUploader.prototype, {
clearStoredFiles: function() {
qq.FineUploaderBasic.prototype.clearStoredFiles.apply(this, arguments);
this._listElement.innerHTML = "";
},
addExtraDropzone: function(element){
this._dnd.setupExtraDropzone(element);
},
removeExtraDropzone: function(element){
return this._dnd.removeDropzone(element);
},
getItemByFileId: function(id){
var item = this._listElement.firstChild;
// there can't be txt nodes in dynamically created list
// and we can use nextSibling
while (item){
if (item.qqFileId == id) return item;
item = item.nextSibling;
}
},
reset: function() {
qq.FineUploaderBasic.prototype.reset.apply(this, arguments);
this._element.innerHTML = this._options.template;
this._listElement = this._options.listElement || this._find(this._element, 'list');
if (!this._options.button) {
this._button = this._createUploadButton(this._find(this._element, 'button'));
}
this._bindCancelAndRetryEvents();
this._dnd.dispose();
this._dnd = this._setupDragAndDrop();
this._totalFilesInBatch = 0;
this._filesInBatchAddedToUi = 0;
},
_removeFileItem: function(fileId) {
var item = this.getItemByFileId(fileId);
qq(item).remove();
},
_setupDragAndDrop: function() {
var self = this,
dropProcessingEl = this._find(this._element, 'dropProcessing'),
dropZoneElements = this._options.dragAndDrop.extraDropzones,
preventSelectFiles;
preventSelectFiles = function(event) {
event.preventDefault();
};
if (!this._options.dragAndDrop.disableDefaultDropzone) {
dropZoneElements.push(this._find(this._options.element, 'drop'));
}
return new qq.DragAndDrop({
dropZoneElements: dropZoneElements,
hideDropZonesBeforeEnter: this._options.dragAndDrop.hideDropzones,
allowMultipleItems: this._options.multiple,
classes: {
dropActive: this._options.classes.dropActive
},
callbacks: {
processingDroppedFiles: function() {
var input = self._button.getInput();
qq(dropProcessingEl).css({display: 'block'});
qq(input).attach('click', preventSelectFiles);
},
processingDroppedFilesComplete: function(files) {
var input = self._button.getInput();
qq(dropProcessingEl).hide();
qq(input).detach('click', preventSelectFiles);
if (files) {
self.addFiles(files);
}
},
dropError: function(code, errorData) {
self._itemError(code, errorData);
},
dropLog: function(message, level) {
self.log(message, level);
}
}
});
},
_leaving_document_out: function(e){
return ((qq.chrome() || (qq.safari() && qq.windows())) && e.clientX == 0 && e.clientY == 0) // null coords for Chrome and Safari Windows
|| (qq.firefox() && !e.relatedTarget); // null e.relatedTarget for Firefox
},
_storeForLater: function(id) {
qq.FineUploaderBasic.prototype._storeForLater.apply(this, arguments);
var item = this.getItemByFileId(id);
qq(this._find(item, 'spinner')).hide();
},
/**
* Gets one of the elements listed in this._options.classes
**/
_find: function(parent, type) {
var element = qq(parent).getByClass(this._options.classes[type])[0];
if (!element){
throw new Error('element not found ' + type);
}
return element;
},
_onSubmit: function(id, name) {
qq.FineUploaderBasic.prototype._onSubmit.apply(this, arguments);
this._addToList(id, name);
},
// Update the progress bar & percentage as the file is uploaded
_onProgress: function(id, name, loaded, total){
qq.FineUploaderBasic.prototype._onProgress.apply(this, arguments);
var item, progressBar, percent, cancelLink;
item = this.getItemByFileId(id);
progressBar = this._find(item, 'progressBar');
percent = Math.round(loaded / total * 100);
if (loaded === total) {
cancelLink = this._find(item, 'cancel');
qq(cancelLink).hide();
qq(progressBar).hide();
qq(this._find(item, 'statusText')).setText(this._options.text.waitingForResponse);
// If last byte was sent, display total file size
this._displayFileSize(id);
}
else {
// If still uploading, display percentage - total size is actually the total request(s) size
this._displayFileSize(id, loaded, total);
qq(progressBar).css({display: 'block'});
}
// Update progress bar element
qq(progressBar).css({width: percent + '%'});
},
_onComplete: function(id, name, result, xhr){
qq.FineUploaderBasic.prototype._onComplete.apply(this, arguments);
var item = this.getItemByFileId(id);
qq(this._find(item, 'statusText')).clearText();
qq(item).removeClass(this._classes.retrying);
qq(this._find(item, 'progressBar')).hide();
if (!this._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) {
qq(this._find(item, 'cancel')).hide();
}
qq(this._find(item, 'spinner')).hide();
if (result.success) {
if (this._isDeletePossible()) {
this._showDeleteLink(id);
}
qq(item).addClass(this._classes.success);
if (this._classes.successIcon) {
this._find(item, 'finished').style.display = "inline-block";
qq(item).addClass(this._classes.successIcon);
}
} else {
qq(item).addClass(this._classes.fail);
if (this._classes.failIcon) {
this._find(item, 'finished').style.display = "inline-block";
qq(item).addClass(this._classes.failIcon);
}
if (this._options.retry.showButton && !this._preventRetries[id]) {
qq(item).addClass(this._classes.retryable);
}
this._controlFailureTextDisplay(item, result);
}
},
_onUpload: function(id, name){
qq.FineUploaderBasic.prototype._onUpload.apply(this, arguments);
this._showSpinner(id);
},
_onCancel: function(id, name) {
qq.FineUploaderBasic.prototype._onCancel.apply(this, arguments);
this._removeFileItem(id);
},
_onBeforeAutoRetry: function(id) {
var item, progressBar, failTextEl, retryNumForDisplay, maxAuto, retryNote;
qq.FineUploaderBasic.prototype._onBeforeAutoRetry.apply(this, arguments);
item = this.getItemByFileId(id);
progressBar = this._find(item, 'progressBar');
this._showCancelLink(item);
progressBar.style.width = 0;
qq(progressBar).hide();
if (this._options.retry.showAutoRetryNote) {
failTextEl = this._find(item, 'statusText');
retryNumForDisplay = this._autoRetries[id] + 1;
maxAuto = this._options.retry.maxAutoAttempts;
retryNote = this._options.retry.autoRetryNote.replace(/\{retryNum\}/g, retryNumForDisplay);
retryNote = retryNote.replace(/\{maxAuto\}/g, maxAuto);
qq(failTextEl).setText(retryNote);
if (retryNumForDisplay === 1) {
qq(item).addClass(this._classes.retrying);
}
}
},
//return false if we should not attempt the requested retry
_onBeforeManualRetry: function(id) {
var item = this.getItemByFileId(id);
if (qq.FineUploaderBasic.prototype._onBeforeManualRetry.apply(this, arguments)) {
this._find(item, 'progressBar').style.width = 0;
qq(item).removeClass(this._classes.fail);
qq(this._find(item, 'statusText')).clearText();
this._showSpinner(id);
this._showCancelLink(item);
return true;
}
else {
qq(item).addClass(this._classes.retryable);
return false;
}
},
_onSubmitDelete: function(id) {
var onSuccessCallback = qq.bind(this._onSubmitDeleteSuccess, this, id);
qq.FineUploaderBasic.prototype._onSubmitDelete.call(this, id, onSuccessCallback);
},
_onSubmitDeleteSuccess: function(id) {
if (this._options.deleteFile.forceConfirm) {
this._showDeleteConfirm(id);
}
else {
this._sendDeleteRequest(id);
}
},
_onDeleteComplete: function(id, xhr, isError) {
qq.FineUploaderBasic.prototype._onDeleteComplete.apply(this, arguments);
var item = this.getItemByFileId(id),
spinnerEl = this._find(item, 'spinner'),
statusTextEl = this._find(item, 'statusText');
qq(spinnerEl).hide();
if (isError) {
qq(statusTextEl).setText(this._options.deleteFile.deletingFailedText);
this._showDeleteLink(id);
}
else {
this._removeFileItem(id);
}
},
_sendDeleteRequest: function(id) {
var item = this.getItemByFileId(id),
deleteLink = this._find(item, 'deleteButton'),
statusTextEl = this._find(item, 'statusText');
qq(deleteLink).hide();
this._showSpinner(id);
qq(statusTextEl).setText(this._options.deleteFile.deletingStatusText);
this._deleteHandler.sendDelete(id, this.getUuid(id));
},
_showDeleteConfirm: function(id) {
var fileName = this._handler.getName(id),
confirmMessage = this._options.deleteFile.confirmMessage.replace(/\{filename\}/g, fileName),
uuid = this.getUuid(id),
self = this;
this._options.showConfirm(confirmMessage, function() {
self._sendDeleteRequest(id);
});
},
_addToList: function(id, name){
var item = qq.toElement(this._options.fileTemplate);
if (this._options.disableCancelForFormUploads && !qq.supportedFeatures.ajaxUploading) {
var cancelLink = this._find(item, 'cancel');
qq(cancelLink).remove();
}
item.qqFileId = id;
var fileElement = this._find(item, 'file');
qq(fileElement).setText(this._options.formatFileName(name));
qq(this._find(item, 'size')).hide();
if (!this._options.multiple) {
this._handler.cancelAll();
this._clearList();
}
if (this._options.display.prependFiles) {
this._prependItem(item);
}
else {
this._listElement.appendChild(item);
}
this._filesInBatchAddedToUi += 1;
if (this._options.display.fileSizeOnSubmit && qq.supportedFeatures.ajaxUploading) {
this._displayFileSize(id);
}
},
_prependItem: function(item) {
var parentEl = this._listElement,
beforeEl = parentEl.firstChild;
if (this._totalFilesInBatch > 1 && this._filesInBatchAddedToUi > 0) {
beforeEl = qq(parentEl).children()[this._filesInBatchAddedToUi - 1].nextSibling;
}
parentEl.insertBefore(item, beforeEl);
},
_clearList: function(){
this._listElement.innerHTML = '';
this.clearStoredFiles();
},
_displayFileSize: function(id, loadedSize, totalSize) {
var item = this.getItemByFileId(id),
size = this.getSize(id),
sizeForDisplay = this._formatSize(size),
sizeEl = this._find(item, 'size');
if (loadedSize !== undefined && totalSize !== undefined) {
sizeForDisplay = this._formatProgress(loadedSize, totalSize);
}
qq(sizeEl).css({display: 'inline'});
qq(sizeEl).setText(sizeForDisplay);
},
/**
* delegate click event for cancel & retry links
**/
_bindCancelAndRetryEvents: function(){
var self = this,
list = this._listElement;
this._disposeSupport.attach(list, 'click', function(e){
e = e || window.event;
var target = e.target || e.srcElement;
if (qq(target).hasClass(self._classes.cancel) || qq(target).hasClass(self._classes.retry) || qq(target).hasClass(self._classes.deleteButton)){
qq.preventDefault(e);
var item = target.parentNode;
while(item.qqFileId === undefined) {
item = item.parentNode;
}
if (qq(target).hasClass(self._classes.deleteButton)) {
self.deleteFile(item.qqFileId);
}
else if (qq(target).hasClass(self._classes.cancel)) {
self.cancel(item.qqFileId);
}
else {
qq(item).removeClass(self._classes.retryable);
self.retry(item.qqFileId);
}
}
});
},
_formatProgress: function (uploadedSize, totalSize) {
var message = this._options.text.formatProgress;
function r(name, replacement) { message = message.replace(name, replacement); }
r('{percent}', Math.round(uploadedSize / totalSize * 100));
r('{total_size}', this._formatSize(totalSize));
return message;
},
_controlFailureTextDisplay: function(item, response) {
var mode, maxChars, responseProperty, failureReason, shortFailureReason;
mode = this._options.failedUploadTextDisplay.mode;
maxChars = this._options.failedUploadTextDisplay.maxChars;
responseProperty = this._options.failedUploadTextDisplay.responseProperty;
if (mode === 'custom') {
failureReason = response[responseProperty];
if (failureReason) {
if (failureReason.length > maxChars) {
shortFailureReason = failureReason.substring(0, maxChars) + '...';
}
}
else {
failureReason = this._options.text.failUpload;
this.log("'" + responseProperty + "' is not a valid property on the server response.", 'warn');
}
qq(this._find(item, 'statusText')).setText(shortFailureReason || failureReason);
if (this._options.failedUploadTextDisplay.enableTooltip) {
this._showTooltip(item, failureReason);
}
}
else if (mode === 'default') {
qq(this._find(item, 'statusText')).setText(this._options.text.failUpload);
}
else if (mode !== 'none') {
this.log("failedUploadTextDisplay.mode value of '" + mode + "' is not valid", 'warn');
}
},
_showTooltip: function(item, text) {
item.title = text;
},
_showSpinner: function(id) {
var item = this.getItemByFileId(id),
spinnerEl = this._find(item, 'spinner');
spinnerEl.style.display = "inline-block";
},
_showCancelLink: function(item) {
if (!this._options.disableCancelForFormUploads || qq.supportedFeatures.ajaxUploading) {
var cancelLink = this._find(item, 'cancel');
qq(cancelLink).css({display: 'inline'});
}
},
_showDeleteLink: function(id) {
var item = this.getItemByFileId(id),
deleteLink = this._find(item, 'deleteButton');
qq(deleteLink).css({display: 'inline'});
},
_itemError: function(code, name){
var message = qq.FineUploaderBasic.prototype._itemError.apply(this, arguments);
this._options.showMessage(message);
},
_batchError: function(message) {
qq.FineUploaderBasic.prototype._batchError.apply(this, arguments);
this._options.showMessage(message);
},
_setupPastePrompt: function() {
var self = this;
this._options.callbacks.onPasteReceived = function() {
var message = self._options.paste.namePromptMessage,
defaultVal = self._options.paste.defaultName;
return self._options.showPrompt(message, defaultVal);
};
},
_fileOrBlobRejected: function(id, name) {
this._totalFilesInBatch -= 1;
qq.FineUploaderBasic.prototype._fileOrBlobRejected.apply(this, arguments);
},
_prepareItemsForUpload: function(items, params, endpoint) {
this._totalFilesInBatch = items.length;
this._filesInBatchAddedToUi = 0;
qq.FineUploaderBasic.prototype._prepareItemsForUpload.apply(this, arguments);
}
});
/** Generic class for sending non-upload ajax requests and handling the associated responses **/
//TODO Use XDomainRequest if expectCors = true. Not necessary now since only DELETE requests are sent and XDR doesn't support pre-flighting.
/*globals qq, XMLHttpRequest*/
qq.AjaxRequestor = function(o) {
"use strict";
var log, shouldParamsBeInQueryString,
queue = [],
requestState = [],
options = {
method: 'POST',
maxConnections: 3,
customHeaders: {},
endpointStore: {},
paramsStore: {},
successfulResponseCodes: [200],
demoMode: false,
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {},
onSend: function(id) {},
onComplete: function(id, xhr, isError) {},
onCancel: function(id) {}
};
qq.extend(options, o);
log = options.log;
shouldParamsBeInQueryString = getMethod() === 'GET' || getMethod() === 'DELETE';
/**
* Removes element from queue, sends next request
*/
function dequeue(id) {
var i = qq.indexOf(queue, id),
max = options.maxConnections,
nextId;
delete requestState[id];
queue.splice(i, 1);
if (queue.length >= max && i < max){
nextId = queue[max-1];
sendRequest(nextId);
}
}
function onComplete(id) {
var xhr = requestState[id].xhr,
method = getMethod(),
isError = false;
dequeue(id);
if (!isResponseSuccessful(xhr.status)) {
isError = true;
log(method + " request for " + id + " has failed - response code " + xhr.status, "error");
}
options.onComplete(id, xhr, isError);
}
function sendRequest(id) {
var xhr = new XMLHttpRequest(),
method = getMethod(),
params = {},
url;
options.onSend(id);
if (options.paramsStore.getParams) {
params = options.paramsStore.getParams(id);
}
url = createUrl(id, params);
requestState[id].xhr = xhr;
xhr.onreadystatechange = getReadyStateChangeHandler(id);
xhr.open(method, url, true);
if (options.cors.expected && options.cors.sendCredentials) {
xhr.withCredentials = true;
}
setHeaders(id);
log('Sending ' + method + " request for " + id);
if (!shouldParamsBeInQueryString && params) {
xhr.send(qq.obj2url(params, ""));
}
else {
xhr.send();
}
}
function createUrl(id, params) {
var endpoint = options.endpointStore.getEndpoint(id),
addToPath = requestState[id].addToPath;
if (addToPath !== undefined) {
endpoint += "/" + addToPath;
}
if (shouldParamsBeInQueryString && params) {
return qq.obj2url(params, endpoint);
}
else {
return endpoint;
}
}
function getReadyStateChangeHandler(id) {
var xhr = requestState[id].xhr;
return function() {
if (xhr.readyState === 4) {
onComplete(id, xhr);
}
};
}
function setHeaders(id) {
var xhr = requestState[id].xhr,
customHeaders = options.customHeaders;
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Cache-Control", "no-cache");
qq.each(customHeaders, function(name, val) {
xhr.setRequestHeader(name, val);
});
}
function cancelRequest(id) {
var xhr = requestState[id].xhr,
method = getMethod();
if (xhr) {
xhr.onreadystatechange = null;
xhr.abort();
dequeue(id);
log('Cancelled ' + method + " for " + id);
options.onCancel(id);
return true;
}
return false;
}
function isResponseSuccessful(responseCode) {
return qq.indexOf(options.successfulResponseCodes, responseCode) >= 0;
}
function getMethod() {
if (options.demoMode) {
return "GET";
}
return options.method;
}
return {
send: function(id, addToPath) {
requestState[id] = {
addToPath: addToPath
};
var len = queue.push(id);
// if too many active connections, wait...
if (len <= options.maxConnections){
sendRequest(id);
}
},
cancel: function(id) {
return cancelRequest(id);
}
};
};
/** Generic class for sending non-upload ajax requests and handling the associated responses **/
/*globals qq, XMLHttpRequest*/
qq.DeleteFileAjaxRequestor = function(o) {
"use strict";
var requestor,
options = {
endpointStore: {},
maxConnections: 3,
customHeaders: {},
paramsStore: {},
demoMode: false,
cors: {
expected: false,
sendCredentials: false
},
log: function(str, level) {},
onDelete: function(id) {},
onDeleteComplete: function(id, xhr, isError) {}
};
qq.extend(options, o);
requestor = new qq.AjaxRequestor({
method: 'DELETE',
endpointStore: options.endpointStore,
paramsStore: options.paramsStore,
maxConnections: options.maxConnections,
customHeaders: options.customHeaders,
successfulResponseCodes: [200, 202, 204],
demoMode: options.demoMode,
log: options.log,
onSend: options.onDelete,
onComplete: options.onDeleteComplete
});
return {
sendDelete: function(id, uuid) {
requestor.send(id, uuid);
options.log("Submitted delete file request for " + id);
}
};
};
qq.WindowReceiveMessage = function(o) {
var options = {
log: function(message, level) {}
},
callbackWrapperDetachers = {};
qq.extend(options, o);
return {
receiveMessage : function(id, callback) {
var onMessageCallbackWrapper = function(event) {
callback(event.data);
};
if (window.postMessage) {
callbackWrapperDetachers[id] = qq(window).attach("message", onMessageCallbackWrapper);
}
else {
log("iframe message passing not supported in this browser!", "error");
}
},
stopReceivingMessages : function(id) {
if (window.postMessage) {
var detacher = callbackWrapperDetachers[id];
if (detacher) {
detacher();
}
}
}
};
};
/**
* Class for uploading files, uploading itself is handled by child classes
*/
/*globals qq*/
qq.UploadHandler = function(o) {
"use strict";
var queue = [],
options, log, handlerImpl, api;
// Default options, can be overridden by the user
options = {
debug: false,
forceMultipart: true,
paramsInBody: false,
paramsStore: {},
endpointStore: {},
cors: {
expected: false,
sendCredentials: false
},
maxConnections: 3, // maximum number of concurrent uploads
uuidParamName: 'qquuid',
totalFileSizeParamName: 'qqtotalfilesize',
chunking: {
enabled: false,
partSize: 2000000, //bytes
paramNames: {
partIndex: 'qqpartindex',
partByteOffset: 'qqpartbyteoffset',
chunkSize: 'qqchunksize',
totalParts: 'qqtotalparts',
filename: 'qqfilename'
}
},
resume: {
enabled: false,
id: null,
cookiesExpireIn: 7, //days
paramNames: {
resuming: "qqresume"
}
},
blobs: {
paramNames: {
name: 'qqblobname'
}
},
log: function(str, level) {},
onProgress: function(id, fileName, loaded, total){},
onComplete: function(id, fileName, response, xhr){},
onCancel: function(id, fileName){},
onUpload: function(id, fileName){},
onUploadChunk: function(id, fileName, chunkData){},
onAutoRetry: function(id, fileName, response, xhr){},
onResume: function(id, fileName, chunkData){},
onUuidChanged: function(id, newUuid){}
};
qq.extend(options, o);
log = options.log;
/**
* Removes element from queue, starts upload of next
*/
function dequeue(id) {
var i = qq.indexOf(queue, id),
max = options.maxConnections,
nextId;
if (i >= 0) {
queue.splice(i, 1);
if (queue.length >= max && i < max){
nextId = queue[max-1];
handlerImpl.upload(nextId);
}
}
};
if (qq.supportedFeatures.ajaxUploading) {
handlerImpl = new qq.UploadHandlerXhr(options, dequeue, options.onUuidChanged, log);
}
else {
handlerImpl = new qq.UploadHandlerForm(options, dequeue, options.onUuidChanged, log);
}
function cancelSuccess(id) {
log('Cancelling ' + id);
options.paramsStore.remove(id);
dequeue(id);
}
api = {
/**
* Adds file or file input to the queue
* @returns id
**/
add: function(file){
return handlerImpl.add(file);
},
/**
* Sends the file identified by id
*/
upload: function(id){
var len = queue.push(id);
// if too many active uploads, wait...
if (len <= options.maxConnections){
handlerImpl.upload(id);
return true;
}
return false;
},
retry: function(id) {
var i = qq.indexOf(queue, id);
if (i >= 0) {
return handlerImpl.upload(id, true);
}
else {
return this.upload(id);
}
},
/**
* Cancels file upload by id
*/
cancel: function(id) {
var cancelRetVal = handlerImpl.cancel(id);
if (qq.isPromise(cancelRetVal)) {
cancelRetVal.then(function() {
cancelSuccess(id);
});
}
else if (cancelRetVal !== false) {
cancelSuccess(id);
}
},
/**
* Cancels all queued or in-progress uploads
*/
cancelAll: function() {
var self = this,
queueCopy = [];
qq.extend(queueCopy, queue);
qq.each(queueCopy, function(idx, fileId) {
self.cancel(fileId);
});
queue = [];
},
/**
* Returns name of the file identified by id
*/
getName: function(id){
return handlerImpl.getName(id);
},
/**
* Returns size of the file identified by id
*/
getSize: function(id){
if (handlerImpl.getSize) {
return handlerImpl.getSize(id);
}
},
getFile: function(id) {
if (handlerImpl.getFile) {
return handlerImpl.getFile(id);
}
},
reset: function() {
log('Resetting upload handler');
api.cancelAll();
queue = [];
handlerImpl.reset();
},
expunge: function(id) {
return handlerImpl.expunge(id);
},
getUuid: function(id) {
return handlerImpl.getUuid(id);
},
/**
* Determine if the file exists.
*/
isValid: function(id) {
return handlerImpl.isValid(id);
},
getResumableFilesData: function() {
if (handlerImpl.getResumableFilesData) {
return handlerImpl.getResumableFilesData();
}
return [];
}
};
return api;
};
/*globals qq, document, setTimeout*/
/*globals clearTimeout*/
qq.UploadHandlerForm = function(o, uploadCompleteCallback, onUuidChanged, logCallback) {
"use strict";
var options = o,
inputs = [],
uuids = [],
detachLoadEvents = {},
postMessageCallbackTimers = {},
uploadComplete = uploadCompleteCallback,
log = logCallback,
corsMessageReceiver = new qq.WindowReceiveMessage({log: log}),
onloadCallbacks = {},
formHandlerInstanceId = qq.getUniqueId(),
api;
function detachLoadEvent(id) {
if (detachLoadEvents[id] !== undefined) {
detachLoadEvents[id]();
delete detachLoadEvents[id];
}
}
function registerPostMessageCallback(iframe, callback) {
var iframeName = iframe.id,
fileId = getFileIdForIframeName(iframeName);
onloadCallbacks[uuids[fileId]] = callback;
detachLoadEvents[fileId] = qq(iframe).attach('load', function() {
if (inputs[fileId]) {
log("Received iframe load event for CORS upload request (iframe name " + iframeName + ")");
postMessageCallbackTimers[iframeName] = setTimeout(function() {
var errorMessage = "No valid message received from loaded iframe for iframe name " + iframeName;
log(errorMessage, "error");
callback({
error: errorMessage
});
}, 1000);
}
});
corsMessageReceiver.receiveMessage(iframeName, function(message) {
log("Received the following window message: '" + message + "'");
var response = parseResponse(getFileIdForIframeName(iframeName), message),
uuid = response.uuid,
onloadCallback;
if (uuid && onloadCallbacks[uuid]) {
log("Handling response for iframe name " + iframeName);
clearTimeout(postMessageCallbackTimers[iframeName]);
delete postMessageCallbackTimers[iframeName];
detachLoadEvent(iframeName);
onloadCallback = onloadCallbacks[uuid];
delete onloadCallbacks[uuid];
corsMessageReceiver.stopReceivingMessages(iframeName);
onloadCallback(response);
}
else if (!uuid) {
log("'" + message + "' does not contain a UUID - ignoring.");
}
});
}
function attachLoadEvent(iframe, callback) {
/*jslint eqeq: true*/
if (options.cors.expected) {
registerPostMessageCallback(iframe, callback);
}
else {
detachLoadEvents[iframe.id] = qq(iframe).attach('load', function(){
log('Received response for ' + iframe.id);
// when we remove iframe from dom
// the request stops, but in IE load
// event fires
if (!iframe.parentNode){
return;
}
try {
// fixing Opera 10.53
if (iframe.contentDocument &&
iframe.contentDocument.body &&
iframe.contentDocument.body.innerHTML == "false"){
// In Opera event is fired second time
// when body.innerHTML changed from false
// to server response approx. after 1 sec
// when we upload file with iframe
return;
}
}
catch (error) {
//IE may throw an "access is denied" error when attempting to access contentDocument on the iframe in some cases
log('Error when attempting to access iframe during handling of upload response (' + error + ")", 'error');
}
callback();
});
}
}
/**
* Returns json object received by iframe from server.
*/
function getIframeContentJson(id, iframe) {
/*jshint evil: true*/
var response;
//IE may throw an "access is denied" error when attempting to access contentDocument on the iframe in some cases
try {
// iframe.contentWindow.document - for IE<7
var doc = iframe.contentDocument || iframe.contentWindow.document,
innerHtml = doc.body.innerHTML;
log("converting iframe's innerHTML to JSON");
log("innerHTML = " + innerHtml);
//plain text response may be wrapped in <pre> tag
if (innerHtml && innerHtml.match(/^<pre/i)) {
innerHtml = doc.body.firstChild.firstChild.nodeValue;
}
response = parseResponse(id, innerHtml);
}
catch(error) {
log('Error when attempting to parse form upload response (' + error + ")", 'error');
response = {success: false};
}
return response;
}
function parseResponse(id, innerHtmlOrMessage) {
var response;
try {
response = qq.parseJson(innerHtmlOrMessage);
if (response.newUuid !== undefined) {
log("Server requested UUID change from '" + uuids[id] + "' to '" + response.newUuid + "'");
uuids[id] = response.newUuid;
onUuidChanged(id, response.newUuid);
}
}
catch(error) {
log('Error when attempting to parse iframe upload response (' + error + ')', 'error');
response = {};
}
return response;
}
/**
* Creates iframe with unique name
*/
function createIframe(id) {
// We can't use following code as the name attribute
// won't be properly registered in IE6, and new window
// on form submit will open
// var iframe = document.createElement('iframe');
// iframe.setAttribute('name', id);
var iframeName = getIframeName(id),
iframe = qq.toElement('<iframe src="javascript:false;" name="' + iframeName + '" />');
iframe.setAttribute('id', iframeName);
iframe.style.display = 'none';
document.body.appendChild(iframe);
return iframe;
}
/**
* Creates form, that will be submitted to iframe
*/
function createForm(id, iframe){
var params = options.paramsStore.getParams(id),
protocol = options.demoMode ? "GET" : "POST",
form = qq.toElement('<form method="' + protocol + '" enctype="multipart/form-data"></form>'),
endpoint = options.endpointStore.getEndpoint(id),
url = endpoint;
params[options.uuidParamName] = uuids[id];
if (!options.paramsInBody) {
url = qq.obj2url(params, endpoint);
}
else {
qq.obj2Inputs(params, form);
}
form.setAttribute('action', url);
form.setAttribute('target', iframe.name);
form.style.display = 'none';
document.body.appendChild(form);
return form;
}
function expungeFile(id) {
delete inputs[id];
delete uuids[id];
delete detachLoadEvents[id];
if (options.cors.expected) {
clearTimeout(postMessageCallbackTimers[id]);
delete postMessageCallbackTimers[id];
corsMessageReceiver.stopReceivingMessages(id);
}
var iframe = document.getElementById(getIframeName(id));
if (iframe) {
// to cancel request set src to something else
// we use src="javascript:false;" because it doesn't
// trigger ie6 prompt on https
iframe.setAttribute('src', 'java' + String.fromCharCode(115) + 'cript:false;'); //deal with "JSLint: javascript URL" warning, which apparently cannot be turned off
qq(iframe).remove();
}
}
function getFileIdForIframeName(iframeName) {
return iframeName.split("_")[0];
}
function getIframeName(fileId) {
return fileId + "_" + formHandlerInstanceId;
}
api = {
add: function(fileInput) {
fileInput.setAttribute('name', options.inputName);
var id = inputs.push(fileInput) - 1;
uuids[id] = qq.getUniqueId();
// remove file input from DOM
if (fileInput.parentNode){
qq(fileInput).remove();
}
return id;
},
getName: function(id) {
/*jslint regexp: true*/
if (api.isValid(id)) {
// get input value and remove path to normalize
return inputs[id].value.replace(/.*(\/|\\)/, "");
}
else {
log(id + " is not a valid item ID.", "error");
}
},
isValid: function(id) {
return inputs[id] !== undefined;
},
reset: function() {
inputs = [];
uuids = [];
detachLoadEvents = {};
formHandlerInstanceId = qq.getUniqueId();
},
expunge: function(id) {
return expungeFile(id);
},
getUuid: function(id) {
return uuids[id];
},
cancel: function(id) {
var onCancelRetVal = options.onCancel(id, api.getName(id));
if (qq.isPromise(onCancelRetVal)) {
return onCancelRetVal.then(function() {
expungeFile(id);
});
}
else if (onCancelRetVal !== false) {
expungeFile(id);
return true;
}
return false;
},
upload: function(id) {
var input = inputs[id],
fileName = api.getName(id),
iframe = createIframe(id),
form;
if (!input){
throw new Error('file with passed id was not added, or already uploaded or cancelled');
}
options.onUpload(id, api.getName(id));
form = createForm(id, iframe);
form.appendChild(input);
attachLoadEvent(iframe, function(responseFromMessage){
log('iframe loaded');
var response = responseFromMessage ? responseFromMessage : getIframeContentJson(id, iframe);
detachLoadEvent(id);
//we can't remove an iframe if the iframe doesn't belong to the same domain
if (!options.cors.expected) {
qq(iframe).remove();
}
if (!response.success) {
if (options.onAutoRetry(id, fileName, response)) {
return;
}
}
options.onComplete(id, fileName, response);
uploadComplete(id);
});
log('Sending upload request for ' + id);
form.submit();
qq(form).remove();
}
};
return api;
};
/*globals qq, File, XMLHttpRequest, FormData, Blob*/
qq.UploadHandlerXhr = function(o, uploadCompleteCallback, onUuidChanged, logCallback) {
"use strict";
var options = o,
uploadComplete = uploadCompleteCallback,
log = logCallback,
fileState = [],
cookieItemDelimiter = "|",
chunkFiles = options.chunking.enabled && qq.supportedFeatures.chunking,
resumeEnabled = options.resume.enabled && chunkFiles && qq.supportedFeatures.resume,
resumeId = getResumeId(),
multipart = options.forceMultipart || options.paramsInBody,
api;
function addChunkingSpecificParams(id, params, chunkData) {
var size = api.getSize(id),
name = api.getName(id);
params[options.chunking.paramNames.partIndex] = chunkData.part;
params[options.chunking.paramNames.partByteOffset] = chunkData.start;
params[options.chunking.paramNames.chunkSize] = chunkData.size;
params[options.chunking.paramNames.totalParts] = chunkData.count;
params[options.totalFileSizeParamName] = size;
/**
* When a Blob is sent in a multipart request, the filename value in the content-disposition header is either "blob"
* or an empty string. So, we will need to include the actual file name as a param in this case.
*/
if (multipart) {
params[options.chunking.paramNames.filename] = name;
}
}
function addResumeSpecificParams(params) {
params[options.resume.paramNames.resuming] = true;
}
function getChunk(fileOrBlob, startByte, endByte) {
if (fileOrBlob.slice) {
return fileOrBlob.slice(startByte, endByte);
}
else if (fileOrBlob.mozSlice) {
return fileOrBlob.mozSlice(startByte, endByte);
}
else if (fileOrBlob.webkitSlice) {
return fileOrBlob.webkitSlice(startByte, endByte);
}
}
function getChunkData(id, chunkIndex) {
var chunkSize = options.chunking.partSize,
fileSize = api.getSize(id),
fileOrBlob = fileState[id].file || fileState[id].blobData.blob,
startBytes = chunkSize * chunkIndex,
endBytes = startBytes+chunkSize >= fileSize ? fileSize : startBytes+chunkSize,
totalChunks = getTotalChunks(id);
return {
part: chunkIndex,
start: startBytes,
end: endBytes,
count: totalChunks,
blob: getChunk(fileOrBlob, startBytes, endBytes),
size: endBytes - startBytes
};
}
function getTotalChunks(id) {
var fileSize = api.getSize(id),
chunkSize = options.chunking.partSize;
return Math.ceil(fileSize / chunkSize);
}
function createXhr(id) {
var xhr = new XMLHttpRequest();
fileState[id].xhr = xhr;
return xhr;
}
function setParamsAndGetEntityToSend(params, xhr, fileOrBlob, id) {
var formData = new FormData(),
method = options.demoMode ? "GET" : "POST",
endpoint = options.endpointStore.getEndpoint(id),
url = endpoint,
name = api.getName(id),
size = api.getSize(id),
blobData = fileState[id].blobData;
params[options.uuidParamName] = fileState[id].uuid;
if (multipart) {
params[options.totalFileSizeParamName] = size;
if (blobData) {
/**
* When a Blob is sent in a multipart request, the filename value in the content-disposition header is either "blob"
* or an empty string. So, we will need to include the actual file name as a param in this case.
*/
params[options.blobs.paramNames.name] = blobData.name;
}
}
//build query string
if (!options.paramsInBody) {
if (!multipart) {
params[options.inputName] = name;
}
url = qq.obj2url(params, endpoint);
}
xhr.open(method, url, true);
if (options.cors.expected && options.cors.sendCredentials) {
xhr.withCredentials = true;
}
if (multipart) {
if (options.paramsInBody) {
qq.obj2FormData(params, formData);
}
formData.append(options.inputName, fileOrBlob);
return formData;
}
return fileOrBlob;
}
function setHeaders(id, xhr) {
var extraHeaders = options.customHeaders,
fileOrBlob = fileState[id].file || fileState[id].blobData.blob;
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("Cache-Control", "no-cache");
if (!multipart) {
xhr.setRequestHeader("Content-Type", "application/octet-stream");
//NOTE: return mime type in xhr works on chrome 16.0.9 firefox 11.0a2
xhr.setRequestHeader("X-Mime-Type", fileOrBlob.type);
}
qq.each(extraHeaders, function(name, val) {
xhr.setRequestHeader(name, val);
});
}
function handleCompletedItem(id, response, xhr) {
var name = api.getName(id),
size = api.getSize(id);
fileState[id].attemptingResume = false;
options.onProgress(id, name, size, size);
options.onComplete(id, name, response, xhr);
if (fileState[id]) {
delete fileState[id].xhr;
}
uploadComplete(id);
}
function uploadNextChunk(id) {
var chunkIdx = fileState[id].remainingChunkIdxs[0],
chunkData = getChunkData(id, chunkIdx),
xhr = createXhr(id),
size = api.getSize(id),
name = api.getName(id),
toSend, params;
if (fileState[id].loaded === undefined) {
fileState[id].loaded = 0;
}
if (resumeEnabled && fileState[id].file) {
persistChunkData(id, chunkData);
}
xhr.onreadystatechange = getReadyStateChangeHandler(id, xhr);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
var totalLoaded = e.loaded + fileState[id].loaded,
estTotalRequestsSize = calcAllRequestsSizeForChunkedUpload(id, chunkIdx, e.total);
options.onProgress(id, name, totalLoaded, estTotalRequestsSize);
}
};
options.onUploadChunk(id, name, getChunkDataForCallback(chunkData));
params = options.paramsStore.getParams(id);
addChunkingSpecificParams(id, params, chunkData);
if (fileState[id].attemptingResume) {
addResumeSpecificParams(params);
}
toSend = setParamsAndGetEntityToSend(params, xhr, chunkData.blob, id);
setHeaders(id, xhr);
log('Sending chunked upload request for item ' + id + ": bytes " + (chunkData.start+1) + "-" + chunkData.end + " of " + size);
xhr.send(toSend);
}
function calcAllRequestsSizeForChunkedUpload(id, chunkIdx, requestSize) {
var chunkData = getChunkData(id, chunkIdx),
blobSize = chunkData.size,
overhead = requestSize - blobSize,
size = api.getSize(id),
chunkCount = chunkData.count,
initialRequestOverhead = fileState[id].initialRequestOverhead,
overheadDiff = overhead - initialRequestOverhead;
fileState[id].lastRequestOverhead = overhead;
if (chunkIdx === 0) {
fileState[id].lastChunkIdxProgress = 0;
fileState[id].initialRequestOverhead = overhead;
fileState[id].estTotalRequestsSize = size + (chunkCount * overhead);
}
else if (fileState[id].lastChunkIdxProgress !== chunkIdx) {
fileState[id].lastChunkIdxProgress = chunkIdx;
fileState[id].estTotalRequestsSize += overheadDiff;
}
return fileState[id].estTotalRequestsSize;
}
function getLastRequestOverhead(id) {
if (multipart) {
return fileState[id].lastRequestOverhead;
}
else {
return 0;
}
}
function handleSuccessfullyCompletedChunk(id, response, xhr) {
var chunkIdx = fileState[id].remainingChunkIdxs.shift(),
chunkData = getChunkData(id, chunkIdx);
fileState[id].attemptingResume = false;
fileState[id].loaded += chunkData.size + getLastRequestOverhead(id);
if (fileState[id].remainingChunkIdxs.length > 0) {
uploadNextChunk(id);
}
else {
if (resumeEnabled) {
deletePersistedChunkData(id);
}
handleCompletedItem(id, response, xhr);
}
}
function isErrorResponse(xhr, response) {
return xhr.status !== 200 || !response.success || response.reset;
}
function parseResponse(id, xhr) {
var response;
try {
response = qq.parseJson(xhr.responseText);
if (response.newUuid !== undefined) {
log("Server requested UUID change from '" + fileState[id].uuid + "' to '" + response.newUuid + "'");
fileState[id].uuid = response.newUuid;
onUuidChanged(id, response.newUuid);
}
}
catch(error) {
log('Error when attempting to parse xhr response text (' + error + ')', 'error');
response = {};
}
return response;
}
function handleResetResponse(id) {
log('Server has ordered chunking effort to be restarted on next attempt for item ID ' + id, 'error');
if (resumeEnabled) {
deletePersistedChunkData(id);
fileState[id].attemptingResume = false;
}
fileState[id].remainingChunkIdxs = [];
delete fileState[id].loaded;
delete fileState[id].estTotalRequestsSize;
delete fileState[id].initialRequestOverhead;
}
function handleResetResponseOnResumeAttempt(id) {
fileState[id].attemptingResume = false;
log("Server has declared that it cannot handle resume for item ID " + id + " - starting from the first chunk", 'error');
handleResetResponse(id);
api.upload(id, true);
}
function handleNonResetErrorResponse(id, response, xhr) {
var name = api.getName(id);
if (options.onAutoRetry(id, name, response, xhr)) {
return;
}
else {
handleCompletedItem(id, response, xhr);
}
}
function onComplete(id, xhr) {
var response;
// the request was aborted/cancelled
if (!fileState[id]) {
return;
}
log("xhr - server response received for " + id);
log("responseText = " + xhr.responseText);
response = parseResponse(id, xhr);
if (isErrorResponse(xhr, response)) {
if (response.reset) {
handleResetResponse(id);
}
if (fileState[id].attemptingResume && response.reset) {
handleResetResponseOnResumeAttempt(id);
}
else {
handleNonResetErrorResponse(id, response, xhr);
}
}
else if (chunkFiles) {
handleSuccessfullyCompletedChunk(id, response, xhr);
}
else {
handleCompletedItem(id, response, xhr);
}
}
function getChunkDataForCallback(chunkData) {
return {
partIndex: chunkData.part,
startByte: chunkData.start + 1,
endByte: chunkData.end,
totalParts: chunkData.count
};
}
function getReadyStateChangeHandler(id, xhr) {
return function() {
if (xhr.readyState === 4) {
onComplete(id, xhr);
}
};
}
function persistChunkData(id, chunkData) {
var fileUuid = api.getUuid(id),
lastByteSent = fileState[id].loaded,
initialRequestOverhead = fileState[id].initialRequestOverhead,
estTotalRequestsSize = fileState[id].estTotalRequestsSize,
cookieName = getChunkDataCookieName(id),
cookieValue = fileUuid +
cookieItemDelimiter + chunkData.part +
cookieItemDelimiter + lastByteSent +
cookieItemDelimiter + initialRequestOverhead +
cookieItemDelimiter + estTotalRequestsSize,
cookieExpDays = options.resume.cookiesExpireIn;
qq.setCookie(cookieName, cookieValue, cookieExpDays);
}
function deletePersistedChunkData(id) {
if (fileState[id].file) {
var cookieName = getChunkDataCookieName(id);
qq.deleteCookie(cookieName);
}
}
function getPersistedChunkData(id) {
var chunkCookieValue = qq.getCookie(getChunkDataCookieName(id)),
filename = api.getName(id),
sections, uuid, partIndex, lastByteSent, initialRequestOverhead, estTotalRequestsSize;
if (chunkCookieValue) {
sections = chunkCookieValue.split(cookieItemDelimiter);
if (sections.length === 5) {
uuid = sections[0];
partIndex = parseInt(sections[1], 10);
lastByteSent = parseInt(sections[2], 10);
initialRequestOverhead = parseInt(sections[3], 10);
estTotalRequestsSize = parseInt(sections[4], 10);
return {
uuid: uuid,
part: partIndex,
lastByteSent: lastByteSent,
initialRequestOverhead: initialRequestOverhead,
estTotalRequestsSize: estTotalRequestsSize
};
}
else {
log('Ignoring previously stored resume/chunk cookie for ' + filename + " - old cookie format", "warn");
}
}
}
function getChunkDataCookieName(id) {
var filename = api.getName(id),
fileSize = api.getSize(id),
maxChunkSize = options.chunking.partSize,
cookieName;
cookieName = "qqfilechunk" + cookieItemDelimiter + encodeURIComponent(filename) + cookieItemDelimiter + fileSize + cookieItemDelimiter + maxChunkSize;
if (resumeId !== undefined) {
cookieName += cookieItemDelimiter + resumeId;
}
return cookieName;
}
function getResumeId() {
if (options.resume.id !== null &&
options.resume.id !== undefined &&
!qq.isFunction(options.resume.id) &&
!qq.isObject(options.resume.id)) {
return options.resume.id;
}
}
function calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex) {
var currentChunkIndex;
for (currentChunkIndex = getTotalChunks(id)-1; currentChunkIndex >= firstChunkIndex; currentChunkIndex-=1) {
fileState[id].remainingChunkIdxs.unshift(currentChunkIndex);
}
uploadNextChunk(id);
}
function onResumeSuccess(id, name, firstChunkIndex, persistedChunkInfoForResume) {
firstChunkIndex = persistedChunkInfoForResume.part;
fileState[id].loaded = persistedChunkInfoForResume.lastByteSent;
fileState[id].estTotalRequestsSize = persistedChunkInfoForResume.estTotalRequestsSize;
fileState[id].initialRequestOverhead = persistedChunkInfoForResume.initialRequestOverhead;
fileState[id].attemptingResume = true;
log('Resuming ' + name + " at partition index " + firstChunkIndex);
calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex);
}
function handlePossibleResumeAttempt(id, persistedChunkInfoForResume, firstChunkIndex) {
var name = api.getName(id),
firstChunkDataForResume = getChunkData(id, persistedChunkInfoForResume.part),
onResumeRetVal;
onResumeRetVal = options.onResume(id, name, getChunkDataForCallback(firstChunkDataForResume));
if (qq.isPromise(onResumeRetVal)) {
log("Waiting for onResume promise to be fulfilled for " + id);
onResumeRetVal.then(
function() {
onResumeSuccess(id, name, firstChunkIndex, persistedChunkInfoForResume);
},
function() {
log("onResume promise fulfilled - failure indicated. Will not resume.")
calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex);
}
);
}
else if (onResumeRetVal !== false) {
onResumeSuccess(id, name, firstChunkIndex, persistedChunkInfoForResume);
}
else {
log("onResume callback returned false. Will not resume.");
calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex);
}
}
function handleFileChunkingUpload(id, retry) {
var firstChunkIndex = 0,
persistedChunkInfoForResume;
if (!fileState[id].remainingChunkIdxs || fileState[id].remainingChunkIdxs.length === 0) {
fileState[id].remainingChunkIdxs = [];
if (resumeEnabled && !retry && fileState[id].file) {
persistedChunkInfoForResume = getPersistedChunkData(id);
if (persistedChunkInfoForResume) {
handlePossibleResumeAttempt(id, persistedChunkInfoForResume, firstChunkIndex);
}
else {
calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex);
}
}
else {
calculateRemainingChunkIdxsAndUpload(id, firstChunkIndex);
}
}
else {
uploadNextChunk(id);
}
}
function handleStandardFileUpload(id) {
var fileOrBlob = fileState[id].file || fileState[id].blobData.blob,
name = api.getName(id),
xhr, params, toSend;
fileState[id].loaded = 0;
xhr = createXhr(id);
xhr.upload.onprogress = function(e){
if (e.lengthComputable){
fileState[id].loaded = e.loaded;
options.onProgress(id, name, e.loaded, e.total);
}
};
xhr.onreadystatechange = getReadyStateChangeHandler(id, xhr);
params = options.paramsStore.getParams(id);
toSend = setParamsAndGetEntityToSend(params, xhr, fileOrBlob, id);
setHeaders(id, xhr);
log('Sending upload request for ' + id);
xhr.send(toSend);
}
function expungeItem(id) {
var xhr = fileState[id].xhr;
if (xhr) {
xhr.onreadystatechange = null;
xhr.abort();
}
if (resumeEnabled) {
deletePersistedChunkData(id);
}
delete fileState[id];
}
api = {
/**
* Adds File or Blob to the queue
* Returns id to use with upload, cancel
**/
add: function(fileOrBlobData){
var id, persistedChunkData,
uuid = qq.getUniqueId();
if (qq.isFile(fileOrBlobData)) {
id = fileState.push({file: fileOrBlobData}) - 1;
}
else if (qq.isBlob(fileOrBlobData.blob)) {
id = fileState.push({blobData: fileOrBlobData}) - 1;
}
else {
throw new Error('Passed obj in not a File or BlobData (in qq.UploadHandlerXhr)');
}
if (resumeEnabled) {
persistedChunkData = getPersistedChunkData(id);
if (persistedChunkData) {
uuid = persistedChunkData.uuid;
}
}
fileState[id].uuid = uuid;
return id;
},
getName: function(id){
if (api.isValid(id)) {
var file = fileState[id].file,
blobData = fileState[id].blobData;
if (file) {
// fix missing name in Safari 4
//NOTE: fixed missing name firefox 11.0a2 file.fileName is actually undefined
return (file.fileName !== null && file.fileName !== undefined) ? file.fileName : file.name;
}
else {
return blobData.name;
}
}
else {
log(id + " is not a valid item ID.", "error");
}
},
getSize: function(id){
/*jshint eqnull: true*/
var fileOrBlob = fileState[id].file || fileState[id].blobData.blob;
if (qq.isFileOrInput(fileOrBlob)) {
return fileOrBlob.fileSize != null ? fileOrBlob.fileSize : fileOrBlob.size;
}
else {
return fileOrBlob.size;
}
},
getFile: function(id) {
if (fileState[id]) {
return fileState[id].file || fileState[id].blobData.blob;
}
},
isValid: function(id) {
return fileState[id] !== undefined;
},
reset: function() {
fileState = [];
},
expunge: function(id) {
return expungeItem(id);
},
getUuid: function(id) {
return fileState[id].uuid;
},
/**
* Sends the file identified by id to the server
*/
upload: function(id, retry) {
var name = this.getName(id);
if (this.isValid(id)) {
options.onUpload(id, name);
if (chunkFiles) {
handleFileChunkingUpload(id, retry);
}
else {
handleStandardFileUpload(id);
}
}
},
cancel: function(id) {
var onCancelRetVal = options.onCancel(id, this.getName(id));
if (qq.isPromise(onCancelRetVal)) {
return onCancelRetVal.then(function() {
expungeItem(id);
});
}
else if (onCancelRetVal !== false) {
expungeItem(id);
return true;
}
return false;
},
getResumableFilesData: function() {
var matchingCookieNames = [],
resumableFilesData = [];
if (chunkFiles && resumeEnabled) {
if (resumeId === undefined) {
matchingCookieNames = qq.getCookieNames(new RegExp("^qqfilechunk\\" + cookieItemDelimiter + ".+\\" +
cookieItemDelimiter + "\\d+\\" + cookieItemDelimiter + options.chunking.partSize + "="));
}
else {
matchingCookieNames = qq.getCookieNames(new RegExp("^qqfilechunk\\" + cookieItemDelimiter + ".+\\" +
cookieItemDelimiter + "\\d+\\" + cookieItemDelimiter + options.chunking.partSize + "\\" +
cookieItemDelimiter + resumeId + "="));
}
qq.each(matchingCookieNames, function(idx, cookieName) {
var cookiesNameParts = cookieName.split(cookieItemDelimiter);
var cookieValueParts = qq.getCookie(cookieName).split(cookieItemDelimiter);
resumableFilesData.push({
name: decodeURIComponent(cookiesNameParts[1]),
size: cookiesNameParts[2],
uuid: cookieValueParts[0],
partIdx: cookieValueParts[1]
});
});
return resumableFilesData;
}
return [];
}
};
return api;
};
/*globals jQuery, qq*/
(function($) {
"use strict";
var uploader, $el, init, dataStore, pluginOption, pluginOptions, addCallbacks, transformVariables, isValidCommand,
delegateCommand;
pluginOptions = ['uploaderType'];
init = function (options) {
if (options) {
var xformedOpts = transformVariables(options);
addCallbacks(xformedOpts);
if (pluginOption('uploaderType') === 'basic') {
uploader(new qq.FineUploaderBasic(xformedOpts));
}
else {
uploader(new qq.FineUploader(xformedOpts));
}
}
return $el;
};
dataStore = function(key, val) {
var data = $el.data('fineuploader');
if (val) {
if (data === undefined) {
data = {};
}
data[key] = val;
$el.data('fineuploader', data);
}
else {
if (data === undefined) {
return null;
}
return data[key];
}
};
//the underlying Fine Uploader instance is stored in jQuery's data stored, associated with the element
// tied to this instance of the plug-in
uploader = function(instanceToStore) {
return dataStore('uploader', instanceToStore);
};
pluginOption = function(option, optionVal) {
return dataStore(option, optionVal);
};
//implement all callbacks defined in Fine Uploader as functions that trigger appropriately names events and
// return the result of executing the bound handler back to Fine Uploader
addCallbacks = function(transformedOpts) {
var callbacks = transformedOpts.callbacks = {},
uploaderInst = new qq.FineUploaderBasic();
$.each(uploaderInst._options.callbacks, function(prop, func) {
var name, $callbackEl;
name = /^on(\w+)/.exec(prop)[1];
name = name.substring(0, 1).toLowerCase() + name.substring(1);
$callbackEl = $el;
callbacks[prop] = function() {
var args = Array.prototype.slice.call(arguments);
return $callbackEl.triggerHandler(name, args);
};
});
};
//transform jQuery objects into HTMLElements, and pass along all other option properties
transformVariables = function(source, dest) {
var xformed, arrayVals;
if (dest === undefined) {
if (source.uploaderType !== 'basic') {
xformed = { element : $el[0] };
}
else {
xformed = {};
}
}
else {
xformed = dest;
}
$.each(source, function(prop, val) {
if ($.inArray(prop, pluginOptions) >= 0) {
pluginOption(prop, val);
}
else if (val instanceof $) {
xformed[prop] = val[0];
}
else if ($.isPlainObject(val)) {
xformed[prop] = {};
transformVariables(val, xformed[prop]);
}
else if ($.isArray(val)) {
arrayVals = [];
$.each(val, function(idx, arrayVal) {
if (arrayVal instanceof $) {
$.merge(arrayVals, arrayVal);
}
else {
arrayVals.push(arrayVal);
}
});
xformed[prop] = arrayVals;
}
else {
xformed[prop] = val;
}
});
if (dest === undefined) {
return xformed;
}
};
isValidCommand = function(command) {
return $.type(command) === "string" &&
!command.match(/^_/) && //enforce private methods convention
uploader()[command] !== undefined;
};
//assuming we have already verified that this is a valid command, call the associated function in the underlying
// Fine Uploader instance (passing along the arguments from the caller) and return the result of the call back to the caller
delegateCommand = function(command) {
var xformedArgs = [], origArgs = Array.prototype.slice.call(arguments, 1);
transformVariables(origArgs, xformedArgs);
return uploader()[command].apply(uploader(), xformedArgs);
};
$.fn.fineUploader = function(optionsOrCommand) {
var self = this, selfArgs = arguments, retVals = [];
this.each(function(index, el) {
$el = $(el);
if (uploader() && isValidCommand(optionsOrCommand)) {
retVals.push(delegateCommand.apply(self, selfArgs));
if (self.length === 1) {
return false;
}
}
else if (typeof optionsOrCommand === 'object' || !optionsOrCommand) {
init.apply(self, selfArgs);
}
else {
$.error('Method ' + optionsOrCommand + ' does not exist on jQuery.fineUploader');
}
});
if (retVals.length === 1) {
return retVals[0];
}
else if (retVals.length > 1) {
return retVals;
}
return this;
};
}(jQuery));
/*globals jQuery, qq*/
(function($) {
"use strict";
var rootDataKey = "fineUploaderDnd",
$el;
function init (options) {
if (!options) {
options = {};
}
options.dropZoneElements = [$el];
var xformedOpts = transformVariables(options);
addCallbacks(xformedOpts);
dnd(new qq.DragAndDrop(xformedOpts));
return $el;
};
function dataStore(key, val) {
var data = $el.data(rootDataKey);
if (val) {
if (data === undefined) {
data = {};
}
data[key] = val;
$el.data(rootDataKey, data);
}
else {
if (data === undefined) {
return null;
}
return data[key];
}
};
function dnd(instanceToStore) {
return dataStore('dndInstance', instanceToStore);
};
function addCallbacks(transformedOpts) {
var callbacks = transformedOpts.callbacks = {},
dndInst = new qq.FineUploaderBasic();
$.each(new qq.DragAndDrop.callbacks(), function(prop, func) {
var name = prop,
$callbackEl;
$callbackEl = $el;
callbacks[prop] = function() {
var args = Array.prototype.slice.call(arguments),
jqueryHandlerResult = $callbackEl.triggerHandler(name, args);
return jqueryHandlerResult;
};
});
};
//transform jQuery objects into HTMLElements, and pass along all other option properties
function transformVariables(source, dest) {
var xformed, arrayVals;
if (dest === undefined) {
xformed = {};
}
else {
xformed = dest;
}
$.each(source, function(prop, val) {
if (val instanceof $) {
xformed[prop] = val[0];
}
else if ($.isPlainObject(val)) {
xformed[prop] = {};
transformVariables(val, xformed[prop]);
}
else if ($.isArray(val)) {
arrayVals = [];
$.each(val, function(idx, arrayVal) {
if (arrayVal instanceof $) {
$.merge(arrayVals, arrayVal);
}
else {
arrayVals.push(arrayVal);
}
});
xformed[prop] = arrayVals;
}
else {
xformed[prop] = val;
}
});
if (dest === undefined) {
return xformed;
}
};
function isValidCommand(command) {
return $.type(command) === "string" &&
command === "dispose" &&
dnd()[command] !== undefined;
};
function delegateCommand(command) {
var xformedArgs = [], origArgs = Array.prototype.slice.call(arguments, 1);
transformVariables(origArgs, xformedArgs);
return dnd()[command].apply(dnd(), xformedArgs);
};
$.fn.fineUploaderDnd = function(optionsOrCommand) {
var self = this, selfArgs = arguments, retVals = [];
this.each(function(index, el) {
$el = $(el);
if (dnd() && isValidCommand(optionsOrCommand)) {
retVals.push(delegateCommand.apply(self, selfArgs));
if (self.length === 1) {
return false;
}
}
else if (typeof optionsOrCommand === 'object' || !optionsOrCommand) {
init.apply(self, selfArgs);
}
else {
$.error("Method " + optionsOrCommand + " does not exist in Fine Uploader's DnD module.");
}
});
if (retVals.length === 1) {
return retVals[0];
}
else if (retVals.length > 1) {
return retVals;
}
return this;
};
}(jQuery));
| baig/cdnjs | ajax/libs/file-uploader/3.6.4/fineuploader-jquery.js | JavaScript | mit | 162,455 |
function ssc_init() {
if (!document.body) return;
var e = document.body;
var t = document.documentElement;
var n = window.innerHeight;
var r = e.scrollHeight;
ssc_root = document.compatMode.indexOf("CSS") >= 0 ? t : e;
ssc_activeElement = e;
ssc_initdone = true;
if (top != self) {
ssc_frame = true
}
else if (r > n && (e.offsetHeight <= n || t.offsetHeight <= n)) {
ssc_root.style.height = "auto";
if (ssc_root.offsetHeight <= n) {
var i = document.createElement("div");
i.style.clear = "both";
e.appendChild(i)
}
}
if (!ssc_fixedback) {
e.style.backgroundAttachment = "scroll";
t.style.backgroundAttachment = "scroll"
}
if (ssc_keyboardsupport) {
ssc_addEvent("keydown", ssc_keydown)
}
}
function ssc_scrollArray(e, t, n, r) {
r || (r = 1e3);
ssc_directionCheck(t, n);
ssc_que.push({
x: t,
y: n,
lastX: t < 0 ? .99 : -.99,
lastY: n < 0 ? .99 : -.99,
start: +(new Date)
});
if (ssc_pending) {
return
}
var i = function () {
var s = +(new Date);
var o = 0;
var u = 0;
for (var a = 0; a < ssc_que.length; a++) {
var f = ssc_que[a];
var l = s - f.start;
var c = l >= ssc_animtime;
var h = c ? 1 : l / ssc_animtime;
if (ssc_pulseAlgorithm) {
h = ssc_pulse(h)
}
var p = f.x * h - f.lastX >> 0;
var d = f.y * h - f.lastY >> 0;
o += p;
u += d;
f.lastX += p;
f.lastY += d;
if (c) {
ssc_que.splice(a, 1);
a--
}
}
if (t) {
var v = e.scrollLeft;
e.scrollLeft += o;
if (o && e.scrollLeft === v) {
t = 0
}
}
if (n) {
var m = e.scrollTop;
e.scrollTop += u;
if (u && e.scrollTop === m) {
n = 0
}
}
if (!t && !n) {
ssc_que = []
}
if (ssc_que.length) {
setTimeout(i, r / ssc_framerate + 1)
}
else {
ssc_pending = false
}
};
setTimeout(i, 0);
ssc_pending = true
}
function ssc_wheel(e) {
if (!ssc_initdone) {
ssc_init()
}
var t = e.target;
var n = ssc_overflowingAncestor(t);
if (!n || e.defaultPrevented || ssc_isNodeName(ssc_activeElement, "embed") || ssc_isNodeName(t, "embed") && /\.pdf/i.test(t.src)) {
return true
}
var r = e.wheelDeltaX || 0;
var i = e.wheelDeltaY || 0;
if (!r && !i) {
i = e.wheelDelta || 0
}
if (Math.abs(r) > 1.2) {
r *= ssc_stepsize / 120
}
if (Math.abs(i) > 1.2) {
i *= ssc_stepsize / 120
}
ssc_scrollArray(n, -r, -i);
e.preventDefault()
}
function ssc_keydown(e) {
var t = e.target;
var n = e.ctrlKey || e.altKey || e.metaKey;
if (/input|textarea|embed/i.test(t.nodeName) || t.isContentEditable || e.defaultPrevented || n) {
return true
}
if (ssc_isNodeName(t, "button") && e.keyCode === ssc_key.spacebar) {
return true
}
var r, i = 0,
s = 0;
var o = ssc_overflowingAncestor(ssc_activeElement);
var u = o.clientHeight;
if (o == document.body) {
u = window.innerHeight
}
switch (e.keyCode) {
case ssc_key.up:
s = -ssc_arrowscroll;
break;
case ssc_key.down:
s = ssc_arrowscroll;
break;
case ssc_key.spacebar:
r = e.shiftKey ? 1 : -1;
s = -r * u * .9;
break;
case ssc_key.pageup:
s = -u * .9;
break;
case ssc_key.pagedown:
s = u * .9;
break;
case ssc_key.home:
s = -o.scrollTop;
break;
case ssc_key.end:
var a = o.scrollHeight - o.scrollTop - u;
s = a > 0 ? a + 10 : 0;
break;
case ssc_key.left:
i = -ssc_arrowscroll;
break;
case ssc_key.right:
i = ssc_arrowscroll;
break;
default:
return true
}
ssc_scrollArray(o, i, s);
e.preventDefault()
}
function ssc_mousedown(e) {
ssc_activeElement = e.target
}
function ssc_setCache(e, t) {
for (var n = e.length; n--;) ssc_cache[ssc_uniqueID(e[n])] = t;
return t
}
function ssc_overflowingAncestor(e) {
var t = [];
var n = ssc_root.scrollHeight;
do {
var r = ssc_cache[ssc_uniqueID(e)];
if (r) {
return ssc_setCache(t, r)
}
t.push(e);
if (n === e.scrollHeight) {
if (!ssc_frame || ssc_root.clientHeight + 10 < n) {
return ssc_setCache(t, document.body)
}
}
else if (e.clientHeight + 10 < e.scrollHeight) {
overflow = getComputedStyle(e, "").getPropertyValue("overflow");
if (overflow === "scroll" || overflow === "auto") {
return ssc_setCache(t, e)
}
}
} while (e = e.parentNode)
}
function ssc_addEvent(e, t, n) {
window.addEventListener(e, t, n || false)
}
function ssc_removeEvent(e, t, n) {
window.removeEventListener(e, t, n || false)
}
function ssc_isNodeName(e, t) {
return e.nodeName.toLowerCase() === t.toLowerCase()
}
function ssc_directionCheck(e, t) {
e = e > 0 ? 1 : -1;
t = t > 0 ? 1 : -1;
if (ssc_direction.x !== e || ssc_direction.y !== t) {
ssc_direction.x = e;
ssc_direction.y = t;
ssc_que = []
}
}
function ssc_pulse_(e) {
var t, n, r;
e = e * ssc_pulseScale;
if (e < 1) {
t = e - (1 - Math.exp(-e))
}
else {
n = Math.exp(-1);
e -= 1;
r = 1 - Math.exp(-e);
t = n + r * (1 - n)
}
return t * ssc_pulseNormalize
}
function ssc_pulse(e) {
if (e >= 1) return 1;
if (e <= 0) return 0;
if (ssc_pulseNormalize == 1) {
ssc_pulseNormalize /= ssc_pulse_(1)
}
return ssc_pulse_(e)
}
var ssc_framerate = 150;
var ssc_animtime = 500;
var ssc_stepsize = 150;
var ssc_pulseAlgorithm = true;
var ssc_pulseScale = 6;
var ssc_pulseNormalize = 1;
var ssc_keyboardsupport = true;
var ssc_arrowscroll = 50;
var ssc_frame = false;
var ssc_direction = {
x: 0,
y: 0
};
var ssc_initdone = false;
var ssc_fixedback = true;
var ssc_root = document.documentElement;
var ssc_activeElement;
var ssc_key = {
left: 37,
up: 38,
right: 39,
down: 40,
spacebar: 32,
pageup: 33,
pagedown: 34,
end: 35,
home: 36
};
var ssc_que = [];
var ssc_pending = false;
var ssc_cache = {};
setInterval(function () {
ssc_cache = {}
}, 10 * 1e3);
var ssc_uniqueID = function () {
var e = 0;
return function (t) {
return t.ssc_uniqueID || (t.ssc_uniqueID = e++)
}
}();
ssc_addEvent("mousedown", ssc_mousedown);
ssc_addEvent("mousewheel", ssc_wheel);
ssc_addEvent("load", ssc_init)
| scriptindex/scriptindex.github.io | themes/ichi/assets/js/vendor/smoothscroll.js | JavaScript | mit | 7,070 |
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
//>>built
define("dojo/cldr/nls/fi/gregorian",{"dateFormatItem-Ehm":"E h.mm a","days-standAlone-short":["su","ma","ti","ke","to","pe","la"],"months-format-narrow":["T","H","M","H","T","K","H","E","S","L","M","J"],"field-second-relative+0":"nyt","quarters-standAlone-narrow":["1","2","3","4"],"field-weekday":"viikonpäivä","dateFormatItem-yQQQ":"QQQ y","dateFormatItem-yMEd":"E d.M.y","field-wed-relative+0":"tänä keskiviikkona","field-wed-relative+1":"ensi keskiviikkona","dateFormatItem-GyMMMEd":"E d. MMM y G","dateFormatItem-MMMEd":"ccc d. MMM","eraNarrow":["eK","jK","jKr.","jaa."],"dateFormatItem-yMM":"M.y","field-tue-relative+-1":"viime tiistaina","days-format-short":["su","ma","ti","ke","to","pe","la"],"dateFormat-long":"d. MMMM y","field-fri-relative+-1":"viime perjantaina","field-wed-relative+-1":"viime keskiviikkona","months-format-wide":["tammikuuta","helmikuuta","maaliskuuta","huhtikuuta","toukokuuta","kesäkuuta","heinäkuuta","elokuuta","syyskuuta","lokakuuta","marraskuuta","joulukuuta"],"dateTimeFormat-medium":"{1} {0}","dayPeriods-format-wide-pm":"ip.","dateFormat-full":"cccc d. MMMM y","field-thu-relative+-1":"viime torstaina","dateFormatItem-Md":"d.M.","dayPeriods-standAlone-wide-pm":"ip.","dayPeriods-format-abbr-am":"ap.","dateFormatItem-yMd":"d.M.y","field-era":"aikakausi","dateFormatItem-yM":"L.y","months-standAlone-wide":["tammikuu","helmikuu","maaliskuu","huhtikuu","toukokuu","kesäkuu","heinäkuu","elokuu","syyskuu","lokakuu","marraskuu","joulukuu"],"timeFormat-short":"H.mm","quarters-format-wide":["1. neljännes","2. neljännes","3. neljännes","4. neljännes"],"dateFormatItem-yQQQQ":"QQQQ y","timeFormat-long":"H.mm.ss z","field-year":"vuosi","dateFormatItem-yMMM":"LLL y","field-hour":"tunti","months-format-abbr":["tammikuuta","helmikuuta","maaliskuuta","huhtikuuta","toukokuuta","kesäkuuta","heinäkuuta","elokuuta","syyskuuta","lokakuuta","marraskuuta","joulukuuta"],"field-sat-relative+0":"tänä lauantaina","field-sat-relative+1":"ensi lauantaina","timeFormat-full":"H.mm.ss zzzz","field-day-relative+0":"tänään","field-thu-relative+0":"tänä torstaina","field-day-relative+1":"huomenna","field-thu-relative+1":"ensi torstaina","dateFormatItem-GyMMMd":"d. MMM y G","field-day-relative+2":"ylihuomenna","dateFormatItem-H":"H","months-standAlone-abbr":["tammi","helmi","maalis","huhti","touko","kesä","heinä","elo","syys","loka","marras","joulu"],"quarters-format-abbr":["1. nelj.","2. nelj.","3. nelj.","4. nelj."],"quarters-standAlone-wide":["1. neljännes","2. neljännes","3. neljännes","4. neljännes"],"dateFormatItem-Gy":"y G","dateFormatItem-M":"L","days-standAlone-wide":["sunnuntai","maanantai","tiistai","keskiviikko","torstai","perjantai","lauantai"],"timeFormat-medium":"H.mm.ss","field-sun-relative+0":"tänä sunnuntaina","dateFormatItem-Hm":"H.mm","field-sun-relative+1":"ensi sunnuntaina","quarters-standAlone-abbr":["1. nelj.","2. nelj.","3. nelj.","4. nelj."],"eraAbbr":["eKr.","eaa.","jKr.","jaa."],"field-minute":"minuutti","field-dayperiod":"vuorokaudenaika","days-standAlone-abbr":["su","ma","ti","ke","to","pe","la"],"dateFormatItem-d":"d","dateFormatItem-ms":"m.ss","quarters-format-narrow":["1","2","3","4"],"field-day-relative+-1":"eilen","dateFormatItem-h":"h a","dateTimeFormat-long":"{1} {0}","dayPeriods-format-narrow-am":"ap.","field-day-relative+-2":"toissapäivänä","dateFormatItem-MMMd":"d. MMM","dateFormatItem-MEd":"E d.M.","dateTimeFormat-full":"{1} {0}","field-fri-relative+0":"tänä perjantaina","dateFormatItem-yMMMM":"LLLL y","field-fri-relative+1":"ensi perjantaina","dateFormatItem-yMMMMccccd":"cccc d. MMMM y","field-day":"päivä","days-format-wide":["sunnuntaina","maanantaina","tiistaina","keskiviikkona","torstaina","perjantaina","lauantaina"],"field-zone":"aikavyöhyke","dateFormatItem-y":"y","months-standAlone-narrow":["T","H","M","H","T","K","H","E","S","L","M","J"],"field-year-relative+-1":"viime vuonna","field-month-relative+-1":"viime kuussa","dateFormatItem-hm":"h.mm a","dayPeriods-format-abbr-pm":"ip.","days-format-abbr":["su","ma","ti","ke","to","pe","la"],"eraNames":["ennen Kristuksen syntymää","ennen ajanlaskun alkua","jälkeen Kristuksen syntymän","jälkeen ajanlaskun alun"],"dateFormatItem-yMMMd":"d. MMM y","days-format-narrow":["S","M","T","K","T","P","L"],"days-standAlone-narrow":["S","M","T","K","T","P","L"],"dateFormatItem-MMM":"LLL","field-month":"kuukausi","field-tue-relative+0":"tänä tiistaina","field-tue-relative+1":"ensi tiistaina","dayPeriods-format-wide-am":"ap.","dayPeriods-standAlone-wide-am":"ap.","dateFormatItem-EHm":"E H.mm","field-mon-relative+0":"tänä maanantaina","field-mon-relative+1":"ensi maanantaina","dateFormat-short":"d.M.y","dateFormatItem-EHms":"E H.mm.ss","dateFormatItem-Ehms":"E h.mm.ss a","field-second":"sekunti","field-sat-relative+-1":"viime lauantaina","dateFormatItem-yMMMEd":"E d. MMM y","field-sun-relative+-1":"viime sunnuntaina","field-month-relative+0":"tässä kuussa","field-month-relative+1":"ensi kuussa","dateFormatItem-Ed":"E d.","dateTimeFormats-appendItem-Timezone":"{0} {1}","field-week":"viikko","dateFormat-medium":"d.M.y","field-year-relative+0":"tänä vuonna","field-week-relative+-1":"viime viikolla","field-year-relative+1":"ensi vuonna","dayPeriods-format-narrow-pm":"ip.","dateTimeFormat-short":"{1} {0}","dateFormatItem-Hms":"H.mm.ss","dateFormatItem-hms":"h.mm.ss a","dateFormatItem-GyMMM":"LLL y G","field-mon-relative+-1":"viime maanantaina","field-week-relative+0":"tällä viikolla","field-week-relative+1":"ensi viikolla"});
| aeharding/cdnjs | ajax/libs/dojo/1.10.3/cldr/nls/fi/gregorian.js | JavaScript | mit | 5,740 |
!function(a){"use strict";var b=window.webshims;if(!b.defineProperties){var c="defineProperty",d=Object.prototype.hasOwnProperty,e=["configurable","enumerable","writable"],f=function(a){for(var b=0;3>b;b++)void 0!==a[e[b]]||"writable"===e[b]&&void 0===a.value||(a[e[b]]=!0)},g=function(a){if(a)for(var b in a)d.call(a,b)&&f(a[b])};Object.create&&(b.objectCreate=function(b,c,d){g(c);var e=Object.create(b,c);return d&&(e.options=a.extend(!0,{},e.options||{},d),d=e.options),e._create&&a.isFunction(e._create)&&e._create(d),e}),Object[c]&&(b[c]=function(a,b,d){return f(d),Object[c](a,b,d)}),Object.defineProperties&&(b.defineProperties=function(a,b){return g(b),Object.defineProperties(a,b)}),b.getOwnPropertyDescriptor=Object.getOwnPropertyDescriptor,b.getPrototypeOf=Object.getPrototypeOf}}(window.webshims.$),webshims.register("dom-extend",function(a,b,c,d,e){"use strict";function f(c,d,e){var f=a.clone(c,d,!1);return a(f.querySelectorAll("."+b.shadowClass)).detach(),e?(t++,a(f.querySelectorAll("[id]")).prop("id",function(a,b){return b+t})):a(f.querySelectorAll('audio[id^="ID-"], video[id^="ID-"], label[id^="ID-"]')).removeAttr("id"),f}var g=!("hrefNormalized"in a.support)||a.support.hrefNormalized,h=!("getSetAttribute"in a.support)||a.support.getSetAttribute,i=Object.prototype.hasOwnProperty;if(b.assumeARIA=h||Modernizr.canvas||Modernizr.video||Modernizr.boxsizing,("text"==a('<input type="email" />').attr("type")||""===a("<form />").attr("novalidate")||"required"in a("<input />")[0].attributes)&&b.error("IE browser modes are busted in IE10+. Please test your HTML/CSS/JS with a real IE version or at least IETester or similiar tools"),"debug"in b&&b.error('Use webshims.setOptions("debug", true||false||"noCombo"); to debug flag'),!b.cfg.no$Switch){var j=function(){if(!c.jQuery||c.$&&c.jQuery!=c.$||c.jQuery.webshims||(b.error("jQuery was included more than once. Make sure to include it only once or try the $.noConflict(extreme) feature! Webshims and other Plugins might not work properly. Or set webshims.cfg.no$Switch to 'true'."),c.$&&(c.$=b.$),c.jQuery=b.$),b.M!=Modernizr){b.error("Modernizr was included more than once. Make sure to include it only once! Webshims and other scripts might not work properly.");for(var a in Modernizr)a in b.M||(b.M[a]=Modernizr[a]);Modernizr=b.M}};j(),setTimeout(j,90),b.ready("DOM",j),a(j),b.ready("WINDOWLOAD",j)}var k=(b.modules,/\s*,\s*/),l={},m={},n={},o={},p={},q={},r=a.fn.val,s=function(b,c,d,e,f){return f?r.call(a(b)):r.call(a(b),d)};a.widget||!function(){var b=a.cleanData;a.cleanData=function(c){if(!a.widget)for(var d,e=0;null!=(d=c[e]);e++)try{a(d).triggerHandler("remove")}catch(f){}b(c)}}(),a.fn.val=function(b){var c=this[0];if(arguments.length&&null==b&&(b=""),!arguments.length)return c&&1===c.nodeType?a.prop(c,"value",b,"val",!0):r.call(this);if(a.isArray(b))return r.apply(this,arguments);var d=a.isFunction(b);return this.each(function(f){if(c=this,1===c.nodeType)if(d){var g=b.call(c,f,a.prop(c,"value",e,"val",!0));null==g&&(g=""),a.prop(c,"value",g,"val")}else a.prop(c,"value",b,"val")})},a.fn.onTrigger=function(a,b){return this.on(a,b).each(b)},a.fn.onWSOff=function(b,c,e,f){return f||(f=d),a(f)[e?"onTrigger":"on"](b,c),this.on("remove",function(d){d.originalEvent||a(f).off(b,c)}),this};var t=0,u="_webshims"+Math.round(1e3*Math.random()),v=function(b,c,d){if(b=b.jquery?b[0]:b,!b)return d||{};var f=a.data(b,u);return d!==e&&(f||(f=a.data(b,u,{})),c&&(f[c]=d)),c?f&&f[c]:f};[{name:"getNativeElement",prop:"nativeElement"},{name:"getShadowElement",prop:"shadowElement"},{name:"getShadowFocusElement",prop:"shadowFocusElement"}].forEach(function(b){a.fn[b.name]=function(){var c=[];return this.each(function(){var d=v(this,"shadowData"),e=d&&d[b.prop]||this;-1==a.inArray(e,c)&&c.push(e)}),this.pushStack(c)}}),a.fn.clonePolyfill=function(b,c){return b=b||!1,this.map(function(){var e=f(this,b,c);return setTimeout(function(){a.contains(d.body,e)&&a(e).updatePolyfill()}),e})},b.cfg.extendNative||b.cfg.noTriggerOverride||!function(b){a.event.trigger=function(c,d,e,f){if(!n[c]||f||!e||1!==e.nodeType)return b.apply(this,arguments);var g,h,j,k=e[c],l=a.prop(e,c),m=l&&k!=l;return m&&(j="__ws"+c,h=c in e&&i.call(e,c),e[c]=l,e[j]=k),g=b.apply(this,arguments),m&&(h?e[c]=k:delete e[c],delete e[j]),g}}(a.event.trigger),["removeAttr","prop","attr"].forEach(function(c){l[c]=a[c],a[c]=function(b,d,f,g,h){var i="val"==g,j=i?s:l[c];if(!b||!m[d]||1!==b.nodeType||!i&&g&&"attr"==c&&a.attrFn[d])return j(b,d,f,g,h);var k,n,p,r=(b.nodeName||"").toLowerCase(),t=o[r],u="attr"!=c||f!==!1&&null!==f?c:"removeAttr";if(t||(t=o["*"]),t&&(t=t[d]),t&&(k=t[u]),k){if("value"==d&&(n=k.isVal,k.isVal=i),"removeAttr"===u)return k.value.call(b);if(f===e)return k.get?k.get.call(b):k.value;k.set&&("attr"==c&&f===!0&&(f=d),p=k.set.call(b,f)),"value"==d&&(k.isVal=n)}else p=j(b,d,f,g,h);if((f!==e||"removeAttr"===u)&&q[r]&&q[r][d]){var v;v="removeAttr"==u?!1:"prop"==u?!!f:!0,q[r][d].forEach(function(a){(!a.only||(a.only="prop"&&"prop"==c)||"attr"==a.only&&"prop"!=c)&&a.call(b,f,v,i?"val":u,c)})}return p},p[c]=function(a,d,f){o[a]||(o[a]={}),o[a][d]||(o[a][d]={});var g=o[a][d][c],h=function(a,b,e){var g;return b&&b[a]?b[a]:e&&e[a]?e[a]:"prop"==c&&"value"==d?function(a){var b=this;return f.isVal?s(b,d,a,!1,0===arguments.length):l[c](b,d,a)}:"prop"==c&&"value"==a&&f.value.apply?(g="__ws"+d,n[d]=!0,function(){var a=this[g]||l[c](this,d);return a&&a.apply&&(a=a.apply(this,arguments)),a}):function(a){return l[c](this,d,a)}};o[a][d][c]=f,f.value===e&&(f.set||(f.set=f.writeable?h("set",f,g):b.cfg.useStrict&&"prop"==d?function(){throw d+" is readonly on "+a}:function(){b.info(d+" is readonly on "+a)}),f.get||(f.get=h("get",f,g))),["value","get","set"].forEach(function(a){f[a]&&(f["_sup"+a]=h(a,g))})}});var w=function(){var a=b.getPrototypeOf(d.createElement("foobar")),c=Modernizr.advancedObjectProperties&&Modernizr.objectAccessor;return function(e,f,g){var h,j;if(!(c&&(h=d.createElement(e))&&(j=b.getPrototypeOf(h))&&a!==j)||h[f]&&i.call(h,f))g._supvalue=function(){var a=v(this,"propValue");return a&&a[f]&&a[f].apply?a[f].apply(this,arguments):a&&a[f]},x.extendValue(e,f,g.value);else{var k=h[f];g._supvalue=function(){return k&&k.apply?k.apply(this,arguments):k},j[f]=g.value}g.value._supvalue=g._supvalue}}(),x=function(){var c={};b.addReady(function(d,e){var f={},g=function(b){f[b]||(f[b]=a(d.getElementsByTagName(b)),e[0]&&a.nodeName(e[0],b)&&(f[b]=f[b].add(e)))};a.each(c,function(a,c){return g(a),c&&c.forEach?void c.forEach(function(b){f[a].each(b)}):void b.warn("Error: with "+a+"-property. methods: "+c)}),f=null});var e,f=a([]),g=function(b,f){c[b]?c[b].push(f):c[b]=[f],a.isDOMReady&&(e||a(d.getElementsByTagName(b))).each(f)};return{createTmpCache:function(b){return a.isDOMReady&&(e=e||a(d.getElementsByTagName(b))),e||f},flushTmpCache:function(){e=null},content:function(b,c){g(b,function(){var b=a.attr(this,c);null!=b&&a.attr(this,c,b)})},createElement:function(a,b){g(a,b)},extendValue:function(b,c,d){g(b,function(){a(this).each(function(){var a=v(this,"propValue",{});a[c]=this[c],this[c]=d})})}}}(),y=function(a,b){a.defaultValue===e&&(a.defaultValue=""),a.removeAttr||(a.removeAttr={value:function(){a[b||"prop"].set.call(this,a.defaultValue),a.removeAttr._supvalue.call(this)}}),a.attr||(a.attr={})};a.extend(b,{getID:function(){var b=(new Date).getTime();return function(c){c=a(c);var d=c.prop("id");return d||(b++,d="ID-"+b,c.eq(0).prop("id",d)),d}}(),shadowClass:"wsshadow-"+Date.now(),implement:function(a,c){var d=v(a,"implemented")||v(a,"implemented",{});return d[c]?(b.warn(c+" already implemented for element #"+a.id),!1):(d[c]=!0,!0)},extendUNDEFProp:function(b,c){a.each(c,function(a,c){a in b||(b[a]=c)})},getOptions:function(){var c=/\-([a-z])/g,d={},e={},f=function(a,b){return b.toLowerCase()},g=function(a,b){return b.toUpperCase()};return function(h,i,j,k){e[i]?i=e[i]:(e[i]=i.replace(c,g),i=e[i]);var l,m=v(h,"cfg"+i),n={};if(m)return m;if(m=a(h).data(),m&&"string"==typeof m[i]){if(k)return v(h,"cfg"+i,m[i]);b.error("data-"+i+" attribute has to be a valid JSON, was: "+m[i])}j?Array.isArray(j)?j.unshift(!0,{}):j=[!0,{},j]:j=[!0,{}],m&&"object"==typeof m[i]&&j.push(m[i]),d[i]||(d[i]=new RegExp("^"+i+"([A-Z])"));for(l in m)d[i].test(l)&&(n[l.replace(d[i],f)]=m[l]);return j.push(n),v(h,"cfg"+i,a.extend.apply(a,j))}}(),createPropDefault:y,data:v,moveToFirstEvent:function(b,c,d){var e,f=(a._data(b,"events")||{})[c];f&&f.length>1&&(e=f.pop(),d||(d="bind"),"bind"==d&&f.delegateCount?f.splice(f.delegateCount,0,e):f.unshift(e)),b=null},addShadowDom:function(){var e,f,g,h=a(c),i={init:!1,runs:0,test:function(){var a=i.getHeight(),b=i.getWidth();a!=i.height||b!=i.width?(i.height=a,i.width=b,i.handler({type:"docresize"}),i.runs++,i.runs<9&&setTimeout(i.test,90)):i.runs=0},handler:function(){var b=function(){a(d).triggerHandler("updateshadowdom")};return function(a){clearTimeout(e),e=setTimeout(function(){if("resize"==a.type){var d=h.width(),e=h.width();if(e==f&&d==g)return;f=e,g=d,i.height=i.getHeight(),i.width=i.getWidth()}c.requestAnimationFrame?requestAnimationFrame(b):setTimeout(b,0)},"resize"!=a.type||c.requestAnimationFrame?9:50)}}(),_create:function(){a.each({Height:"getHeight",Width:"getWidth"},function(a,b){var c=d.body,e=d.documentElement;i[b]=function(){return Math.max(c["scroll"+a],e["scroll"+a],c["offset"+a],e["offset"+a],e["client"+a])}})},start:function(){!this.init&&d.body&&(this.init=!0,this._create(),this.height=i.getHeight(),this.width=i.getWidth(),setInterval(this.test,999),a(this.test),null==a.support.boxSizing&&a(function(){a.support.boxSizing&&i.handler({type:"boxsizing"})}),b.ready("WINDOWLOAD",this.test),a(d).on("updatelayout.webshim pageinit popupafteropen panelbeforeopen tabsactivate collapsibleexpand shown.bs.modal shown.bs.collapse slid.bs.carousel",this.handler),a(c).on("resize",this.handler))}};return b.docObserve=function(){b.ready("DOM",function(){i.start()})},function(c,d,e){if(c&&d){e=e||{},c.jquery&&(c=c[0]),d.jquery&&(d=d[0]);var f=a.data(c,u)||a.data(c,u,{}),g=a.data(d,u)||a.data(d,u,{}),h={};e.shadowFocusElement?e.shadowFocusElement&&(e.shadowFocusElement.jquery&&(e.shadowFocusElement=e.shadowFocusElement[0]),h=a.data(e.shadowFocusElement,u)||a.data(e.shadowFocusElement,u,h)):e.shadowFocusElement=d,a(c).on("remove",function(b){b.originalEvent||setTimeout(function(){a(d).remove()},4)}),f.hasShadow=d,h.nativeElement=g.nativeElement=c,h.shadowData=g.shadowData=f.shadowData={nativeElement:c,shadowElement:d,shadowFocusElement:e.shadowFocusElement},e.shadowChilds&&e.shadowChilds.each(function(){v(this,"shadowData",g.shadowData)}),e.data&&(h.shadowData.data=g.shadowData.data=f.shadowData.data=e.data),e=null}b.docObserve()}}(),propTypes:{standard:function(a){y(a),a.prop||(a.prop={set:function(b){a.attr.set.call(this,""+b)},get:function(){return a.attr.get.call(this)||a.defaultValue}})},"boolean":function(a){y(a),a.prop||(a.prop={set:function(b){b?a.attr.set.call(this,""):a.removeAttr.value.call(this)},get:function(){return null!=a.attr.get.call(this)}})},src:function(){var b=d.createElement("a");return b.style.display="none",function(c,d){y(c),c.prop||(c.prop={set:function(a){c.attr.set.call(this,a)},get:function(){var c,e=this.getAttribute(d);if(null==e)return"";if(b.setAttribute("href",e+""),!g){try{a(b).insertAfter(this),c=b.getAttribute("href",4)}catch(f){c=b.getAttribute("href",4)}a(b).detach()}return c||b.href}})}}(),enumarated:function(a){y(a),a.prop||(a.prop={set:function(b){a.attr.set.call(this,b)},get:function(){var b=(a.attr.get.call(this)||"").toLowerCase();return b&&-1!=a.limitedTo.indexOf(b)||(b=a.defaultValue),b}})}},reflectProperties:function(c,d){"string"==typeof d&&(d=d.split(k)),d.forEach(function(d){b.defineNodeNamesProperty(c,d,{prop:{set:function(b){a.attr(this,d,b)},get:function(){return a.attr(this,d)||""}}})})},defineNodeNameProperty:function(c,d,e){return m[d]=!0,e.reflect&&(e.propType&&!b.propTypes[e.propType]?b.error("could not finde propType "+e.propType):b.propTypes[e.propType||"standard"](e,d)),["prop","attr","removeAttr"].forEach(function(f){var g=e[f];g&&(g="prop"===f?a.extend({writeable:!0},g):a.extend({},g,{writeable:!0}),p[f](c,d,g),"*"!=c&&b.cfg.extendNative&&"prop"==f&&g.value&&a.isFunction(g.value)&&w(c,d,g),e[f]=g)}),e.initAttr&&x.content(c,d),e},defineNodeNameProperties:function(a,c,d,e){for(var f in c)!e&&c[f].initAttr&&x.createTmpCache(a),d&&(c[f][d]||(c[f][d]={},["value","set","get"].forEach(function(a){a in c[f]&&(c[f][d][a]=c[f][a],delete c[f][a])}))),c[f]=b.defineNodeNameProperty(a,f,c[f]);return e||x.flushTmpCache(),c},createElement:function(c,d,e){var f;return a.isFunction(d)&&(d={after:d}),x.createTmpCache(c),d.before&&x.createElement(c,d.before),e&&(f=b.defineNodeNameProperties(c,e,!1,!0)),d.after&&x.createElement(c,d.after),x.flushTmpCache(),f},onNodeNamesPropertyModify:function(b,c,d,e){"string"==typeof b&&(b=b.split(k)),a.isFunction(d)&&(d={set:d}),b.forEach(function(a){q[a]||(q[a]={}),"string"==typeof c&&(c=c.split(k)),d.initAttr&&x.createTmpCache(a),c.forEach(function(b){q[a][b]||(q[a][b]=[],m[b]=!0),d.set&&(e&&(d.set.only=e),q[a][b].push(d.set)),d.initAttr&&x.content(a,b)}),x.flushTmpCache()})},defineNodeNamesBooleanProperty:function(c,d,f){f||(f={}),a.isFunction(f)&&(f.set=f),b.defineNodeNamesProperty(c,d,{attr:{set:function(a){f.useContentAttribute?b.contentAttr(this,d,a):this.setAttribute(d,a),f.set&&f.set.call(this,!0)},get:function(){var a=f.useContentAttribute?b.contentAttr(this,d):this.getAttribute(d);return null==a?e:d}},removeAttr:{value:function(){this.removeAttribute(d),f.set&&f.set.call(this,!1)}},reflect:!0,propType:"boolean",initAttr:f.initAttr||!1})},contentAttr:function(a,b,c){if(a.nodeName){var d;return c===e?(d=a.attributes[b]||{},c=d.specified?d.value:null,null==c?e:c):void("boolean"==typeof c?c?a.setAttribute(b,b):a.removeAttribute(b):a.setAttribute(b,c))}},activeLang:function(){var c=[],d=[],e={},f=function(d,f,h){f._isLoading=!0,e[d]?e[d].push(f):(e[d]=[f],b.loader.loadScript(d,function(){h==c.join()&&a.each(e[d],function(a,b){g(b)}),delete e[d]}))},g=function(b){var d=b.__active,e=function(a,d){return b._isLoading=!1,b[d]||-1!=b.availableLangs.indexOf(d)?(b[d]?(b.__active=b[d],b.__activeName=d):f(b.langSrc+d,b,c.join()),!1):void 0};a.each(c,e),b.__active||(b.__active=b[""],b.__activeName=""),d!=b.__active&&a(b).trigger("change")};return function(a){var b;if("string"==typeof a)c[0]!=a&&(c=[a],b=c[0].split("-")[0],b&&b!=a&&c.push(b),d.forEach(g));else if("object"==typeof a)return a.__active||(d.push(a),g(a)),a.__active;return c[0]}}()}),a.each({defineNodeNamesProperty:"defineNodeNameProperty",defineNodeNamesProperties:"defineNodeNameProperties",createElements:"createElement"},function(a,c){b[a]=function(a,d,e,f){"string"==typeof a&&(a=a.split(k));var g={};return a.forEach(function(a){g[a]=b[c](a,d,e,f)}),g}}),b.isReady("webshimLocalization",!0),function(){if(!("content"in d.createElement("template")||(a(function(){var c=a("main").attr({role:"main"});c.length>1?b.error("only one main element allowed in document"):c.is("article *, section *")&&b.error("main not allowed inside of article/section elements")}),"hidden"in d.createElement("a")))){b.defineNodeNamesBooleanProperty(["*"],"hidden");var c={article:"article",aside:"complementary",section:"region",nav:"navigation",address:"contentinfo"},e=function(a,b){var c=a.getAttribute("role");c||a.setAttribute("role",b)};a.webshims.addReady(function(b,f){if(a.each(c,function(c,d){for(var g=a(c,b).add(f.filter(c)),h=0,i=g.length;i>h;h++)e(g[h],d)}),b===d){var g=d.getElementsByTagName("header")[0],h=d.getElementsByTagName("footer"),i=h.length;if(g&&!a(g).closest("section, article")[0]&&e(g,"banner"),!i)return;var j=h[i-1];a(j).closest("section, article")[0]||e(j,"contentinfo")}})}}()}),webshims.register("form-core",function(a,b,c,d,e,f){"use strict";b.capturingEventPrevented=function(b){if(!b._isPolyfilled){var c=b.isDefaultPrevented,d=b.preventDefault;b.preventDefault=function(){return clearTimeout(a.data(b.target,b.type+"DefaultPrevented")),a.data(b.target,b.type+"DefaultPrevented",setTimeout(function(){a.removeData(b.target,b.type+"DefaultPrevented")},30)),d.apply(this,arguments)},b.isDefaultPrevented=function(){return!(!c.apply(this,arguments)&&!a.data(b.target,b.type+"DefaultPrevented"))},b._isPolyfilled=!0}},Modernizr.formvalidation&&!b.bugs.bustedValidity&&b.capturingEvents(["invalid"],!0);var g=b.modules,h=function(b){return(a.prop(b,"validity")||{valid:1}).valid},i=function(){var c=["form-validation"];f.lazyCustomMessages&&(f.customMessages=!0,c.push("form-message")),b._getAutoEnhance(f.customDatalist)&&(f.fD=!0,c.push("form-datalist")),f.addValidators&&c.push("form-validators"),b.reTest(c),a(d).off(".lazyloadvalidation")},j=function(){var c,e,f=a.expr[":"],g=/^(?:form|fieldset)$/i,i=function(b){var c=!1;return a(b).jProp("elements").each(function(){return!g.test(this.nodeName||"")&&(c=f.invalid(this))?!1:void 0}),c};if(a.extend(f,{"valid-element":function(b){return g.test(b.nodeName||"")?!i(b):!(!a.prop(b,"willValidate")||!h(b))},"invalid-element":function(b){return g.test(b.nodeName||"")?i(b):!(!a.prop(b,"willValidate")||h(b))},"required-element":function(b){return!(!a.prop(b,"willValidate")||!a.prop(b,"required"))},"user-error":function(b){return a.prop(b,"willValidate")&&a(b).hasClass("user-error")},"optional-element":function(b){return!(!a.prop(b,"willValidate")||a.prop(b,"required")!==!1)}}),["valid","invalid","required","optional"].forEach(function(b){f[b]=a.expr[":"][b+"-element"]}),Modernizr.fieldsetdisabled&&!a('<fieldset disabled=""><input /><input /></fieldset>').find(":disabled").filter(":disabled").is(":disabled")&&(c=a.find.matches,e={":disabled":1,":enabled":1},a.find.matches=function(a,b){return e[a]?c.call(this,"*"+a,b):c.apply(this,arguments)},a.extend(f,{enabled:function(b){return b.disabled===!1&&!a(b).is("fieldset[disabled] *")},disabled:function(b){return b.disabled===!0||"disabled"in b&&a(b).is("fieldset[disabled] *")}})),"unknown"==typeof d.activeElement){var j=f.focus;f.focus=function(){try{return j.apply(this,arguments)}catch(a){b.error(a)}return!1}}},k={noAutoCallback:!0,options:f},l=b.loader.addModule,m=function(a,c,d){i(),b.ready("form-validation",function(){a[c].apply(a,d)})},n="transitionDelay"in d.documentElement.style?"":" no-transition",o=b.cfg.wspopover;l("form-validation",a.extend({d:["form-message"]},k)),l("form-validators",a.extend({},k)),a.expr.filters?j():b.ready("sizzle",j),b.triggerInlineForm=function(b,c){a(b).trigger(c)},o.position||o.position===!1||(o.position={at:"left bottom",my:"left top",collision:"fit flip"}),b.wsPopover={id:0,_create:function(){this.options=a.extend(!0,{},o,this.options),this.id=b.wsPopover.id++,this.eventns=".wsoverlay"+this.id,this.timers={},this.element=a('<div class="ws-popover'+n+'" tabindex="-1"><div class="ws-po-outerbox"><div class="ws-po-arrow"><div class="ws-po-arrowbox" /></div><div class="ws-po-box" /></div></div>'),this.contentElement=a(".ws-po-box",this.element),this.lastElement=a([]),this.bindElement(),this.element.data("wspopover",this)},options:{},content:function(a){this.contentElement.html(a)},bindElement:function(){var a=this,b=function(){a.stopBlur=!1};this.preventBlur=function(){a.stopBlur=!0,clearTimeout(a.timers.stopBlur),a.timers.stopBlur=setTimeout(b,9)},this.element.on({mousedown:this.preventBlur})},show:function(){m(this,"show",arguments)}},b.validityAlert={showFor:function(){m(this,"showFor",arguments)}},b.getContentValidationMessage=function(c,d,e){var f;b.errorbox&&b.errorbox.initIvalContentMessage&&b.errorbox.initIvalContentMessage(c);var g=(b.getOptions&&b.errorbox?b.getOptions(c,"errormessage",!1,!0):a(c).data("errormessage"))||c.getAttribute("x-moz-errormessage")||"";return e&&g[e]?g=g[e]:g&&(d=d||a.prop(c,"validity")||{valid:1},d.valid&&(g="")),"object"==typeof g&&(d=d||a.prop(c,"validity")||{valid:1},d.customError&&(f=a.data(c,"customMismatchedRule"))&&g[f]&&"string"==typeof g[f]?g=g[f]:d.valid||(a.each(d,function(a,b){return b&&"valid"!=a&&g[a]?(g=g[a],!1):void 0}),"object"==typeof g&&(d.typeMismatch&&g.badInput&&(g=g.badInput),d.badInput&&g.typeMismatch&&(g=g.typeMismatch)))),"object"==typeof g&&(g=g.defaultMessage),b.replaceValidationplaceholder&&(g=b.replaceValidationplaceholder(c,g)),g||""},a.fn.getErrorMessage=function(c){var d="",e=this[0];return e&&(d=b.getContentValidationMessage(e,!1,c)||a.prop(e,"customValidationMessage")||a.prop(e,"validationMessage")),d},a.event.special.valuevalidation={setup:function(){b.error("valuevalidation was renamed to validatevalue!")}},a.event.special.validatevalue={setup:function(){var b=a(this).data()||a.data(this,{});"validatevalue"in b||(b.validatevalue=!0)}},a(d).on("focusin.lazyloadvalidation",function(a){"form"in a.target&&i()}),b.ready("WINDOWLOAD",i),g["form-number-date-ui"].loaded&&!f.customMessages&&(g["form-number-date-api"].test()||Modernizr.inputtypes.range&&Modernizr.inputtypes.color)&&b.isReady("form-number-date-ui",!0),b.ready("DOM",function(){d.querySelector(".ws-custom-file")&&b.reTest(["form-validation"])}),a(function(){var a="FileReader"in c&&"FormData"in c;a||b.addReady(function(c){a||g.filereader.loaded||g.moxie.loaded||c.querySelector("input.ws-filereader")&&(b.reTest(["filereader","moxie"]),a=!0)})})}),webshims.register("form-datalist",function(a,b,c,d,e,f){"use strict";var g=function(a){a&&"string"==typeof a||(a="DOM"),g[a+"Loaded"]||(g[a+"Loaded"]=!0,b.ready(a,function(){b.loader.loadList(["form-datalist-lazy"])}))},h={submit:1,button:1,reset:1,hidden:1,range:1,date:1,month:1};b.modules["form-number-date-ui"].loaded&&a.extend(h,{number:1,time:1}),b.propTypes.element=function(c,e){b.createPropDefault(c,"attr"),c.prop||(c.prop={get:function(){var b=a.attr(this,e);return b&&(b=d.getElementById(b),b&&c.propNodeName&&!a.nodeName(b,c.propNodeName)&&(b=null)),b||null},writeable:!1})},function(){var i=a.webshims.cfg.forms,j=Modernizr.input.list;if(!j||i.customDatalist){var k=function(){var c=function(){var b;!a.data(this,"datalistWidgetData")&&(b=a.prop(this,"id"))?a('input[list="'+b+'"], input[data-wslist="'+b+'"]').eq(0).attr("list",b):a(this).triggerHandler("updateDatalist")},d={autocomplete:{attr:{get:function(){var b=this,c=a.data(b,"datalistWidget");return c?c._autocomplete:"autocomplete"in b?b.autocomplete:b.getAttribute("autocomplete")},set:function(b){var c=this,d=a.data(c,"datalistWidget");d?(d._autocomplete=b,"off"==b&&d.hideList()):"autocomplete"in c?c.autocomplete=b:c.setAttribute("autocomplete",b)}}}};j?((a("<datalist><select><option></option></select></datalist>").prop("options")||[]).length||b.defineNodeNameProperty("datalist","options",{prop:{writeable:!1,get:function(){var b=this.options||[];if(!b.length){var c=this,d=a("select",c);d[0]&&d[0].options&&d[0].options.length&&(b=d[0].options)}return b}}}),d.list={attr:{get:function(){var c=b.contentAttr(this,"list");return null!=c?(a.data(this,"datalistListAttr",c),h[a.prop(this,"type")]||h[a.attr(this,"type")]||this.removeAttribute("list")):c=a.data(this,"datalistListAttr"),null==c?e:c},set:function(c){var d=this;a.data(d,"datalistListAttr",c),h[a.prop(this,"type")]||h[a.attr(this,"type")]?d.setAttribute("list",c):(b.objectCreate(l,e,{input:d,id:c,datalist:a.prop(d,"list")}),d.setAttribute("data-wslist",c)),a(d).triggerHandler("listdatalistchange")}},initAttr:!0,reflect:!0,propType:"element",propNodeName:"datalist"}):b.defineNodeNameProperties("input",{list:{attr:{get:function(){var a=b.contentAttr(this,"list");return null==a?e:a},set:function(c){var d=this;b.contentAttr(d,"list",c),b.objectCreate(f.shadowListProto,e,{input:d,id:c,datalist:a.prop(d,"list")}),a(d).triggerHandler("listdatalistchange")}},initAttr:!0,reflect:!0,propType:"element",propNodeName:"datalist"}}),b.defineNodeNameProperties("input",d),b.addReady(function(a,b){b.filter("datalist > select, datalist, datalist > option, datalist > select > option").closest("datalist").each(c)})},l={_create:function(d){if(!h[a.prop(d.input,"type")]&&!h[a.attr(d.input,"type")]){var e=d.datalist,f=a.data(d.input,"datalistWidget"),i=this;return e&&f&&f.datalist!==e?(f.datalist=e,f.id=d.id,a(f.datalist).off("updateDatalist.datalistWidget").on("updateDatalist.datalistWidget",a.proxy(f,"_resetListCached")),void f._resetListCached()):e?void(f&&f.datalist===e||(this.datalist=e,this.id=d.id,this.hasViewableData=!0,this._autocomplete=a.attr(d.input,"autocomplete"),a.data(d.input,"datalistWidget",this),a.data(e,"datalistWidgetData",this),g("WINDOWLOAD"),b.isReady("form-datalist-lazy")?c.QUnit?i._lazyCreate(d):setTimeout(function(){i._lazyCreate(d)},9):(a(d.input).one("focus",g),b.ready("form-datalist-lazy",function(){i._destroyed||i._lazyCreate(d)})))):void(f&&f.destroy())}},destroy:function(b){var f,g=a.attr(this.input,"autocomplete");a(this.input).off(".datalistWidget").removeData("datalistWidget"),this.shadowList.remove(),a(d).off(".datalist"+this.id),a(c).off(".datalist"+this.id),this.input.form&&this.input.id&&a(this.input.form).off("submit.datalistWidget"+this.input.id),this.input.removeAttribute("aria-haspopup"),g===e?this.input.removeAttribute("autocomplete"):a(this.input).attr("autocomplete",g),b&&"beforeunload"==b.type&&(f=this.input,setTimeout(function(){a.attr(f,"list",a.attr(f,"list"))},9)),this._destroyed=!0}};b.loader.addModule("form-datalist-lazy",{noAutoCallback:!0,options:a.extend(f,{shadowListProto:l})}),f.list||(f.list={}),k()}}()}); | fk/cdnjs | ajax/libs/webshim/1.14.3-RC2/minified/shims/combos/31.js | JavaScript | mit | 25,422 |
if (typeof _yuitest_coverage == "undefined"){
_yuitest_coverage = {};
_yuitest_coverline = function(src, line){
var coverage = _yuitest_coverage[src];
if (!coverage.lines[line]){
coverage.calledLines++;
}
coverage.lines[line]++;
};
_yuitest_coverfunc = function(src, name, line){
var coverage = _yuitest_coverage[src],
funcId = name + ":" + line;
if (!coverage.functions[funcId]){
coverage.calledFunctions++;
}
coverage.functions[funcId]++;
};
}
_yuitest_coverage["build/widget-base-ie/widget-base-ie.js"] = {
lines: {},
functions: {},
coveredLines: 0,
calledLines: 0,
coveredFunctions: 0,
calledFunctions: 0,
path: "build/widget-base-ie/widget-base-ie.js",
code: []
};
_yuitest_coverage["build/widget-base-ie/widget-base-ie.js"].code=["YUI.add('widget-base-ie', function (Y, NAME) {","","/**"," * IE specific support for the widget-base module."," *"," * @module widget-base-ie"," */","var BOUNDING_BOX = \"boundingBox\","," CONTENT_BOX = \"contentBox\","," HEIGHT = \"height\","," OFFSET_HEIGHT = \"offsetHeight\","," EMPTY_STR = \"\","," IE = Y.UA.ie,"," heightReallyMinHeight = IE < 7,"," bbTempExpanding = Y.Widget.getClassName(\"tmp\", \"forcesize\"),"," contentExpanded = Y.Widget.getClassName(\"content\", \"expanded\");","","// TODO: Ideally we want to re-use the base _uiSizeCB impl","Y.Widget.prototype._uiSizeCB = function(expand) {",""," var bb = this.get(BOUNDING_BOX),"," cb = this.get(CONTENT_BOX),"," borderBoxSupported = this._bbs;",""," if (borderBoxSupported === undefined) {"," this._bbs = borderBoxSupported = !(IE && IE < 8 && bb.get(\"ownerDocument\").get(\"compatMode\") != \"BackCompat\"); "," }",""," if (borderBoxSupported) {"," cb.toggleClass(contentExpanded, expand);"," } else {"," if (expand) {"," if (heightReallyMinHeight) {"," bb.addClass(bbTempExpanding);"," }",""," cb.set(OFFSET_HEIGHT, bb.get(OFFSET_HEIGHT));",""," if (heightReallyMinHeight) {"," bb.removeClass(bbTempExpanding);"," }"," } else {"," cb.setStyle(HEIGHT, EMPTY_STR);"," }"," }","};","","","}, '@VERSION@', {\"requires\": [\"widget-base\"]});"];
_yuitest_coverage["build/widget-base-ie/widget-base-ie.js"].lines = {"1":0,"8":0,"19":0,"21":0,"25":0,"26":0,"29":0,"30":0,"32":0,"33":0,"34":0,"37":0,"39":0,"40":0,"43":0};
_yuitest_coverage["build/widget-base-ie/widget-base-ie.js"].functions = {"_uiSizeCB:19":0,"(anonymous 1):1":0};
_yuitest_coverage["build/widget-base-ie/widget-base-ie.js"].coveredLines = 15;
_yuitest_coverage["build/widget-base-ie/widget-base-ie.js"].coveredFunctions = 2;
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 1);
YUI.add('widget-base-ie', function (Y, NAME) {
/**
* IE specific support for the widget-base module.
*
* @module widget-base-ie
*/
_yuitest_coverfunc("build/widget-base-ie/widget-base-ie.js", "(anonymous 1)", 1);
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 8);
var BOUNDING_BOX = "boundingBox",
CONTENT_BOX = "contentBox",
HEIGHT = "height",
OFFSET_HEIGHT = "offsetHeight",
EMPTY_STR = "",
IE = Y.UA.ie,
heightReallyMinHeight = IE < 7,
bbTempExpanding = Y.Widget.getClassName("tmp", "forcesize"),
contentExpanded = Y.Widget.getClassName("content", "expanded");
// TODO: Ideally we want to re-use the base _uiSizeCB impl
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 19);
Y.Widget.prototype._uiSizeCB = function(expand) {
_yuitest_coverfunc("build/widget-base-ie/widget-base-ie.js", "_uiSizeCB", 19);
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 21);
var bb = this.get(BOUNDING_BOX),
cb = this.get(CONTENT_BOX),
borderBoxSupported = this._bbs;
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 25);
if (borderBoxSupported === undefined) {
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 26);
this._bbs = borderBoxSupported = !(IE && IE < 8 && bb.get("ownerDocument").get("compatMode") != "BackCompat");
}
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 29);
if (borderBoxSupported) {
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 30);
cb.toggleClass(contentExpanded, expand);
} else {
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 32);
if (expand) {
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 33);
if (heightReallyMinHeight) {
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 34);
bb.addClass(bbTempExpanding);
}
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 37);
cb.set(OFFSET_HEIGHT, bb.get(OFFSET_HEIGHT));
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 39);
if (heightReallyMinHeight) {
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 40);
bb.removeClass(bbTempExpanding);
}
} else {
_yuitest_coverline("build/widget-base-ie/widget-base-ie.js", 43);
cb.setStyle(HEIGHT, EMPTY_STR);
}
}
};
}, '@VERSION@', {"requires": ["widget-base"]});
| luhad/cdnjs | ajax/libs/yui/3.7.3/widget-base-ie/widget-base-ie-coverage.js | JavaScript | mit | 5,358 |
if (typeof _yuitest_coverage == "undefined"){
_yuitest_coverage = {};
_yuitest_coverline = function(src, line){
var coverage = _yuitest_coverage[src];
if (!coverage.lines[line]){
coverage.calledLines++;
}
coverage.lines[line]++;
};
_yuitest_coverfunc = function(src, name, line){
var coverage = _yuitest_coverage[src],
funcId = name + ":" + line;
if (!coverage.functions[funcId]){
coverage.calledFunctions++;
}
coverage.functions[funcId]++;
};
}
_yuitest_coverage["build/shim-plugin/shim-plugin.js"] = {
lines: {},
functions: {},
coveredLines: 0,
calledLines: 0,
coveredFunctions: 0,
calledFunctions: 0,
path: "build/shim-plugin/shim-plugin.js",
code: []
};
_yuitest_coverage["build/shim-plugin/shim-plugin.js"].code=["YUI.add('shim-plugin', function (Y, NAME) {",""," /**"," * Provides shimming support for Node via a Plugin."," * This fixes SELECT bleedthrough for IE6 & Mac scrollbars"," * @module shim-plugin"," */",""," /**"," * Node plugin which can be used to add shim support."," *"," * @class Plugin.Shim"," * @param {Object} User configuration object"," */"," function Shim(config) {"," this.init(config);"," }",""," /**"," * Default class used to mark the shim element"," *"," * @property CLASS_NAME"," * @type String"," * @static"," * @default \"yui-node-shim\""," */"," // TODO: use ClassNameManager"," Shim.CLASS_NAME = 'yui-node-shim';",""," /**"," * Default markup template used to generate the shim element."," * "," * @property TEMPLATE"," * @type String"," * @static"," */"," Shim.TEMPLATE = '<iframe class=\"' + Shim.CLASS_NAME +"," '\" frameborder=\"0\" title=\"Node Stacking Shim\"' +"," 'src=\"javascript:false\" tabindex=\"-1\" role=\"presentation\"' +"," 'style=\"position:absolute; z-index:-1;\"></iframe>';",""," Shim.prototype = {"," init: function(config) {"," this._host = config.host;"," this.initEvents();"," this.insert();"," this.sync();"," },",""," initEvents: function() {"," this._resizeHandle = this._host.on('resize', this.sync, this);"," },"," "," getShim: function() {"," return this._shim || ("," this._shim = Y.Node.create("," Shim.TEMPLATE,"," this._host.get('ownerDocument')"," )"," );"," },",""," insert: function() {"," var node = this._host;"," this._shim = node.insertBefore( this.getShim(),"," node.get('firstChild'));"," },",""," /**"," * Updates the size of the shim to fill its container"," * @method sync"," */"," sync: function() {"," var shim = this._shim,"," node = this._host;",""," if (shim) {"," shim.setAttrs({"," width: node.getStyle('width'),"," height: node.getStyle('height')"," });"," }"," },",""," /**"," * Removes the shim and destroys the plugin"," * @method destroy"," */"," destroy: function() {"," var shim = this._shim;"," if (shim) {"," shim.remove(true);"," }",""," this._resizeHandle.detach();"," }"," };",""," Shim.NAME = 'Shim';"," Shim.NS = 'shim';",""," Y.namespace('Plugin');"," Y.Plugin.Shim = Shim;","","","}, '@VERSION@', {\"requires\": [\"node-style\", \"node-pluginhost\"]});"];
_yuitest_coverage["build/shim-plugin/shim-plugin.js"].lines = {"1":0,"15":0,"16":0,"28":0,"37":0,"42":0,"44":0,"45":0,"46":0,"47":0,"51":0,"55":0,"64":0,"65":0,"74":0,"77":0,"78":0,"90":0,"91":0,"92":0,"95":0,"99":0,"100":0,"102":0,"103":0};
_yuitest_coverage["build/shim-plugin/shim-plugin.js"].functions = {"Shim:15":0,"init:43":0,"initEvents:50":0,"getShim:54":0,"insert:63":0,"sync:73":0,"destroy:89":0,"(anonymous 1):1":0};
_yuitest_coverage["build/shim-plugin/shim-plugin.js"].coveredLines = 25;
_yuitest_coverage["build/shim-plugin/shim-plugin.js"].coveredFunctions = 8;
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 1);
YUI.add('shim-plugin', function (Y, NAME) {
/**
* Provides shimming support for Node via a Plugin.
* This fixes SELECT bleedthrough for IE6 & Mac scrollbars
* @module shim-plugin
*/
/**
* Node plugin which can be used to add shim support.
*
* @class Plugin.Shim
* @param {Object} User configuration object
*/
_yuitest_coverfunc("build/shim-plugin/shim-plugin.js", "(anonymous 1)", 1);
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 15);
function Shim(config) {
_yuitest_coverfunc("build/shim-plugin/shim-plugin.js", "Shim", 15);
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 16);
this.init(config);
}
/**
* Default class used to mark the shim element
*
* @property CLASS_NAME
* @type String
* @static
* @default "yui-node-shim"
*/
// TODO: use ClassNameManager
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 28);
Shim.CLASS_NAME = 'yui-node-shim';
/**
* Default markup template used to generate the shim element.
*
* @property TEMPLATE
* @type String
* @static
*/
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 37);
Shim.TEMPLATE = '<iframe class="' + Shim.CLASS_NAME +
'" frameborder="0" title="Node Stacking Shim"' +
'src="javascript:false" tabindex="-1" role="presentation"' +
'style="position:absolute; z-index:-1;"></iframe>';
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 42);
Shim.prototype = {
init: function(config) {
_yuitest_coverfunc("build/shim-plugin/shim-plugin.js", "init", 43);
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 44);
this._host = config.host;
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 45);
this.initEvents();
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 46);
this.insert();
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 47);
this.sync();
},
initEvents: function() {
_yuitest_coverfunc("build/shim-plugin/shim-plugin.js", "initEvents", 50);
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 51);
this._resizeHandle = this._host.on('resize', this.sync, this);
},
getShim: function() {
_yuitest_coverfunc("build/shim-plugin/shim-plugin.js", "getShim", 54);
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 55);
return this._shim || (
this._shim = Y.Node.create(
Shim.TEMPLATE,
this._host.get('ownerDocument')
)
);
},
insert: function() {
_yuitest_coverfunc("build/shim-plugin/shim-plugin.js", "insert", 63);
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 64);
var node = this._host;
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 65);
this._shim = node.insertBefore( this.getShim(),
node.get('firstChild'));
},
/**
* Updates the size of the shim to fill its container
* @method sync
*/
sync: function() {
_yuitest_coverfunc("build/shim-plugin/shim-plugin.js", "sync", 73);
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 74);
var shim = this._shim,
node = this._host;
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 77);
if (shim) {
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 78);
shim.setAttrs({
width: node.getStyle('width'),
height: node.getStyle('height')
});
}
},
/**
* Removes the shim and destroys the plugin
* @method destroy
*/
destroy: function() {
_yuitest_coverfunc("build/shim-plugin/shim-plugin.js", "destroy", 89);
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 90);
var shim = this._shim;
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 91);
if (shim) {
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 92);
shim.remove(true);
}
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 95);
this._resizeHandle.detach();
}
};
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 99);
Shim.NAME = 'Shim';
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 100);
Shim.NS = 'shim';
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 102);
Y.namespace('Plugin');
_yuitest_coverline("build/shim-plugin/shim-plugin.js", 103);
Y.Plugin.Shim = Shim;
}, '@VERSION@', {"requires": ["node-style", "node-pluginhost"]});
| xirzec/cdnjs | ajax/libs/yui/3.8.0/shim-plugin/shim-plugin-coverage.js | JavaScript | mit | 9,148 |
if (typeof _yuitest_coverage == "undefined"){
_yuitest_coverage = {};
_yuitest_coverline = function(src, line){
var coverage = _yuitest_coverage[src];
if (!coverage.lines[line]){
coverage.calledLines++;
}
coverage.lines[line]++;
};
_yuitest_coverfunc = function(src, name, line){
var coverage = _yuitest_coverage[src],
funcId = name + ":" + line;
if (!coverage.functions[funcId]){
coverage.calledFunctions++;
}
coverage.functions[funcId]++;
};
}
_yuitest_coverage["build/arraylist-add/arraylist-add.js"] = {
lines: {},
functions: {},
coveredLines: 0,
calledLines: 0,
coveredFunctions: 0,
calledFunctions: 0,
path: "build/arraylist-add/arraylist-add.js",
code: []
};
_yuitest_coverage["build/arraylist-add/arraylist-add.js"].code=["YUI.add('arraylist-add', function (Y, NAME) {","","/**"," * Collection utilities beyond what is provided in the YUI core"," * @module collection"," * @submodule arraylist-add"," * @deprecated Use ModelList or a custom ArrayList subclass"," */","","/*"," * Adds methods add and remove to Y.ArrayList"," */","Y.mix(Y.ArrayList.prototype, {",""," /**"," * Add a single item to the ArrayList. Does not prevent duplicates."," *"," * @method add"," * @param { mixed } item Item presumably of the same type as others in the"," * ArrayList."," * @param {Number} index (Optional.) Number representing the position at"," * which the item should be inserted."," * @return {ArrayList} the instance."," * @for ArrayList"," * @deprecated Use ModelList or a custom ArrayList subclass"," * @chainable"," */"," add: function(item, index) {"," var items = this._items;",""," if (Y.Lang.isNumber(index)) {"," items.splice(index, 0, item);"," }"," else {"," items.push(item);"," }",""," return this;"," },",""," /**"," * Removes first or all occurrences of an item to the ArrayList. If a"," * comparator is not provided, uses itemsAreEqual method to determine"," * matches."," *"," * @method remove"," * @param { mixed } needle Item to find and remove from the list."," * @param { Boolean } all If true, remove all occurrences."," * @param { Function } comparator optional a/b function to test equivalence."," * @return {ArrayList} the instance."," * @for ArrayList"," * @deprecated Use ModelList or a custom ArrayList subclass"," * @chainable"," */"," remove: function(needle, all, comparator) {"," comparator = comparator || this.itemsAreEqual;",""," for (var i = this._items.length - 1; i >= 0; --i) {"," if (comparator.call(this, needle, this.item(i))) {"," this._items.splice(i, 1);"," if (!all) {"," break;"," }"," }"," }",""," return this;"," },",""," /**"," * Default comparator for items stored in this list. Used by remove()."," *"," * @method itemsAreEqual"," * @param { mixed } a item to test equivalence with."," * @param { mixed } b other item to test equivalance."," * @return { Boolean } true if items are deemed equivalent."," * @for ArrayList"," * @deprecated Use ModelList or a custom ArrayList subclass"," */"," itemsAreEqual: function(a, b) {"," return a === b;"," }","","});","","","}, '@VERSION@', {\"requires\": [\"arraylist\"]});"];
_yuitest_coverage["build/arraylist-add/arraylist-add.js"].lines = {"1":0,"13":0,"29":0,"31":0,"32":0,"35":0,"38":0,"56":0,"58":0,"59":0,"60":0,"61":0,"62":0,"67":0,"81":0};
_yuitest_coverage["build/arraylist-add/arraylist-add.js"].functions = {"add:28":0,"remove:55":0,"itemsAreEqual:80":0,"(anonymous 1):1":0};
_yuitest_coverage["build/arraylist-add/arraylist-add.js"].coveredLines = 15;
_yuitest_coverage["build/arraylist-add/arraylist-add.js"].coveredFunctions = 4;
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 1);
YUI.add('arraylist-add', function (Y, NAME) {
/**
* Collection utilities beyond what is provided in the YUI core
* @module collection
* @submodule arraylist-add
* @deprecated Use ModelList or a custom ArrayList subclass
*/
/*
* Adds methods add and remove to Y.ArrayList
*/
_yuitest_coverfunc("build/arraylist-add/arraylist-add.js", "(anonymous 1)", 1);
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 13);
Y.mix(Y.ArrayList.prototype, {
/**
* Add a single item to the ArrayList. Does not prevent duplicates.
*
* @method add
* @param { mixed } item Item presumably of the same type as others in the
* ArrayList.
* @param {Number} index (Optional.) Number representing the position at
* which the item should be inserted.
* @return {ArrayList} the instance.
* @for ArrayList
* @deprecated Use ModelList or a custom ArrayList subclass
* @chainable
*/
add: function(item, index) {
_yuitest_coverfunc("build/arraylist-add/arraylist-add.js", "add", 28);
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 29);
var items = this._items;
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 31);
if (Y.Lang.isNumber(index)) {
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 32);
items.splice(index, 0, item);
}
else {
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 35);
items.push(item);
}
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 38);
return this;
},
/**
* Removes first or all occurrences of an item to the ArrayList. If a
* comparator is not provided, uses itemsAreEqual method to determine
* matches.
*
* @method remove
* @param { mixed } needle Item to find and remove from the list.
* @param { Boolean } all If true, remove all occurrences.
* @param { Function } comparator optional a/b function to test equivalence.
* @return {ArrayList} the instance.
* @for ArrayList
* @deprecated Use ModelList or a custom ArrayList subclass
* @chainable
*/
remove: function(needle, all, comparator) {
_yuitest_coverfunc("build/arraylist-add/arraylist-add.js", "remove", 55);
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 56);
comparator = comparator || this.itemsAreEqual;
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 58);
for (var i = this._items.length - 1; i >= 0; --i) {
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 59);
if (comparator.call(this, needle, this.item(i))) {
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 60);
this._items.splice(i, 1);
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 61);
if (!all) {
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 62);
break;
}
}
}
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 67);
return this;
},
/**
* Default comparator for items stored in this list. Used by remove().
*
* @method itemsAreEqual
* @param { mixed } a item to test equivalence with.
* @param { mixed } b other item to test equivalance.
* @return { Boolean } true if items are deemed equivalent.
* @for ArrayList
* @deprecated Use ModelList or a custom ArrayList subclass
*/
itemsAreEqual: function(a, b) {
_yuitest_coverfunc("build/arraylist-add/arraylist-add.js", "itemsAreEqual", 80);
_yuitest_coverline("build/arraylist-add/arraylist-add.js", 81);
return a === b;
}
});
}, '@VERSION@', {"requires": ["arraylist"]});
| binki/cdnjs | ajax/libs/yui/3.8.0/arraylist-add/arraylist-add-coverage.js | JavaScript | mit | 7,862 |
if (typeof _yuitest_coverage == "undefined"){
_yuitest_coverage = {};
_yuitest_coverline = function(src, line){
var coverage = _yuitest_coverage[src];
if (!coverage.lines[line]){
coverage.calledLines++;
}
coverage.lines[line]++;
};
_yuitest_coverfunc = function(src, name, line){
var coverage = _yuitest_coverage[src],
funcId = name + ":" + line;
if (!coverage.functions[funcId]){
coverage.calledFunctions++;
}
coverage.functions[funcId]++;
};
}
_yuitest_coverage["build/align-plugin/align-plugin.js"] = {
lines: {},
functions: {},
coveredLines: 0,
calledLines: 0,
coveredFunctions: 0,
calledFunctions: 0,
path: "build/align-plugin/align-plugin.js",
code: []
};
_yuitest_coverage["build/align-plugin/align-plugin.js"].code=["YUI.add('align-plugin', function (Y, NAME) {",""," /**"," * Provides advanced positioning support for Node via a Plugin"," * for centering and alignment. "," * @module align-plugin"," */",""," var OFFSET_WIDTH = 'offsetWidth',"," OFFSET_HEIGHT = 'offsetHeight',"," undefined = undefined;",""," /**"," * Node plugin which can be used to align a node with another node,"," * region, or the viewport."," *"," * @class Plugin.Align"," * @param {Object} User configuration object"," */"," function Align(config) {"," if (config.host) {"," this._host = config.host;"," }"," }"," "," Align.prototype = {"," /**"," * Aligns node with a point on another node or region."," * Possible alignment points are:"," * <dl>"," * <dt>tl</dt>"," * <dd>top left</dd>"," * <dt>tr</dt>"," * <dd>top right</dd>"," * <dt>bl</dt>"," * <dd>bottom left</dd>"," * <dt>br</dt>"," * <dd>bottom right</dd>"," * <dt>tc</dt>"," * <dd>top center</dd>"," * <dt>bc</dt>"," * <dd>bottom center</dd>"," * <dt>rc</dt>"," * <dd>right center</dd>"," * <dt>lc</dt>"," * <dd>left center</dd>"," * <dt>cc</dt>"," * <dd>center center</dd>"," * </dl>"," * @method to "," * @param region {String || Node || HTMLElement || Object} The node or"," * region to align with. Defaults to the viewport region."," * @param regionPoint {String} The point of the region to align with."," * @param point {String} The point of the node aligned to the region. "," * @param resize {Boolean} Whether or not the node should re-align when"," * the window is resized. Defaults to false."," */"," to: function(region, regionPoint, point, syncOnResize) {"," // cache original args for syncing"," this._syncArgs = Y.Array(arguments);",""," if (region.top === undefined) {"," region = Y.one(region).get('region');"," }",""," if (region) {"," var xy = [region.left, region.top],"," offxy = [region.width, region.height],"," points = Align.points,"," node = this._host,"," NULL = null,"," size = node.getAttrs([OFFSET_HEIGHT, OFFSET_WIDTH]),"," nodeoff = [0 - size[OFFSET_WIDTH], 0 - size[OFFSET_HEIGHT]], // reverse offsets"," regionFn0 = regionPoint ? points[regionPoint.charAt(0)]: NULL,"," regionFn1 = (regionPoint && regionPoint !== 'cc') ? points[regionPoint.charAt(1)] : NULL,"," nodeFn0 = point ? points[point.charAt(0)] : NULL,"," nodeFn1 = (point && point !== 'cc') ? points[point.charAt(1)] : NULL;",""," if (regionFn0) {"," xy = regionFn0(xy, offxy, regionPoint);"," }"," if (regionFn1) {"," xy = regionFn1(xy, offxy, regionPoint);"," }",""," if (nodeFn0) {"," xy = nodeFn0(xy, nodeoff, point);"," }"," if (nodeFn1) {"," xy = nodeFn1(xy, nodeoff, point);"," }",""," if (xy && node) {"," node.setXY(xy);"," }"," "," this._resize(syncOnResize);",""," }"," return this;"," },",""," sync: function() {"," this.to.apply(this, this._syncArgs);"," return this;"," },",""," _resize: function(add) {"," var handle = this._handle;"," if (add && !handle) {"," this._handle = Y.on('resize', this._onresize, window, this);"," } else if (!add && handle) {"," handle.detach();"," }",""," },",""," _onresize: function() {"," var self = this;"," setTimeout(function() { // for performance"," self.sync();"," });"," },"," "," /**"," * Aligns the center of a node to the center of another node or region."," * @method center "," * @param region {Node || HTMLElement || Object} optional The node or"," * region to align with. Defaults to the viewport region."," * the window is resized. If centering to viewport, this defaults"," * to true, otherwise default is false."," */"," center: function(region, resize) {"," this.to(region, 'cc', 'cc', resize); "," return this;"," },",""," /**"," * Removes the resize handler, if any. This is called automatically"," * when unplugged from the host node."," * @method destroy "," */"," destroy: function() {"," var handle = this._handle;"," if (handle) {"," handle.detach();"," }"," }"," };",""," Align.points = {"," 't': function(xy, off) {"," return xy;"," },",""," 'r': function(xy, off) {"," return [xy[0] + off[0], xy[1]];"," },",""," 'b': function(xy, off) {"," return [xy[0], xy[1] + off[1]];"," },",""," 'l': function(xy, off) {"," return xy;"," },",""," 'c': function(xy, off, point) {"," var axis = (point[0] === 't' || point[0] === 'b') ? 0 : 1,"," ret, val;",""," if (point === 'cc') {"," ret = [xy[0] + off[0] / 2, xy[1] + off[1] / 2];"," } else {"," val = xy[axis] + off[axis] / 2;"," ret = (axis) ? [xy[0], val] : [val, xy[1]];"," }",""," return ret;"," }"," };",""," Align.NAME = 'Align';"," Align.NS = 'align';",""," Align.prototype.constructor = Align;",""," Y.namespace('Plugin');"," Y.Plugin.Align = Align;","","","","}, '@VERSION@', {\"requires\": [\"node-screen\", \"node-pluginhost\"]});"];
_yuitest_coverage["build/align-plugin/align-plugin.js"].lines = {"1":0,"9":0,"20":0,"21":0,"22":0,"26":0,"60":0,"62":0,"63":0,"66":0,"67":0,"79":0,"80":0,"82":0,"83":0,"86":0,"87":0,"89":0,"90":0,"93":0,"94":0,"97":0,"100":0,"104":0,"105":0,"109":0,"110":0,"111":0,"112":0,"113":0,"119":0,"120":0,"121":0,"134":0,"135":0,"144":0,"145":0,"146":0,"151":0,"153":0,"157":0,"161":0,"165":0,"169":0,"172":0,"173":0,"175":0,"176":0,"179":0,"183":0,"184":0,"186":0,"188":0,"189":0};
_yuitest_coverage["build/align-plugin/align-plugin.js"].functions = {"Align:20":0,"to:58":0,"sync:103":0,"_resize:108":0,"(anonymous 2):120":0,"_onresize:118":0,"center:133":0,"destroy:143":0,"\'t\':152":0,"\'r\':156":0,"\'b\':160":0,"\'l\':164":0,"\'c\':168":0,"(anonymous 1):1":0};
_yuitest_coverage["build/align-plugin/align-plugin.js"].coveredLines = 54;
_yuitest_coverage["build/align-plugin/align-plugin.js"].coveredFunctions = 14;
_yuitest_coverline("build/align-plugin/align-plugin.js", 1);
YUI.add('align-plugin', function (Y, NAME) {
/**
* Provides advanced positioning support for Node via a Plugin
* for centering and alignment.
* @module align-plugin
*/
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "(anonymous 1)", 1);
_yuitest_coverline("build/align-plugin/align-plugin.js", 9);
var OFFSET_WIDTH = 'offsetWidth',
OFFSET_HEIGHT = 'offsetHeight',
undefined = undefined;
/**
* Node plugin which can be used to align a node with another node,
* region, or the viewport.
*
* @class Plugin.Align
* @param {Object} User configuration object
*/
_yuitest_coverline("build/align-plugin/align-plugin.js", 20);
function Align(config) {
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "Align", 20);
_yuitest_coverline("build/align-plugin/align-plugin.js", 21);
if (config.host) {
_yuitest_coverline("build/align-plugin/align-plugin.js", 22);
this._host = config.host;
}
}
_yuitest_coverline("build/align-plugin/align-plugin.js", 26);
Align.prototype = {
/**
* Aligns node with a point on another node or region.
* Possible alignment points are:
* <dl>
* <dt>tl</dt>
* <dd>top left</dd>
* <dt>tr</dt>
* <dd>top right</dd>
* <dt>bl</dt>
* <dd>bottom left</dd>
* <dt>br</dt>
* <dd>bottom right</dd>
* <dt>tc</dt>
* <dd>top center</dd>
* <dt>bc</dt>
* <dd>bottom center</dd>
* <dt>rc</dt>
* <dd>right center</dd>
* <dt>lc</dt>
* <dd>left center</dd>
* <dt>cc</dt>
* <dd>center center</dd>
* </dl>
* @method to
* @param region {String || Node || HTMLElement || Object} The node or
* region to align with. Defaults to the viewport region.
* @param regionPoint {String} The point of the region to align with.
* @param point {String} The point of the node aligned to the region.
* @param resize {Boolean} Whether or not the node should re-align when
* the window is resized. Defaults to false.
*/
to: function(region, regionPoint, point, syncOnResize) {
// cache original args for syncing
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "to", 58);
_yuitest_coverline("build/align-plugin/align-plugin.js", 60);
this._syncArgs = Y.Array(arguments);
_yuitest_coverline("build/align-plugin/align-plugin.js", 62);
if (region.top === undefined) {
_yuitest_coverline("build/align-plugin/align-plugin.js", 63);
region = Y.one(region).get('region');
}
_yuitest_coverline("build/align-plugin/align-plugin.js", 66);
if (region) {
_yuitest_coverline("build/align-plugin/align-plugin.js", 67);
var xy = [region.left, region.top],
offxy = [region.width, region.height],
points = Align.points,
node = this._host,
NULL = null,
size = node.getAttrs([OFFSET_HEIGHT, OFFSET_WIDTH]),
nodeoff = [0 - size[OFFSET_WIDTH], 0 - size[OFFSET_HEIGHT]], // reverse offsets
regionFn0 = regionPoint ? points[regionPoint.charAt(0)]: NULL,
regionFn1 = (regionPoint && regionPoint !== 'cc') ? points[regionPoint.charAt(1)] : NULL,
nodeFn0 = point ? points[point.charAt(0)] : NULL,
nodeFn1 = (point && point !== 'cc') ? points[point.charAt(1)] : NULL;
_yuitest_coverline("build/align-plugin/align-plugin.js", 79);
if (regionFn0) {
_yuitest_coverline("build/align-plugin/align-plugin.js", 80);
xy = regionFn0(xy, offxy, regionPoint);
}
_yuitest_coverline("build/align-plugin/align-plugin.js", 82);
if (regionFn1) {
_yuitest_coverline("build/align-plugin/align-plugin.js", 83);
xy = regionFn1(xy, offxy, regionPoint);
}
_yuitest_coverline("build/align-plugin/align-plugin.js", 86);
if (nodeFn0) {
_yuitest_coverline("build/align-plugin/align-plugin.js", 87);
xy = nodeFn0(xy, nodeoff, point);
}
_yuitest_coverline("build/align-plugin/align-plugin.js", 89);
if (nodeFn1) {
_yuitest_coverline("build/align-plugin/align-plugin.js", 90);
xy = nodeFn1(xy, nodeoff, point);
}
_yuitest_coverline("build/align-plugin/align-plugin.js", 93);
if (xy && node) {
_yuitest_coverline("build/align-plugin/align-plugin.js", 94);
node.setXY(xy);
}
_yuitest_coverline("build/align-plugin/align-plugin.js", 97);
this._resize(syncOnResize);
}
_yuitest_coverline("build/align-plugin/align-plugin.js", 100);
return this;
},
sync: function() {
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "sync", 103);
_yuitest_coverline("build/align-plugin/align-plugin.js", 104);
this.to.apply(this, this._syncArgs);
_yuitest_coverline("build/align-plugin/align-plugin.js", 105);
return this;
},
_resize: function(add) {
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "_resize", 108);
_yuitest_coverline("build/align-plugin/align-plugin.js", 109);
var handle = this._handle;
_yuitest_coverline("build/align-plugin/align-plugin.js", 110);
if (add && !handle) {
_yuitest_coverline("build/align-plugin/align-plugin.js", 111);
this._handle = Y.on('resize', this._onresize, window, this);
} else {_yuitest_coverline("build/align-plugin/align-plugin.js", 112);
if (!add && handle) {
_yuitest_coverline("build/align-plugin/align-plugin.js", 113);
handle.detach();
}}
},
_onresize: function() {
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "_onresize", 118);
_yuitest_coverline("build/align-plugin/align-plugin.js", 119);
var self = this;
_yuitest_coverline("build/align-plugin/align-plugin.js", 120);
setTimeout(function() { // for performance
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "(anonymous 2)", 120);
_yuitest_coverline("build/align-plugin/align-plugin.js", 121);
self.sync();
});
},
/**
* Aligns the center of a node to the center of another node or region.
* @method center
* @param region {Node || HTMLElement || Object} optional The node or
* region to align with. Defaults to the viewport region.
* the window is resized. If centering to viewport, this defaults
* to true, otherwise default is false.
*/
center: function(region, resize) {
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "center", 133);
_yuitest_coverline("build/align-plugin/align-plugin.js", 134);
this.to(region, 'cc', 'cc', resize);
_yuitest_coverline("build/align-plugin/align-plugin.js", 135);
return this;
},
/**
* Removes the resize handler, if any. This is called automatically
* when unplugged from the host node.
* @method destroy
*/
destroy: function() {
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "destroy", 143);
_yuitest_coverline("build/align-plugin/align-plugin.js", 144);
var handle = this._handle;
_yuitest_coverline("build/align-plugin/align-plugin.js", 145);
if (handle) {
_yuitest_coverline("build/align-plugin/align-plugin.js", 146);
handle.detach();
}
}
};
_yuitest_coverline("build/align-plugin/align-plugin.js", 151);
Align.points = {
't': function(xy, off) {
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "\'t\'", 152);
_yuitest_coverline("build/align-plugin/align-plugin.js", 153);
return xy;
},
'r': function(xy, off) {
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "\'r\'", 156);
_yuitest_coverline("build/align-plugin/align-plugin.js", 157);
return [xy[0] + off[0], xy[1]];
},
'b': function(xy, off) {
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "\'b\'", 160);
_yuitest_coverline("build/align-plugin/align-plugin.js", 161);
return [xy[0], xy[1] + off[1]];
},
'l': function(xy, off) {
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "\'l\'", 164);
_yuitest_coverline("build/align-plugin/align-plugin.js", 165);
return xy;
},
'c': function(xy, off, point) {
_yuitest_coverfunc("build/align-plugin/align-plugin.js", "\'c\'", 168);
_yuitest_coverline("build/align-plugin/align-plugin.js", 169);
var axis = (point[0] === 't' || point[0] === 'b') ? 0 : 1,
ret, val;
_yuitest_coverline("build/align-plugin/align-plugin.js", 172);
if (point === 'cc') {
_yuitest_coverline("build/align-plugin/align-plugin.js", 173);
ret = [xy[0] + off[0] / 2, xy[1] + off[1] / 2];
} else {
_yuitest_coverline("build/align-plugin/align-plugin.js", 175);
val = xy[axis] + off[axis] / 2;
_yuitest_coverline("build/align-plugin/align-plugin.js", 176);
ret = (axis) ? [xy[0], val] : [val, xy[1]];
}
_yuitest_coverline("build/align-plugin/align-plugin.js", 179);
return ret;
}
};
_yuitest_coverline("build/align-plugin/align-plugin.js", 183);
Align.NAME = 'Align';
_yuitest_coverline("build/align-plugin/align-plugin.js", 184);
Align.NS = 'align';
_yuitest_coverline("build/align-plugin/align-plugin.js", 186);
Align.prototype.constructor = Align;
_yuitest_coverline("build/align-plugin/align-plugin.js", 188);
Y.namespace('Plugin');
_yuitest_coverline("build/align-plugin/align-plugin.js", 189);
Y.Plugin.Align = Align;
}, '@VERSION@', {"requires": ["node-screen", "node-pluginhost"]});
| barcadictni/cdnjs | ajax/libs/yui/3.7.2/align-plugin/align-plugin-coverage.js | JavaScript | mit | 18,494 |
if (typeof _yuitest_coverage == "undefined"){
_yuitest_coverage = {};
_yuitest_coverline = function(src, line){
var coverage = _yuitest_coverage[src];
if (!coverage.lines[line]){
coverage.calledLines++;
}
coverage.lines[line]++;
};
_yuitest_coverfunc = function(src, name, line){
var coverage = _yuitest_coverage[src],
funcId = name + ":" + line;
if (!coverage.functions[funcId]){
coverage.calledFunctions++;
}
coverage.functions[funcId]++;
};
}
_yuitest_coverage["build/node-screen/node-screen.js"] = {
lines: {},
functions: {},
coveredLines: 0,
calledLines: 0,
coveredFunctions: 0,
calledFunctions: 0,
path: "build/node-screen/node-screen.js",
code: []
};
_yuitest_coverage["build/node-screen/node-screen.js"].code=["YUI.add('node-screen', function (Y, NAME) {","","/**"," * Extended Node interface for managing regions and screen positioning."," * Adds support for positioning elements and normalizes window size and scroll detection. "," * @module node"," * @submodule node-screen"," */","","// these are all \"safe\" returns, no wrapping required","Y.each(["," /**"," * Returns the inner width of the viewport (exludes scrollbar). "," * @config winWidth"," * @for Node"," * @type {Int}"," */"," 'winWidth',",""," /**"," * Returns the inner height of the viewport (exludes scrollbar). "," * @config winHeight"," * @type {Int}"," */"," 'winHeight',",""," /**"," * Document width "," * @config docWidth"," * @type {Int}"," */"," 'docWidth',",""," /**"," * Document height "," * @config docHeight"," * @type {Int}"," */"," 'docHeight',",""," /**"," * Pixel distance the page has been scrolled horizontally "," * @config docScrollX"," * @type {Int}"," */"," 'docScrollX',",""," /**"," * Pixel distance the page has been scrolled vertically "," * @config docScrollY"," * @type {Int}"," */"," 'docScrollY'"," ],"," function(name) {"," Y.Node.ATTRS[name] = {"," getter: function() {"," var args = Array.prototype.slice.call(arguments);"," args.unshift(Y.Node.getDOMNode(this));",""," return Y.DOM[name].apply(this, args);"," }"," };"," }",");","","Y.Node.ATTRS.scrollLeft = {"," getter: function() {"," var node = Y.Node.getDOMNode(this);"," return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node);"," },",""," setter: function(val) {"," var node = Y.Node.getDOMNode(this);"," if (node) {"," if ('scrollLeft' in node) {"," node.scrollLeft = val;"," } else if (node.document || node.nodeType === 9) {"," Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc"," }"," } else {"," }"," }","};","","Y.Node.ATTRS.scrollTop = {"," getter: function() {"," var node = Y.Node.getDOMNode(this);"," return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node);"," },",""," setter: function(val) {"," var node = Y.Node.getDOMNode(this);"," if (node) {"," if ('scrollTop' in node) {"," node.scrollTop = val;"," } else if (node.document || node.nodeType === 9) {"," Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc"," }"," } else {"," }"," }","};","","Y.Node.importMethod(Y.DOM, [","/**"," * Gets the current position of the node in page coordinates. "," * @method getXY"," * @for Node"," * @return {Array} The XY position of the node","*/"," 'getXY',","","/**"," * Set the position of the node in page coordinates, regardless of how the node is positioned."," * @method setXY"," * @param {Array} xy Contains X & Y values for new position (coordinates are page-based)"," * @chainable"," */"," 'setXY',","","/**"," * Gets the current position of the node in page coordinates. "," * @method getX"," * @return {Int} The X position of the node","*/"," 'getX',","","/**"," * Set the position of the node in page coordinates, regardless of how the node is positioned."," * @method setX"," * @param {Int} x X value for new position (coordinates are page-based)"," * @chainable"," */"," 'setX',","","/**"," * Gets the current position of the node in page coordinates. "," * @method getY"," * @return {Int} The Y position of the node","*/"," 'getY',","","/**"," * Set the position of the node in page coordinates, regardless of how the node is positioned."," * @method setY"," * @param {Int} y Y value for new position (coordinates are page-based)"," * @chainable"," */"," 'setY',","","/**"," * Swaps the XY position of this node with another node. "," * @method swapXY"," * @param {Node | HTMLElement} otherNode The node to swap with."," * @chainable"," */"," 'swapXY'","]);","","/**"," * @module node"," * @submodule node-screen"," */","","/**"," * Returns a region object for the node"," * @config region"," * @for Node"," * @type Node"," */","Y.Node.ATTRS.region = {"," getter: function() {"," var node = this.getDOMNode(),"," region;",""," if (node && !node.tagName) {"," if (node.nodeType === 9) { // document"," node = node.documentElement;"," }"," }"," if (Y.DOM.isWindow(node)) {"," region = Y.DOM.viewportRegion(node);"," } else {"," region = Y.DOM.region(node);"," }"," return region;"," }","};","","/**"," * Returns a region object for the node's viewport"," * @config viewportRegion"," * @type Node"," */","Y.Node.ATTRS.viewportRegion = {"," getter: function() {"," return Y.DOM.viewportRegion(Y.Node.getDOMNode(this));"," }","};","","Y.Node.importMethod(Y.DOM, 'inViewportRegion');","","// these need special treatment to extract 2nd node arg","/**"," * Compares the intersection of the node with another node or region"," * @method intersect"," * @for Node"," * @param {Node|Object} node2 The node or region to compare with."," * @param {Object} altRegion An alternate region to use (rather than this node's)."," * @return {Object} An object representing the intersection of the regions."," */","Y.Node.prototype.intersect = function(node2, altRegion) {"," var node1 = Y.Node.getDOMNode(this);"," if (Y.instanceOf(node2, Y.Node)) { // might be a region object"," node2 = Y.Node.getDOMNode(node2);"," }"," return Y.DOM.intersect(node1, node2, altRegion);","};","","/**"," * Determines whether or not the node is within the giving region."," * @method inRegion"," * @param {Node|Object} node2 The node or region to compare with."," * @param {Boolean} all Whether or not all of the node must be in the region."," * @param {Object} altRegion An alternate region to use (rather than this node's)."," * @return {Object} An object representing the intersection of the regions."," */","Y.Node.prototype.inRegion = function(node2, all, altRegion) {"," var node1 = Y.Node.getDOMNode(this);"," if (Y.instanceOf(node2, Y.Node)) { // might be a region object"," node2 = Y.Node.getDOMNode(node2);"," }"," return Y.DOM.inRegion(node1, node2, all, altRegion);","};","","","}, '@VERSION@', {\"requires\": [\"dom-screen\", \"node-base\"]});"];
_yuitest_coverage["build/node-screen/node-screen.js"].lines = {"1":0,"11":0,"56":0,"58":0,"59":0,"61":0,"67":0,"69":0,"70":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"86":0,"88":0,"89":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"105":0,"172":0,"174":0,"177":0,"178":0,"179":0,"182":0,"183":0,"185":0,"187":0,"196":0,"198":0,"202":0,"213":0,"214":0,"215":0,"216":0,"218":0,"229":0,"230":0,"231":0,"232":0,"234":0};
_yuitest_coverage["build/node-screen/node-screen.js"].functions = {"getter:57":0,"(anonymous 2):55":0,"getter:68":0,"setter:73":0,"getter:87":0,"setter:92":0,"getter:173":0,"getter:197":0,"intersect:213":0,"inRegion:229":0,"(anonymous 1):1":0};
_yuitest_coverage["build/node-screen/node-screen.js"].coveredLines = 47;
_yuitest_coverage["build/node-screen/node-screen.js"].coveredFunctions = 11;
_yuitest_coverline("build/node-screen/node-screen.js", 1);
YUI.add('node-screen', function (Y, NAME) {
/**
* Extended Node interface for managing regions and screen positioning.
* Adds support for positioning elements and normalizes window size and scroll detection.
* @module node
* @submodule node-screen
*/
// these are all "safe" returns, no wrapping required
_yuitest_coverfunc("build/node-screen/node-screen.js", "(anonymous 1)", 1);
_yuitest_coverline("build/node-screen/node-screen.js", 11);
Y.each([
/**
* Returns the inner width of the viewport (exludes scrollbar).
* @config winWidth
* @for Node
* @type {Int}
*/
'winWidth',
/**
* Returns the inner height of the viewport (exludes scrollbar).
* @config winHeight
* @type {Int}
*/
'winHeight',
/**
* Document width
* @config docWidth
* @type {Int}
*/
'docWidth',
/**
* Document height
* @config docHeight
* @type {Int}
*/
'docHeight',
/**
* Pixel distance the page has been scrolled horizontally
* @config docScrollX
* @type {Int}
*/
'docScrollX',
/**
* Pixel distance the page has been scrolled vertically
* @config docScrollY
* @type {Int}
*/
'docScrollY'
],
function(name) {
_yuitest_coverfunc("build/node-screen/node-screen.js", "(anonymous 2)", 55);
_yuitest_coverline("build/node-screen/node-screen.js", 56);
Y.Node.ATTRS[name] = {
getter: function() {
_yuitest_coverfunc("build/node-screen/node-screen.js", "getter", 57);
_yuitest_coverline("build/node-screen/node-screen.js", 58);
var args = Array.prototype.slice.call(arguments);
_yuitest_coverline("build/node-screen/node-screen.js", 59);
args.unshift(Y.Node.getDOMNode(this));
_yuitest_coverline("build/node-screen/node-screen.js", 61);
return Y.DOM[name].apply(this, args);
}
};
}
);
_yuitest_coverline("build/node-screen/node-screen.js", 67);
Y.Node.ATTRS.scrollLeft = {
getter: function() {
_yuitest_coverfunc("build/node-screen/node-screen.js", "getter", 68);
_yuitest_coverline("build/node-screen/node-screen.js", 69);
var node = Y.Node.getDOMNode(this);
_yuitest_coverline("build/node-screen/node-screen.js", 70);
return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node);
},
setter: function(val) {
_yuitest_coverfunc("build/node-screen/node-screen.js", "setter", 73);
_yuitest_coverline("build/node-screen/node-screen.js", 74);
var node = Y.Node.getDOMNode(this);
_yuitest_coverline("build/node-screen/node-screen.js", 75);
if (node) {
_yuitest_coverline("build/node-screen/node-screen.js", 76);
if ('scrollLeft' in node) {
_yuitest_coverline("build/node-screen/node-screen.js", 77);
node.scrollLeft = val;
} else {_yuitest_coverline("build/node-screen/node-screen.js", 78);
if (node.document || node.nodeType === 9) {
_yuitest_coverline("build/node-screen/node-screen.js", 79);
Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc
}}
} else {
}
}
};
_yuitest_coverline("build/node-screen/node-screen.js", 86);
Y.Node.ATTRS.scrollTop = {
getter: function() {
_yuitest_coverfunc("build/node-screen/node-screen.js", "getter", 87);
_yuitest_coverline("build/node-screen/node-screen.js", 88);
var node = Y.Node.getDOMNode(this);
_yuitest_coverline("build/node-screen/node-screen.js", 89);
return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node);
},
setter: function(val) {
_yuitest_coverfunc("build/node-screen/node-screen.js", "setter", 92);
_yuitest_coverline("build/node-screen/node-screen.js", 93);
var node = Y.Node.getDOMNode(this);
_yuitest_coverline("build/node-screen/node-screen.js", 94);
if (node) {
_yuitest_coverline("build/node-screen/node-screen.js", 95);
if ('scrollTop' in node) {
_yuitest_coverline("build/node-screen/node-screen.js", 96);
node.scrollTop = val;
} else {_yuitest_coverline("build/node-screen/node-screen.js", 97);
if (node.document || node.nodeType === 9) {
_yuitest_coverline("build/node-screen/node-screen.js", 98);
Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc
}}
} else {
}
}
};
_yuitest_coverline("build/node-screen/node-screen.js", 105);
Y.Node.importMethod(Y.DOM, [
/**
* Gets the current position of the node in page coordinates.
* @method getXY
* @for Node
* @return {Array} The XY position of the node
*/
'getXY',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setXY
* @param {Array} xy Contains X & Y values for new position (coordinates are page-based)
* @chainable
*/
'setXY',
/**
* Gets the current position of the node in page coordinates.
* @method getX
* @return {Int} The X position of the node
*/
'getX',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setX
* @param {Int} x X value for new position (coordinates are page-based)
* @chainable
*/
'setX',
/**
* Gets the current position of the node in page coordinates.
* @method getY
* @return {Int} The Y position of the node
*/
'getY',
/**
* Set the position of the node in page coordinates, regardless of how the node is positioned.
* @method setY
* @param {Int} y Y value for new position (coordinates are page-based)
* @chainable
*/
'setY',
/**
* Swaps the XY position of this node with another node.
* @method swapXY
* @param {Node | HTMLElement} otherNode The node to swap with.
* @chainable
*/
'swapXY'
]);
/**
* @module node
* @submodule node-screen
*/
/**
* Returns a region object for the node
* @config region
* @for Node
* @type Node
*/
_yuitest_coverline("build/node-screen/node-screen.js", 172);
Y.Node.ATTRS.region = {
getter: function() {
_yuitest_coverfunc("build/node-screen/node-screen.js", "getter", 173);
_yuitest_coverline("build/node-screen/node-screen.js", 174);
var node = this.getDOMNode(),
region;
_yuitest_coverline("build/node-screen/node-screen.js", 177);
if (node && !node.tagName) {
_yuitest_coverline("build/node-screen/node-screen.js", 178);
if (node.nodeType === 9) { // document
_yuitest_coverline("build/node-screen/node-screen.js", 179);
node = node.documentElement;
}
}
_yuitest_coverline("build/node-screen/node-screen.js", 182);
if (Y.DOM.isWindow(node)) {
_yuitest_coverline("build/node-screen/node-screen.js", 183);
region = Y.DOM.viewportRegion(node);
} else {
_yuitest_coverline("build/node-screen/node-screen.js", 185);
region = Y.DOM.region(node);
}
_yuitest_coverline("build/node-screen/node-screen.js", 187);
return region;
}
};
/**
* Returns a region object for the node's viewport
* @config viewportRegion
* @type Node
*/
_yuitest_coverline("build/node-screen/node-screen.js", 196);
Y.Node.ATTRS.viewportRegion = {
getter: function() {
_yuitest_coverfunc("build/node-screen/node-screen.js", "getter", 197);
_yuitest_coverline("build/node-screen/node-screen.js", 198);
return Y.DOM.viewportRegion(Y.Node.getDOMNode(this));
}
};
_yuitest_coverline("build/node-screen/node-screen.js", 202);
Y.Node.importMethod(Y.DOM, 'inViewportRegion');
// these need special treatment to extract 2nd node arg
/**
* Compares the intersection of the node with another node or region
* @method intersect
* @for Node
* @param {Node|Object} node2 The node or region to compare with.
* @param {Object} altRegion An alternate region to use (rather than this node's).
* @return {Object} An object representing the intersection of the regions.
*/
_yuitest_coverline("build/node-screen/node-screen.js", 213);
Y.Node.prototype.intersect = function(node2, altRegion) {
_yuitest_coverfunc("build/node-screen/node-screen.js", "intersect", 213);
_yuitest_coverline("build/node-screen/node-screen.js", 214);
var node1 = Y.Node.getDOMNode(this);
_yuitest_coverline("build/node-screen/node-screen.js", 215);
if (Y.instanceOf(node2, Y.Node)) { // might be a region object
_yuitest_coverline("build/node-screen/node-screen.js", 216);
node2 = Y.Node.getDOMNode(node2);
}
_yuitest_coverline("build/node-screen/node-screen.js", 218);
return Y.DOM.intersect(node1, node2, altRegion);
};
/**
* Determines whether or not the node is within the giving region.
* @method inRegion
* @param {Node|Object} node2 The node or region to compare with.
* @param {Boolean} all Whether or not all of the node must be in the region.
* @param {Object} altRegion An alternate region to use (rather than this node's).
* @return {Object} An object representing the intersection of the regions.
*/
_yuitest_coverline("build/node-screen/node-screen.js", 229);
Y.Node.prototype.inRegion = function(node2, all, altRegion) {
_yuitest_coverfunc("build/node-screen/node-screen.js", "inRegion", 229);
_yuitest_coverline("build/node-screen/node-screen.js", 230);
var node1 = Y.Node.getDOMNode(this);
_yuitest_coverline("build/node-screen/node-screen.js", 231);
if (Y.instanceOf(node2, Y.Node)) { // might be a region object
_yuitest_coverline("build/node-screen/node-screen.js", 232);
node2 = Y.Node.getDOMNode(node2);
}
_yuitest_coverline("build/node-screen/node-screen.js", 234);
return Y.DOM.inRegion(node1, node2, all, altRegion);
};
}, '@VERSION@', {"requires": ["dom-screen", "node-base"]});
| OnsenUI/cdnjs | ajax/libs/yui/3.7.2/node-screen/node-screen-coverage.js | JavaScript | mit | 18,147 |
if (typeof _yuitest_coverage == "undefined"){
_yuitest_coverage = {};
_yuitest_coverline = function(src, line){
var coverage = _yuitest_coverage[src];
if (!coverage.lines[line]){
coverage.calledLines++;
}
coverage.lines[line]++;
};
_yuitest_coverfunc = function(src, name, line){
var coverage = _yuitest_coverage[src],
funcId = name + ":" + line;
if (!coverage.functions[funcId]){
coverage.calledFunctions++;
}
coverage.functions[funcId]++;
};
}
_yuitest_coverage["build/highlight-accentfold/highlight-accentfold.js"] = {
lines: {},
functions: {},
coveredLines: 0,
calledLines: 0,
coveredFunctions: 0,
calledFunctions: 0,
path: "build/highlight-accentfold/highlight-accentfold.js",
code: []
};
_yuitest_coverage["build/highlight-accentfold/highlight-accentfold.js"].code=["YUI.add('highlight-accentfold', function (Y, NAME) {","","/**","Adds accent-folding highlighters to `Y.Highlight`.","","@module highlight","@submodule highlight-accentfold","**/","","/**","@class Highlight","@static","**/","","var AccentFold = Y.Text.AccentFold,"," Escape = Y.Escape,",""," EMPTY_OBJECT = {},","","Highlight = Y.mix(Y.Highlight, {"," // -- Public Static Methods ------------------------------------------------",""," /**"," Accent-folding version of `all()`.",""," @method allFold"," @param {String} haystack String to apply highlighting to."," @param {String|String[]} needles String or array of strings that should be"," highlighted."," @param {Object} [options] Options object."," @param {Boolean} [options.startsWith=false] If `true`, matches must be"," anchored to the beginning of the string."," @return {String} Escaped and highlighted copy of _haystack_."," @static"," **/"," allFold: function (haystack, needles, options) {"," var template = Highlight._TEMPLATE,"," results = [],"," startPos = 0,"," chunk, i, len, match, result;",""," options = Y.merge({"," // This tells Highlight.all() not to escape HTML, in order to ensure"," // usable match offsets. The output of all() is discarded, and we"," // perform our own escaping before returning the highlighted string."," escapeHTML: false,",""," // While the highlight regex operates on the accent-folded strings,"," // this replacer will highlight the matched positions in the"," // original string."," //"," // Note: this implementation doesn't handle multi-character folds,"," // like \"æ\" -> \"ae\". Doing so correctly would be prohibitively"," // expensive both in terms of code size and runtime performance, so"," // I've chosen to take the pragmatic route and just not do it at"," // all. This is one of many reasons why accent folding is best done"," // on the server."," replacer: function (match, p1, foldedNeedle, pos) {"," var len;",""," // Ignore matches inside HTML entities."," if (p1 && !(/\\s/).test(foldedNeedle)) {"," return match;"," }",""," len = foldedNeedle.length;",""," results.push(["," haystack.substring(startPos, pos), // substring between previous match and this match"," haystack.substr(pos, len) // match to be highlighted"," ]);",""," startPos = pos + len;"," }"," }, options || EMPTY_OBJECT);",""," // Run the highlighter on the folded strings. We don't care about the"," // output; our replacer function will build the canonical highlighted"," // string, with original accented characters."," Highlight.all(AccentFold.fold(haystack), AccentFold.fold(needles), options);",""," // Tack on the remainder of the haystack that wasn't highlighted, if"," // any."," if (startPos < haystack.length) {"," results.push([haystack.substr(startPos)]);"," }",""," // Highlight and escape the string."," for (i = 0, len = results.length; i < len; ++i) {"," chunk = Escape.html(results[i][0]);",""," if ((match = results[i][1])) {"," chunk += template.replace(/\\{s\\}/g, Escape.html(match));"," }",""," results[i] = chunk;"," }",""," return results.join('');"," },",""," /**"," Accent-folding version of `start()`.",""," @method startFold"," @param {String} haystack String to apply highlighting to."," @param {String|String[]} needles String or array of strings that should be"," highlighted."," @return {String} Escaped and highlighted copy of _haystack_."," @static"," **/"," startFold: function (haystack, needles) {"," return Highlight.allFold(haystack, needles, {startsWith: true});"," },",""," /**"," Accent-folding version of `words()`.",""," @method wordsFold"," @param {String} haystack String to apply highlighting to."," @param {String|String[]} needles String or array of strings containing words"," that should be highlighted. If a string is passed, it will be split"," into words; if an array is passed, it is assumed to have already been"," split."," @return {String} Escaped and highlighted copy of _haystack_."," @static"," **/"," wordsFold: function (haystack, needles) {"," var template = Highlight._TEMPLATE;",""," return Highlight.words(haystack, AccentFold.fold(needles), {"," mapper: function (word, needles) {"," if (needles.hasOwnProperty(AccentFold.fold(word))) {"," return template.replace(/\\{s\\}/g, Escape.html(word));"," }",""," return Escape.html(word);"," }"," });"," }","});","","","}, '@VERSION@', {\"requires\": [\"highlight-base\", \"text-accentfold\"]});"];
_yuitest_coverage["build/highlight-accentfold/highlight-accentfold.js"].lines = {"1":0,"15":0,"37":0,"42":0,"59":0,"62":0,"63":0,"66":0,"68":0,"73":0,"80":0,"84":0,"85":0,"89":0,"90":0,"92":0,"93":0,"96":0,"99":0,"113":0,"129":0,"131":0,"133":0,"134":0,"137":0};
_yuitest_coverage["build/highlight-accentfold/highlight-accentfold.js"].functions = {"replacer:58":0,"allFold:36":0,"startFold:112":0,"mapper:132":0,"wordsFold:128":0,"(anonymous 1):1":0};
_yuitest_coverage["build/highlight-accentfold/highlight-accentfold.js"].coveredLines = 25;
_yuitest_coverage["build/highlight-accentfold/highlight-accentfold.js"].coveredFunctions = 6;
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 1);
YUI.add('highlight-accentfold', function (Y, NAME) {
/**
Adds accent-folding highlighters to `Y.Highlight`.
@module highlight
@submodule highlight-accentfold
**/
/**
@class Highlight
@static
**/
_yuitest_coverfunc("build/highlight-accentfold/highlight-accentfold.js", "(anonymous 1)", 1);
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 15);
var AccentFold = Y.Text.AccentFold,
Escape = Y.Escape,
EMPTY_OBJECT = {},
Highlight = Y.mix(Y.Highlight, {
// -- Public Static Methods ------------------------------------------------
/**
Accent-folding version of `all()`.
@method allFold
@param {String} haystack String to apply highlighting to.
@param {String|String[]} needles String or array of strings that should be
highlighted.
@param {Object} [options] Options object.
@param {Boolean} [options.startsWith=false] If `true`, matches must be
anchored to the beginning of the string.
@return {String} Escaped and highlighted copy of _haystack_.
@static
**/
allFold: function (haystack, needles, options) {
_yuitest_coverfunc("build/highlight-accentfold/highlight-accentfold.js", "allFold", 36);
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 37);
var template = Highlight._TEMPLATE,
results = [],
startPos = 0,
chunk, i, len, match, result;
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 42);
options = Y.merge({
// This tells Highlight.all() not to escape HTML, in order to ensure
// usable match offsets. The output of all() is discarded, and we
// perform our own escaping before returning the highlighted string.
escapeHTML: false,
// While the highlight regex operates on the accent-folded strings,
// this replacer will highlight the matched positions in the
// original string.
//
// Note: this implementation doesn't handle multi-character folds,
// like "æ" -> "ae". Doing so correctly would be prohibitively
// expensive both in terms of code size and runtime performance, so
// I've chosen to take the pragmatic route and just not do it at
// all. This is one of many reasons why accent folding is best done
// on the server.
replacer: function (match, p1, foldedNeedle, pos) {
_yuitest_coverfunc("build/highlight-accentfold/highlight-accentfold.js", "replacer", 58);
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 59);
var len;
// Ignore matches inside HTML entities.
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 62);
if (p1 && !(/\s/).test(foldedNeedle)) {
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 63);
return match;
}
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 66);
len = foldedNeedle.length;
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 68);
results.push([
haystack.substring(startPos, pos), // substring between previous match and this match
haystack.substr(pos, len) // match to be highlighted
]);
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 73);
startPos = pos + len;
}
}, options || EMPTY_OBJECT);
// Run the highlighter on the folded strings. We don't care about the
// output; our replacer function will build the canonical highlighted
// string, with original accented characters.
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 80);
Highlight.all(AccentFold.fold(haystack), AccentFold.fold(needles), options);
// Tack on the remainder of the haystack that wasn't highlighted, if
// any.
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 84);
if (startPos < haystack.length) {
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 85);
results.push([haystack.substr(startPos)]);
}
// Highlight and escape the string.
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 89);
for (i = 0, len = results.length; i < len; ++i) {
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 90);
chunk = Escape.html(results[i][0]);
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 92);
if ((match = results[i][1])) {
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 93);
chunk += template.replace(/\{s\}/g, Escape.html(match));
}
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 96);
results[i] = chunk;
}
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 99);
return results.join('');
},
/**
Accent-folding version of `start()`.
@method startFold
@param {String} haystack String to apply highlighting to.
@param {String|String[]} needles String or array of strings that should be
highlighted.
@return {String} Escaped and highlighted copy of _haystack_.
@static
**/
startFold: function (haystack, needles) {
_yuitest_coverfunc("build/highlight-accentfold/highlight-accentfold.js", "startFold", 112);
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 113);
return Highlight.allFold(haystack, needles, {startsWith: true});
},
/**
Accent-folding version of `words()`.
@method wordsFold
@param {String} haystack String to apply highlighting to.
@param {String|String[]} needles String or array of strings containing words
that should be highlighted. If a string is passed, it will be split
into words; if an array is passed, it is assumed to have already been
split.
@return {String} Escaped and highlighted copy of _haystack_.
@static
**/
wordsFold: function (haystack, needles) {
_yuitest_coverfunc("build/highlight-accentfold/highlight-accentfold.js", "wordsFold", 128);
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 129);
var template = Highlight._TEMPLATE;
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 131);
return Highlight.words(haystack, AccentFold.fold(needles), {
mapper: function (word, needles) {
_yuitest_coverfunc("build/highlight-accentfold/highlight-accentfold.js", "mapper", 132);
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 133);
if (needles.hasOwnProperty(AccentFold.fold(word))) {
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 134);
return template.replace(/\{s\}/g, Escape.html(word));
}
_yuitest_coverline("build/highlight-accentfold/highlight-accentfold.js", 137);
return Escape.html(word);
}
});
}
});
}, '@VERSION@', {"requires": ["highlight-base", "text-accentfold"]});
| fredericksilva/cdnjs | ajax/libs/yui/3.9.0/highlight-accentfold/highlight-accentfold-coverage.js | JavaScript | mit | 14,203 |
if (typeof _yuitest_coverage == "undefined"){
_yuitest_coverage = {};
_yuitest_coverline = function(src, line){
var coverage = _yuitest_coverage[src];
if (!coverage.lines[line]){
coverage.calledLines++;
}
coverage.lines[line]++;
};
_yuitest_coverfunc = function(src, name, line){
var coverage = _yuitest_coverage[src],
funcId = name + ":" + line;
if (!coverage.functions[funcId]){
coverage.calledFunctions++;
}
coverage.functions[funcId]++;
};
}
_yuitest_coverage["build/app-base/app-base.js"] = {
lines: {},
functions: {},
coveredLines: 0,
calledLines: 0,
coveredFunctions: 0,
calledFunctions: 0,
path: "build/app-base/app-base.js",
code: []
};
_yuitest_coverage["build/app-base/app-base.js"].code=["YUI.add('app-base', function (Y, NAME) {","","/**","The App Framework provides simple MVC-like building blocks (models, model lists,","views, and URL-based routing) for writing single-page JavaScript applications.","","@main app","@module app","@since 3.4.0","**/","","/**","Provides a top-level application component which manages navigation and views.","","@module app","@submodule app-base","@since 3.5.0","**/","","// TODO: Better handling of lifecycle for registered views:","//","// * [!] Just redo basically everything with view management so there are no","// pre-`activeViewChange` side effects and handle the rest of these things:","//","// * Seems like any view created via `createView` should listen for the view's","// `destroy` event and use that to remove it from the `_viewsInfoMap`. I","// should look at what ModelList does for Models as a reference.","//","// * Should we have a companion `destroyView()` method? Maybe this wouldn't be","// needed if we have a `getView(name, create)` method, and already doing the","// above? We could do `app.getView('foo').destroy()` and it would be removed","// from the `_viewsInfoMap` as well.","//","// * Should we wait to call a view's `render()` method inside of the","// `_attachView()` method?","//","// * Should named views support a collection of instances instead of just one?","//","","var Lang = Y.Lang,"," YObject = Y.Object,",""," PjaxBase = Y.PjaxBase,"," Router = Y.Router,"," View = Y.View,",""," getClassName = Y.ClassNameManager.getClassName,",""," win = Y.config.win,",""," AppBase;","","/**","Provides a top-level application component which manages navigation and views.","","This gives you a foundation and structure on which to build your application; it","combines robust URL navigation with powerful routing and flexible view","management.","","@class App.Base","@param {Object} [config] The following are configuration properties that can be"," specified _in addition_ to default attribute values and the non-attribute"," properties provided by `Y.Base`:"," @param {Object} [config.views] Hash of view-name to metadata used to"," declaratively describe an application's views and their relationship with"," the app and other views. The views specified here will override any defaults"," provided by the `views` object on the `prototype`.","@constructor","@extends Base","@uses View","@uses Router","@uses PjaxBase","@since 3.5.0","**/","AppBase = Y.Base.create('app', Y.Base, [View, Router, PjaxBase], {"," // -- Public Properties ----------------------------------------------------",""," /**"," Hash of view-name to metadata used to declaratively describe an"," application's views and their relationship with the app and its other views.",""," The view metadata is composed of Objects keyed to a view-name that can have"," any or all of the following properties:",""," * `type`: Function or a string representing the view constructor to use to"," create view instances. If a string is used, the constructor function is"," assumed to be on the `Y` object; e.g. `\"SomeView\"` -> `Y.SomeView`.",""," * `preserve`: Boolean for whether the view instance should be retained. By"," default, the view instance will be destroyed when it is no longer the"," `activeView`. If `true` the view instance will simply be `removed()`"," from the DOM when it is no longer active. This is useful when the view"," is frequently used and may be expensive to re-create.",""," * `parent`: String to another named view in this hash that represents the"," parent view within the application's view hierarchy; e.g. a `\"photo\"`"," view could have `\"album\"` has its `parent` view. This parent/child"," relationship is a useful cue for things like transitions.",""," * `instance`: Used internally to manage the current instance of this named"," view. This can be used if your view instance is created up-front, or if"," you would rather manage the View lifecycle, but you probably should just"," let this be handled for you.",""," If `views` are specified at instantiation time, the metadata in the `views`"," Object here will be used as defaults when creating the instance's `views`.",""," Every `Y.App` instance gets its own copy of a `views` object so this Object"," on the prototype will not be polluted.",""," @example"," // Imagine that `Y.UsersView` and `Y.UserView` have been defined."," var app = new Y.App({"," views: {"," users: {"," type : Y.UsersView,"," preserve: true"," },",""," user: {"," type : Y.UserView,"," parent: 'users'"," }"," }"," });",""," @property views"," @type Object"," @default {}"," @since 3.5.0"," **/"," views: {},",""," // -- Protected Properties -------------------------------------------------",""," /**"," Map of view instance id (via `Y.stamp()`) to view-info object in `views`.",""," This mapping is used to tie a specific view instance back to its metadata by"," adding a reference to the the related view info on the `views` object.",""," @property _viewInfoMap"," @type Object"," @default {}"," @protected"," @since 3.5.0"," **/",""," // -- Lifecycle Methods ----------------------------------------------------"," initializer: function (config) {"," config || (config = {});",""," var views = {};",""," // Merges-in specified view metadata into local `views` object."," function mergeViewConfig(view, name) {"," views[name] = Y.merge(views[name], view);"," }",""," // First, each view in the `views` prototype object gets its metadata"," // merged-in, providing the defaults."," YObject.each(this.views, mergeViewConfig);",""," // Then, each view in the specified `config.views` object gets its"," // metadata merged-in."," YObject.each(config.views, mergeViewConfig);",""," // The resulting hodgepodge of metadata is then stored as the instance's"," // `views` object, and no one's objects were harmed in the making."," this.views = views;"," this._viewInfoMap = {};",""," // Using `bind()` to aid extensibility."," this.after('activeViewChange', Y.bind('_afterActiveViewChange', this));",""," // PjaxBase will bind click events when `html5` is `true`, so this just"," // forces the binding when `serverRouting` and `html5` are both falsy."," if (!this.get('serverRouting')) {"," this._pjaxBindUI();"," }"," },",""," // TODO: `destructor` to destroy the `activeView`?",""," // -- Public Methods -------------------------------------------------------",""," /**"," Creates and returns a new view instance using the provided `name` to look up"," the view info metadata defined in the `views` object. The passed-in `config`"," object is passed to the view constructor function.",""," This function also maps a view instance back to its view info metadata.",""," @method createView"," @param {String} name The name of a view defined on the `views` object."," @param {Object} [config] The configuration object passed to the view"," constructor function when creating the new view instance."," @return {View} The new view instance."," @since 3.5.0"," **/"," createView: function (name, config) {"," var viewInfo = this.getViewInfo(name),"," type = (viewInfo && viewInfo.type) || View,"," ViewConstructor, view;",""," // Looks for a namespaced constructor function on `Y`."," ViewConstructor = Lang.isString(type) ?"," YObject.getValue(Y, type.split('.')) : type;",""," // Create the view instance and map it with its metadata."," view = new ViewConstructor(config);"," this._viewInfoMap[Y.stamp(view, true)] = viewInfo;",""," return view;"," },",""," /**"," Returns the metadata associated with a view instance or view name defined on"," the `views` object.",""," @method getViewInfo"," @param {View|String} view View instance, or name of a view defined on the"," `views` object."," @return {Object} The metadata for the view, or `undefined` if the view is"," not registered."," @since 3.5.0"," **/"," getViewInfo: function (view) {"," if (Lang.isString(view)) {"," return this.views[view];"," }",""," return view && this._viewInfoMap[Y.stamp(view, true)];"," },",""," /**"," Navigates to the specified URL if there is a route handler that matches. In"," browsers capable of using HTML5 history or when `serverRouting` is falsy,"," the navigation will be enhanced by firing the `navigate` event and having"," the app handle the \"request\". When `serverRouting` is `true`, non-HTML5"," browsers will navigate to the new URL via a full page reload.",""," When there is a route handler for the specified URL and it is being"," navigated to, this method will return `true`, otherwise it will return"," `false`.",""," **Note:** The specified URL _must_ be of the same origin as the current URL,"," otherwise an error will be logged and navigation will not occur. This is"," intended as both a security constraint and a purposely imposed limitation as"," it does not make sense to tell the app to navigate to a URL on a"," different scheme, host, or port.",""," @method navigate"," @param {String} url The URL to navigate to. This must be of the same origin"," as the current URL."," @param {Object} [options] Additional options to configure the navigation."," These are mixed into the `navigate` event facade."," @param {Boolean} [options.replace] Whether or not the current history"," entry will be replaced, or a new entry will be created. Will default"," to `true` if the specified `url` is the same as the current URL."," @param {Boolean} [options.force] Whether the enhanced navigation"," should occur even in browsers without HTML5 history. Will default to"," `true` when `serverRouting` is falsy."," @see PjaxBase.navigate()"," **/"," // Does not override `navigate()` but does use extra `options`.",""," /**"," Renders this application by appending the `viewContainer` node to the"," `container` node if it isn't already a child of the container, and the"," `activeView` will be appended the view container, if it isn't already.",""," You should call this method at least once, usually after the initialization"," of your app instance so the proper DOM structure is setup and optionally"," append the container to the DOM if it's not there already.",""," You may override this method to customize the app's rendering, but you"," should expect that the `viewContainer`'s contents will be modified by the"," app for the purpose of rendering the `activeView` when it changes.",""," @method render"," @chainable"," @see View.render()"," **/"," render: function () {"," var CLASS_NAMES = Y.App.CLASS_NAMES,"," container = this.get('container'),"," viewContainer = this.get('viewContainer'),"," activeView = this.get('activeView'),"," activeViewContainer = activeView && activeView.get('container'),"," areSame = container.compareTo(viewContainer);",""," container.addClass(CLASS_NAMES.app);"," viewContainer.addClass(CLASS_NAMES.views);",""," // Prevents needless shuffling around of nodes and maintains DOM order."," if (activeView && !viewContainer.contains(activeViewContainer)) {"," viewContainer.appendChild(activeViewContainer);"," }",""," // Prevents needless shuffling around of nodes and maintains DOM order."," if (!container.contains(viewContainer) && !areSame) {"," container.appendChild(viewContainer);"," }",""," return this;"," },",""," /**"," Sets which view is active/visible for the application. This will set the"," app's `activeView` attribute to the specified `view`.",""," The `view` will be \"attached\" to this app, meaning it will be both rendered"," into this app's `viewContainer` node and all of its events will bubble to"," the app. The previous `activeView` will be \"detached\" from this app.",""," When a string-name is provided for a view which has been registered on this"," app's `views` object, the referenced metadata will be used and the"," `activeView` will be set to either a preserved view instance, or a new"," instance of the registered view will be created using the specified `config`"," object passed-into this method.",""," A callback function can be specified as either the third or fourth argument,"," and this function will be called after the new `view` becomes the"," `activeView`, is rendered to the `viewContainer`, and is ready to use.",""," @example"," var app = new Y.App({"," views: {"," usersView: {"," // Imagine that `Y.UsersView` has been defined."," type: Y.UsersView"," }"," },",""," users: new Y.ModelList()"," });",""," app.route('/users/', function () {"," this.showView('usersView', {users: this.get('users')});"," });",""," app.render();"," app.navigate('/uses/'); // => Creates a new `Y.UsersView` and shows it.",""," @method showView"," @param {String|View} view The name of a view defined in the `views` object,"," or a view instance which should become this app's `activeView`."," @param {Object} [config] Optional configuration to use when creating a new"," view instance. This config object can also be used to update an existing"," or preserved view's attributes when `options.update` is `true`."," @param {Object} [options] Optional object containing any of the following"," properties:"," @param {Function} [options.callback] Optional callback function to call"," after new `activeView` is ready to use, the function will be passed:"," @param {View} options.callback.view A reference to the new"," `activeView`."," @param {Boolean} [options.prepend=false] Whether the `view` should be"," prepended instead of appended to the `viewContainer`."," @param {Boolean} [options.render] Whether the `view` should be rendered."," **Note:** If no value is specified, a view instance will only be"," rendered if it's newly created by this method."," @param {Boolean} [options.update=false] Whether an existing view should"," have its attributes updated by passing the `config` object to its"," `setAttrs()` method. **Note:** This option does not have an effect if"," the `view` instance is created as a result of calling this method."," @param {Function} [callback] Optional callback Function to call after the"," new `activeView` is ready to use. **Note:** this will override"," `options.callback` and it can be specified as either the third or fourth"," argument. The function will be passed the following:"," @param {View} callback.view A reference to the new `activeView`."," @chainable"," @since 3.5.0"," **/"," showView: function (view, config, options, callback) {"," var viewInfo, created;",""," options || (options = {});",""," // Support the callback function being either the third or fourth arg."," if (callback) {"," options = Y.merge(options, {callback: callback});"," } else if (Lang.isFunction(options)) {"," options = {callback: options};"," }",""," if (Lang.isString(view)) {"," viewInfo = this.getViewInfo(view);",""," // Use the preserved view instance, or create a new view."," // TODO: Maybe we can remove the strict check for `preserve` and"," // assume we'll use a View instance if it is there, and just check"," // `preserve` when detaching?"," if (viewInfo && viewInfo.preserve && viewInfo.instance) {"," view = viewInfo.instance;",""," // Make sure there's a mapping back to the view metadata."," this._viewInfoMap[Y.stamp(view, true)] = viewInfo;"," } else {"," // TODO: Add the app as a bubble target during construction, but"," // make sure to check that it isn't already in `bubbleTargets`!"," // This will allow the app to be notified for about _all_ of the"," // view's events. **Note:** This should _only_ happen if the"," // view is created _after_ `activeViewChange`.",""," view = this.createView(view, config);"," created = true;"," }"," }",""," // Update the specified or preserved `view` when signaled to do so."," // There's no need to updated a view if it was _just_ created."," if (options.update && !created) {"," view.setAttrs(config);"," }",""," // TODO: Hold off on rendering the view until after it has been"," // \"attached\", and move the call to render into `_attachView()`.",""," // When a value is specified for `options.render`, prefer it because it"," // represents the developer's intent. When no value is specified, the"," // `view` will only be rendered if it was just created."," if ('render' in options) {"," if (options.render) {"," view.render();"," }"," } else if (created) {"," view.render();"," }",""," return this._set('activeView', view, {options: options});"," },",""," // -- Protected Methods ----------------------------------------------------",""," /**"," Helper method to attach the view instance to the application by making the"," app a bubble target of the view, append the view to the `viewContainer`, and"," assign it to the `instance` property of the associated view info metadata.",""," @method _attachView"," @param {View} view View to attach."," @param {Boolean} prepend=false Whether the view should be prepended instead"," of appended to the `viewContainer`."," @protected"," @since 3.5.0"," **/"," _attachView: function (view, prepend) {"," if (!view) {"," return;"," }",""," var viewInfo = this.getViewInfo(view),"," viewContainer = this.get('viewContainer');",""," // Bubble the view's events to this app."," view.addTarget(this);",""," // Save the view instance in the `views` registry."," if (viewInfo) {"," viewInfo.instance = view;"," }",""," // TODO: Attach events here for persevered Views?"," // See related TODO in `_detachView`.",""," // TODO: Actually render the view here so that it gets \"attached\" before"," // it gets rendered?",""," // Insert view into the DOM."," viewContainer[prepend ? 'prepend' : 'append'](view.get('container'));"," },",""," /**"," Overrides View's container destruction to deal with the `viewContainer` and"," checks to make sure not to remove and purge the `<body>`.",""," @method _destroyContainer"," @protected"," @see View._destroyContainer()"," **/"," _destroyContainer: function () {"," var CLASS_NAMES = Y.App.CLASS_NAMES,"," container = this.get('container'),"," viewContainer = this.get('viewContainer'),"," areSame = container.compareTo(viewContainer);",""," // We do not want to remove or destroy the `<body>`."," if (Y.one('body').compareTo(container)) {"," // Just clean-up our events listeners."," this.detachEvents();",""," // Clean-up `yui3-app` CSS class on the `container`."," container.removeClass(CLASS_NAMES.app);",""," if (areSame) {"," // Clean-up `yui3-app-views` CSS class on the `container`."," container.removeClass(CLASS_NAMES.views);"," } else {"," // Destroy and purge the `viewContainer`."," viewContainer.remove(true);"," }",""," return;"," }",""," // Remove and purge events from both containers.",""," viewContainer.remove(true);",""," if (!areSame) {"," container.remove(true);"," }"," },",""," /**"," Helper method to detach the view instance from the application by removing"," the application as a bubble target of the view, and either just removing the"," view if it is intended to be preserved, or destroying the instance"," completely.",""," @method _detachView"," @param {View} view View to detach."," @protected"," @since 3.5.0"," **/"," _detachView: function (view) {"," if (!view) {"," return;"," }",""," var viewInfo = this.getViewInfo(view) || {};",""," if (viewInfo.preserve) {"," view.remove();"," // TODO: Detach events here for preserved Views? It is possible that"," // some event subscriptions are made on elements other than the"," // View's `container`."," } else {"," view.destroy({remove: true});",""," // TODO: The following should probably happen automagically from"," // `destroy()` being called! Possibly `removeTarget()` as well.",""," // Remove from view to view-info map."," delete this._viewInfoMap[Y.stamp(view, true)];",""," // Remove from view-info instance property."," if (view === viewInfo.instance) {"," delete viewInfo.instance;"," }"," }",""," view.removeTarget(this);"," },",""," /**"," Getter for the `viewContainer` attribute.",""," @method _getViewContainer"," @param {Node|null} value Current attribute value."," @return {Node} View container node."," @protected"," @since 3.5.0"," **/"," _getViewContainer: function (value) {"," // This wackiness is necessary to enable fully lazy creation of the"," // container node both when no container is specified and when one is"," // specified via a valueFn.",""," if (!value && !this._viewContainer) {"," // Create a default container and set that as the new attribute"," // value. The `this._viewContainer` property prevents infinite"," // recursion."," value = this._viewContainer = this.create();"," this._set('viewContainer', value);"," }",""," return value;"," },",""," /**"," Provides the default value for the `html5` attribute.",""," The value returned is dependent on the value of the `serverRouting`"," attribute. When `serverRouting` is explicit set to `false` (not just falsy),"," the default value for `html5` will be set to `false` for *all* browsers.",""," When `serverRouting` is `true` or `undefined` the returned value will be"," dependent on the browser's capability of using HTML5 history.",""," @method _initHtml5"," @return {Boolean} Whether or not HTML5 history should be used."," @protected"," @since 3.5.0"," **/"," _initHtml5: function () {"," // When `serverRouting` is explicitly set to `false` (not just falsy),"," // forcing hash-based URLs in all browsers."," if (this.get('serverRouting') === false) {"," return false;"," }",""," // Defaults to whether or not the browser supports HTML5 history."," return Router.html5;"," },",""," /**"," Determines if the specified `view` is configured as a child of the specified"," `parent` view. This requires both views to be either named-views, or view"," instances created using configuration data that exists in the `views`"," object, e.g. created by the `createView()` or `showView()` method.",""," @method _isChildView"," @param {View|String} view The name of a view defined in the `views` object,"," or a view instance."," @param {View|String} parent The name of a view defined in the `views`"," object, or a view instance."," @return {Boolean} Whether the view is configured as a child of the parent."," @protected"," @since 3.5.0"," **/"," _isChildView: function (view, parent) {"," var viewInfo = this.getViewInfo(view),"," parentInfo = this.getViewInfo(parent);",""," if (viewInfo && parentInfo) {"," return this.getViewInfo(viewInfo.parent) === parentInfo;"," }",""," return false;"," },",""," /**"," Determines if the specified `view` is configured as the parent of the"," specified `child` view. This requires both views to be either named-views,"," or view instances created using configuration data that exists in the"," `views` object, e.g. created by the `createView()` or `showView()` method.",""," @method _isParentView"," @param {View|String} view The name of a view defined in the `views` object,"," or a view instance."," @param {View|String} parent The name of a view defined in the `views`"," object, or a view instance."," @return {Boolean} Whether the view is configured as the parent of the child."," @protected"," @since 3.5.0"," **/"," _isParentView: function (view, child) {"," var viewInfo = this.getViewInfo(view),"," childInfo = this.getViewInfo(child);",""," if (viewInfo && childInfo) {"," return this.getViewInfo(childInfo.parent) === viewInfo;"," }",""," return false;"," },",""," /**"," Underlying implementation for `navigate()`.",""," @method _navigate"," @param {String} url The fully-resolved URL that the app should dispatch to"," its route handlers to fulfill the enhanced navigation \"request\", or use to"," update `window.location` in non-HTML5 history capable browsers when"," `serverRouting` is `true`."," @param {Object} [options] Additional options to configure the navigation."," These are mixed into the `navigate` event facade."," @param {Boolean} [options.replace] Whether or not the current history"," entry will be replaced, or a new entry will be created. Will default"," to `true` if the specified `url` is the same as the current URL."," @param {Boolean} [options.force] Whether the enhanced navigation"," should occur even in browsers without HTML5 history. Will default to"," `true` when `serverRouting` is falsy."," @protected"," @see PjaxBase._navigate()"," **/"," _navigate: function (url, options) {"," if (!this.get('serverRouting')) {"," // Force navigation to be enhanced and handled by the app when"," // `serverRouting` is falsy because the server might not be able to"," // properly handle the request."," options = Y.merge({force: true}, options);"," }",""," return PjaxBase.prototype._navigate.call(this, url, options);"," },",""," /**"," Will either save a history entry using `pushState()` or the location hash,"," or gracefully-degrade to sending a request to the server causing a full-page"," reload.",""," Overrides Router's `_save()` method to preform graceful-degradation when the"," app's `serverRouting` is `true` and `html5` is `false` by updating the full"," URL via standard assignment to `window.location` or by calling"," `window.location.replace()`; both of which will cause a request to the"," server resulting in a full-page reload.",""," Otherwise this will just delegate off to Router's `_save()` method allowing"," the client-side enhanced routing to occur.",""," @method _save"," @param {String} [url] URL for the history entry."," @param {Boolean} [replace=false] If `true`, the current history entry will"," be replaced instead of a new one being added."," @chainable"," @protected"," @see Router._save()"," **/"," _save: function (url, replace) {"," var path;",""," // Forces full-path URLs to always be used by modifying"," // `window.location` in non-HTML5 history capable browsers."," if (this.get('serverRouting') && !this.get('html5')) {"," // Perform same-origin check on the specified URL."," if (!this._hasSameOrigin(url)) {"," Y.error('Security error: The new URL must be of the same origin as the current URL.');"," return this;"," }",""," // Either replace the current history entry or create a new one"," // while navigating to the `url`."," if (win) {"," // Results in the URL's full path starting with '/'."," path = this._joinURL(url || '');",""," if (replace) {"," win.location.replace(path);"," } else {"," win.location = path;"," }"," }",""," return this;"," }",""," return Router.prototype._save.apply(this, arguments);"," },",""," /**"," Performs the actual change of this app's `activeView` by attaching the"," `newView` to this app, and detaching the `oldView` from this app using any"," specified `options`.",""," The `newView` is attached to the app by rendering it to the `viewContainer`,"," and making this app a bubble target of its events.",""," The `oldView` is detached from the app by removing it from the"," `viewContainer`, and removing this app as a bubble target for its events."," The `oldView` will either be preserved or properly destroyed.",""," **Note:** The `activeView` attribute is read-only and can be changed by"," calling the `showView()` method.",""," @method _uiSetActiveView"," @param {View} newView The View which is now this app's `activeView`."," @param {View} [oldView] The View which was this app's `activeView`."," @param {Object} [options] Optional object containing any of the following"," properties:"," @param {Function} [options.callback] Optional callback function to call"," after new `activeView` is ready to use, the function will be passed:"," @param {View} options.callback.view A reference to the new"," `activeView`."," @param {Boolean} [options.prepend=false] Whether the `view` should be"," prepended instead of appended to the `viewContainer`."," @param {Boolean} [options.render] Whether the `view` should be rendered."," **Note:** If no value is specified, a view instance will only be"," rendered if it's newly created by this method."," @param {Boolean} [options.update=false] Whether an existing view should"," have its attributes updated by passing the `config` object to its"," `setAttrs()` method. **Note:** This option does not have an effect if"," the `view` instance is created as a result of calling this method."," @protected"," @since 3.5.0"," **/"," _uiSetActiveView: function (newView, oldView, options) {"," options || (options = {});",""," var callback = options.callback,"," isChild = this._isChildView(newView, oldView),"," isParent = !isChild && this._isParentView(newView, oldView),"," prepend = !!options.prepend || isParent;",""," // Prevent detaching (thus removing) the view we want to show. Also hard"," // to animate out and in, the same view."," if (newView === oldView) {"," return callback && callback.call(this, newView);"," }",""," this._attachView(newView, prepend);"," this._detachView(oldView);",""," if (callback) {"," callback.call(this, newView);"," }"," },",""," // -- Protected Event Handlers ---------------------------------------------",""," /**"," Handles the application's `activeViewChange` event (which is fired when the"," `activeView` attribute changes) by detaching the old view, attaching the new"," view.",""," The `activeView` attribute is read-only, so the public API to change its"," value is through the `showView()` method.",""," @method _afterActiveViewChange"," @param {EventFacade} e"," @protected"," @since 3.5.0"," **/"," _afterActiveViewChange: function (e) {"," this._uiSetActiveView(e.newVal, e.prevVal, e.options);"," }","}, {"," ATTRS: {"," /**"," The application's active/visible view.",""," This attribute is read-only, to set the `activeView` use the"," `showView()` method.",""," @attribute activeView"," @type View"," @default null"," @readOnly"," @see App.Base.showView()"," @since 3.5.0"," **/"," activeView: {"," value : null,"," readOnly: true"," },",""," /**"," Container node which represents the application's bounding-box, into"," which this app's content will be rendered.",""," The container node serves as the host for all DOM events attached by the"," app. Delegation is used to handle events on children of the container,"," allowing the container's contents to be re-rendered at any time without"," losing event subscriptions.",""," The default container is the `<body>` Node, but you can override this in"," a subclass, or by passing in a custom `container` config value at"," instantiation time.",""," When `container` is overridden by a subclass or passed as a config"," option at instantiation time, it may be provided as a selector string, a"," DOM element, or a `Y.Node` instance. During initialization, this app's"," `create()` method will be called to convert the container into a"," `Y.Node` instance if it isn't one already and stamp it with the CSS"," class: `\"yui3-app\"`.",""," The container is not added to the page automatically. This allows you to"," have full control over how and when your app is actually rendered to"," the page.",""," @attribute container"," @type HTMLElement|Node|String"," @default Y.one('body')"," @initOnly"," **/"," container: {"," valueFn: function () {"," return Y.one('body');"," }"," },",""," /**"," Whether or not this browser is capable of using HTML5 history.",""," This value is dependent on the value of `serverRouting` and will default"," accordingly.",""," Setting this to `false` will force the use of hash-based history even on"," HTML5 browsers, but please don't do this unless you understand the"," consequences.",""," @attribute html5"," @type Boolean"," @initOnly"," @see serverRouting"," **/"," html5: {"," valueFn: '_initHtml5'"," },",""," /**"," CSS selector string used to filter link click events so that only the"," links which match it will have the enhanced-navigation behavior of pjax"," applied.",""," When a link is clicked and that link matches this selector, navigating"," to the link's `href` URL using the enhanced, pjax, behavior will be"," attempted; and the browser's default way to navigate to new pages will"," be the fallback.",""," By default this selector will match _all_ links on the page.",""," @attribute linkSelector"," @type String|Function"," @default \"a\""," **/"," linkSelector: {"," value: 'a'"," },",""," /**"," Whether or not this application's server is capable of properly routing"," all requests and rendering the initial state in the HTML responses.",""," This can have three different values, each having particular"," implications on how the app will handle routing and navigation:",""," * `undefined`: The best form of URLs will be chosen based on the"," capabilities of the browser. Given no information about the server"," environmentm a balanced approach to routing and navigation is"," chosen.",""," The server should be capable of handling full-path requests, since"," full-URLs will be generated by browsers using HTML5 history. If this"," is a client-side-only app the server could handle full-URL requests"," by sending a redirect back to the root with a hash-based URL, e.g:",""," Request: http://example.com/users/1"," Redirect to: http://example.com/#/users/1",""," * `true`: The server is *fully* capable of properly handling requests"," to all full-path URLs the app can produce.",""," This is the best option for progressive-enhancement because it will"," cause **all URLs to always have full-paths**, which means the server"," will be able to accurately handle all URLs this app produces. e.g.",""," http://example.com/users/1",""," To meet this strict full-URL requirement, browsers which are not"," capable of using HTML5 history will make requests to the server"," resulting in full-page reloads.",""," * `false`: The server is *not* capable of properly handling requests"," to all full-path URLs the app can produce, therefore all routing"," will be handled by this App instance.",""," Be aware that this will cause **all URLs to always be hash-based**,"," even in browsers that are capable of using HTML5 history. e.g.",""," http://example.com/#/users/1",""," A single-page or client-side-only app where the server sends a"," \"shell\" page with JavaScript to the client might have this"," restriction. If you're setting this to `false`, read the following:",""," **Note:** When this is set to `false`, the server will *never* receive"," the full URL because browsers do not send the fragment-part to the"," server, that is everything after and including the \"#\".",""," Consider the following example:",""," URL shown in browser: http://example.com/#/users/1"," URL sent to server: http://example.com/",""," You should feel bad about hurting our precious web if you forcefully set"," either `serverRouting` or `html5` to `false`, because you're basically"," punching the web in the face here with your lossy URLs! Please make sure"," you know what you're doing and that you understand the implications.",""," Ideally you should always prefer full-path URLs (not /#/foo/), and want"," full-page reloads when the client's browser is not capable of enhancing"," the experience using the HTML5 history APIs. Setting this to `true` is"," the best option for progressive-enhancement (and graceful-degradation).",""," @attribute serverRouting"," @type Boolean"," @default undefined"," @initOnly"," @since 3.5.0"," **/"," serverRouting: {"," valueFn : function () { return Y.App.serverRouting; },"," writeOnce: 'initOnly'"," },",""," /**"," The node into which this app's `views` will be rendered when they become"," the `activeView`.",""," The view container node serves as the container to hold the app's"," `activeView`. Each time the `activeView` is set via `showView()`, the"," previous view will be removed from this node, and the new active view's"," `container` node will be appended.",""," The default view container is a `<div>` Node, but you can override this"," in a subclass, or by passing in a custom `viewContainer` config value at"," instantiation time. The `viewContainer` may be provided as a selector"," string, DOM element, or a `Y.Node` instance (having the `viewContainer`"," and the `container` be the same node is also supported).",""," The app's `render()` method will stamp the view container with the CSS"," class `\"yui3-app-views\"` and append it to the app's `container` node if"," it isn't already, and any `activeView` will be appended to this node if"," it isn't already.",""," @attribute viewContainer"," @type HTMLElement|Node|String"," @default Y.Node.create(this.containerTemplate)"," @initOnly"," @since 3.5.0"," **/"," viewContainer: {"," getter : '_getViewContainer',"," setter : Y.one,"," writeOnce: true"," }"," },",""," /**"," Properties that shouldn't be turned into ad-hoc attributes when passed to"," App's constructor.",""," @property _NON_ATTRS_CFG"," @type Array"," @static"," @protected"," @since 3.5.0"," **/"," _NON_ATTRS_CFG: ['views']","});","","// -- Namespace ----------------------------------------------------------------","Y.namespace('App').Base = AppBase;","","/**","Provides a top-level application component which manages navigation and views.","","This gives you a foundation and structure on which to build your application; it","combines robust URL navigation with powerful routing and flexible view","management.","","`Y.App` is both a namespace and constructor function. The `Y.App` class is","special in that any `Y.App` class extensions that are included in the YUI","instance will be **auto-mixed** on to the `Y.App` class. Consider this example:",""," YUI().use('app-base', 'app-transitions', function (Y) {"," // This will create two YUI Apps, `basicApp` will not have transitions,"," // but `fancyApp` will have transitions support included and turn it on."," var basicApp = new Y.App.Base(),"," fancyApp = new Y.App({transitions: true});"," });","","@class App","@param {Object} [config] The following are configuration properties that can be"," specified _in addition_ to default attribute values and the non-attribute"," properties provided by `Y.Base`:"," @param {Object} [config.views] Hash of view-name to metadata used to"," declaratively describe an application's views and their relationship with"," the app and other views. The views specified here will override any defaults"," provided by the `views` object on the `prototype`.","@constructor","@extends App.Base","@uses App.Content","@uses App.Transitions","@uses PjaxContent","@since 3.5.0","**/","Y.App = Y.mix(Y.Base.create('app', AppBase, []), Y.App, true);","","/**","CSS classes used by `Y.App`.","","@property CLASS_NAMES","@type Object","@default {}","@static","@since 3.6.0","**/","Y.App.CLASS_NAMES = {"," app : getClassName('app'),"," views: getClassName('app', 'views')","};","","/**","Default `serverRouting` attribute value for all apps.","","@property serverRouting","@type Boolean","@default undefined","@static","@since 3.6.0","**/","","","}, '@VERSION@', {\"requires\": [\"classnamemanager\", \"pjax-base\", \"router\", \"view\"]});"];
_yuitest_coverage["build/app-base/app-base.js"].lines = {"1":0,"40":0,"75":0,"151":0,"153":0,"156":0,"157":0,"162":0,"166":0,"170":0,"171":0,"174":0,"178":0,"179":0,"202":0,"207":0,"211":0,"212":0,"214":0,"229":0,"230":0,"233":0,"286":0,"293":0,"294":0,"297":0,"298":0,"302":0,"303":0,"306":0,"376":0,"378":0,"381":0,"382":0,"383":0,"384":0,"387":0,"388":0,"394":0,"395":0,"398":0,"406":0,"407":0,"413":0,"414":0,"423":0,"424":0,"425":0,"427":0,"428":0,"431":0,"449":0,"450":0,"453":0,"457":0,"460":0,"461":0,"471":0,"483":0,"489":0,"491":0,"494":0,"496":0,"498":0,"501":0,"504":0,"509":0,"511":0,"512":0,"528":0,"529":0,"532":0,"534":0,"535":0,"540":0,"546":0,"549":0,"550":0,"554":0,"571":0,"575":0,"576":0,"579":0,"600":0,"601":0,"605":0,"624":0,"627":0,"628":0,"631":0,"650":0,"653":0,"654":0,"657":0,"680":0,"684":0,"687":0,"713":0,"717":0,"719":0,"720":0,"721":0,"726":0,"728":0,"730":0,"731":0,"733":0,"737":0,"740":0,"780":0,"782":0,"789":0,"790":0,"793":0,"794":0,"796":0,"797":0,"817":0,"870":0,"985":0,"1036":0,"1071":0,"1082":0};
_yuitest_coverage["build/app-base/app-base.js"].functions = {"mergeViewConfig:156":0,"initializer:150":0,"createView:201":0,"getViewInfo:228":0,"render:285":0,"showView:375":0,"_attachView:448":0,"_destroyContainer:482":0,"_detachView:527":0,"_getViewContainer:566":0,"_initHtml5:597":0,"_isChildView:623":0,"_isParentView:649":0,"_navigate:679":0,"_save:712":0,"_uiSetActiveView:779":0,"_afterActiveViewChange:816":0,"valueFn:869":0,"valueFn:985":0,"(anonymous 1):1":0};
_yuitest_coverage["build/app-base/app-base.js"].coveredLines = 123;
_yuitest_coverage["build/app-base/app-base.js"].coveredFunctions = 20;
_yuitest_coverline("build/app-base/app-base.js", 1);
YUI.add('app-base', function (Y, NAME) {
/**
The App Framework provides simple MVC-like building blocks (models, model lists,
views, and URL-based routing) for writing single-page JavaScript applications.
@main app
@module app
@since 3.4.0
**/
/**
Provides a top-level application component which manages navigation and views.
@module app
@submodule app-base
@since 3.5.0
**/
// TODO: Better handling of lifecycle for registered views:
//
// * [!] Just redo basically everything with view management so there are no
// pre-`activeViewChange` side effects and handle the rest of these things:
//
// * Seems like any view created via `createView` should listen for the view's
// `destroy` event and use that to remove it from the `_viewsInfoMap`. I
// should look at what ModelList does for Models as a reference.
//
// * Should we have a companion `destroyView()` method? Maybe this wouldn't be
// needed if we have a `getView(name, create)` method, and already doing the
// above? We could do `app.getView('foo').destroy()` and it would be removed
// from the `_viewsInfoMap` as well.
//
// * Should we wait to call a view's `render()` method inside of the
// `_attachView()` method?
//
// * Should named views support a collection of instances instead of just one?
//
_yuitest_coverfunc("build/app-base/app-base.js", "(anonymous 1)", 1);
_yuitest_coverline("build/app-base/app-base.js", 40);
var Lang = Y.Lang,
YObject = Y.Object,
PjaxBase = Y.PjaxBase,
Router = Y.Router,
View = Y.View,
getClassName = Y.ClassNameManager.getClassName,
win = Y.config.win,
AppBase;
/**
Provides a top-level application component which manages navigation and views.
This gives you a foundation and structure on which to build your application; it
combines robust URL navigation with powerful routing and flexible view
management.
@class App.Base
@param {Object} [config] The following are configuration properties that can be
specified _in addition_ to default attribute values and the non-attribute
properties provided by `Y.Base`:
@param {Object} [config.views] Hash of view-name to metadata used to
declaratively describe an application's views and their relationship with
the app and other views. The views specified here will override any defaults
provided by the `views` object on the `prototype`.
@constructor
@extends Base
@uses View
@uses Router
@uses PjaxBase
@since 3.5.0
**/
_yuitest_coverline("build/app-base/app-base.js", 75);
AppBase = Y.Base.create('app', Y.Base, [View, Router, PjaxBase], {
// -- Public Properties ----------------------------------------------------
/**
Hash of view-name to metadata used to declaratively describe an
application's views and their relationship with the app and its other views.
The view metadata is composed of Objects keyed to a view-name that can have
any or all of the following properties:
* `type`: Function or a string representing the view constructor to use to
create view instances. If a string is used, the constructor function is
assumed to be on the `Y` object; e.g. `"SomeView"` -> `Y.SomeView`.
* `preserve`: Boolean for whether the view instance should be retained. By
default, the view instance will be destroyed when it is no longer the
`activeView`. If `true` the view instance will simply be `removed()`
from the DOM when it is no longer active. This is useful when the view
is frequently used and may be expensive to re-create.
* `parent`: String to another named view in this hash that represents the
parent view within the application's view hierarchy; e.g. a `"photo"`
view could have `"album"` has its `parent` view. This parent/child
relationship is a useful cue for things like transitions.
* `instance`: Used internally to manage the current instance of this named
view. This can be used if your view instance is created up-front, or if
you would rather manage the View lifecycle, but you probably should just
let this be handled for you.
If `views` are specified at instantiation time, the metadata in the `views`
Object here will be used as defaults when creating the instance's `views`.
Every `Y.App` instance gets its own copy of a `views` object so this Object
on the prototype will not be polluted.
@example
// Imagine that `Y.UsersView` and `Y.UserView` have been defined.
var app = new Y.App({
views: {
users: {
type : Y.UsersView,
preserve: true
},
user: {
type : Y.UserView,
parent: 'users'
}
}
});
@property views
@type Object
@default {}
@since 3.5.0
**/
views: {},
// -- Protected Properties -------------------------------------------------
/**
Map of view instance id (via `Y.stamp()`) to view-info object in `views`.
This mapping is used to tie a specific view instance back to its metadata by
adding a reference to the the related view info on the `views` object.
@property _viewInfoMap
@type Object
@default {}
@protected
@since 3.5.0
**/
// -- Lifecycle Methods ----------------------------------------------------
initializer: function (config) {
_yuitest_coverfunc("build/app-base/app-base.js", "initializer", 150);
_yuitest_coverline("build/app-base/app-base.js", 151);
config || (config = {});
_yuitest_coverline("build/app-base/app-base.js", 153);
var views = {};
// Merges-in specified view metadata into local `views` object.
_yuitest_coverline("build/app-base/app-base.js", 156);
function mergeViewConfig(view, name) {
_yuitest_coverfunc("build/app-base/app-base.js", "mergeViewConfig", 156);
_yuitest_coverline("build/app-base/app-base.js", 157);
views[name] = Y.merge(views[name], view);
}
// First, each view in the `views` prototype object gets its metadata
// merged-in, providing the defaults.
_yuitest_coverline("build/app-base/app-base.js", 162);
YObject.each(this.views, mergeViewConfig);
// Then, each view in the specified `config.views` object gets its
// metadata merged-in.
_yuitest_coverline("build/app-base/app-base.js", 166);
YObject.each(config.views, mergeViewConfig);
// The resulting hodgepodge of metadata is then stored as the instance's
// `views` object, and no one's objects were harmed in the making.
_yuitest_coverline("build/app-base/app-base.js", 170);
this.views = views;
_yuitest_coverline("build/app-base/app-base.js", 171);
this._viewInfoMap = {};
// Using `bind()` to aid extensibility.
_yuitest_coverline("build/app-base/app-base.js", 174);
this.after('activeViewChange', Y.bind('_afterActiveViewChange', this));
// PjaxBase will bind click events when `html5` is `true`, so this just
// forces the binding when `serverRouting` and `html5` are both falsy.
_yuitest_coverline("build/app-base/app-base.js", 178);
if (!this.get('serverRouting')) {
_yuitest_coverline("build/app-base/app-base.js", 179);
this._pjaxBindUI();
}
},
// TODO: `destructor` to destroy the `activeView`?
// -- Public Methods -------------------------------------------------------
/**
Creates and returns a new view instance using the provided `name` to look up
the view info metadata defined in the `views` object. The passed-in `config`
object is passed to the view constructor function.
This function also maps a view instance back to its view info metadata.
@method createView
@param {String} name The name of a view defined on the `views` object.
@param {Object} [config] The configuration object passed to the view
constructor function when creating the new view instance.
@return {View} The new view instance.
@since 3.5.0
**/
createView: function (name, config) {
_yuitest_coverfunc("build/app-base/app-base.js", "createView", 201);
_yuitest_coverline("build/app-base/app-base.js", 202);
var viewInfo = this.getViewInfo(name),
type = (viewInfo && viewInfo.type) || View,
ViewConstructor, view;
// Looks for a namespaced constructor function on `Y`.
_yuitest_coverline("build/app-base/app-base.js", 207);
ViewConstructor = Lang.isString(type) ?
YObject.getValue(Y, type.split('.')) : type;
// Create the view instance and map it with its metadata.
_yuitest_coverline("build/app-base/app-base.js", 211);
view = new ViewConstructor(config);
_yuitest_coverline("build/app-base/app-base.js", 212);
this._viewInfoMap[Y.stamp(view, true)] = viewInfo;
_yuitest_coverline("build/app-base/app-base.js", 214);
return view;
},
/**
Returns the metadata associated with a view instance or view name defined on
the `views` object.
@method getViewInfo
@param {View|String} view View instance, or name of a view defined on the
`views` object.
@return {Object} The metadata for the view, or `undefined` if the view is
not registered.
@since 3.5.0
**/
getViewInfo: function (view) {
_yuitest_coverfunc("build/app-base/app-base.js", "getViewInfo", 228);
_yuitest_coverline("build/app-base/app-base.js", 229);
if (Lang.isString(view)) {
_yuitest_coverline("build/app-base/app-base.js", 230);
return this.views[view];
}
_yuitest_coverline("build/app-base/app-base.js", 233);
return view && this._viewInfoMap[Y.stamp(view, true)];
},
/**
Navigates to the specified URL if there is a route handler that matches. In
browsers capable of using HTML5 history or when `serverRouting` is falsy,
the navigation will be enhanced by firing the `navigate` event and having
the app handle the "request". When `serverRouting` is `true`, non-HTML5
browsers will navigate to the new URL via a full page reload.
When there is a route handler for the specified URL and it is being
navigated to, this method will return `true`, otherwise it will return
`false`.
**Note:** The specified URL _must_ be of the same origin as the current URL,
otherwise an error will be logged and navigation will not occur. This is
intended as both a security constraint and a purposely imposed limitation as
it does not make sense to tell the app to navigate to a URL on a
different scheme, host, or port.
@method navigate
@param {String} url The URL to navigate to. This must be of the same origin
as the current URL.
@param {Object} [options] Additional options to configure the navigation.
These are mixed into the `navigate` event facade.
@param {Boolean} [options.replace] Whether or not the current history
entry will be replaced, or a new entry will be created. Will default
to `true` if the specified `url` is the same as the current URL.
@param {Boolean} [options.force] Whether the enhanced navigation
should occur even in browsers without HTML5 history. Will default to
`true` when `serverRouting` is falsy.
@see PjaxBase.navigate()
**/
// Does not override `navigate()` but does use extra `options`.
/**
Renders this application by appending the `viewContainer` node to the
`container` node if it isn't already a child of the container, and the
`activeView` will be appended the view container, if it isn't already.
You should call this method at least once, usually after the initialization
of your app instance so the proper DOM structure is setup and optionally
append the container to the DOM if it's not there already.
You may override this method to customize the app's rendering, but you
should expect that the `viewContainer`'s contents will be modified by the
app for the purpose of rendering the `activeView` when it changes.
@method render
@chainable
@see View.render()
**/
render: function () {
_yuitest_coverfunc("build/app-base/app-base.js", "render", 285);
_yuitest_coverline("build/app-base/app-base.js", 286);
var CLASS_NAMES = Y.App.CLASS_NAMES,
container = this.get('container'),
viewContainer = this.get('viewContainer'),
activeView = this.get('activeView'),
activeViewContainer = activeView && activeView.get('container'),
areSame = container.compareTo(viewContainer);
_yuitest_coverline("build/app-base/app-base.js", 293);
container.addClass(CLASS_NAMES.app);
_yuitest_coverline("build/app-base/app-base.js", 294);
viewContainer.addClass(CLASS_NAMES.views);
// Prevents needless shuffling around of nodes and maintains DOM order.
_yuitest_coverline("build/app-base/app-base.js", 297);
if (activeView && !viewContainer.contains(activeViewContainer)) {
_yuitest_coverline("build/app-base/app-base.js", 298);
viewContainer.appendChild(activeViewContainer);
}
// Prevents needless shuffling around of nodes and maintains DOM order.
_yuitest_coverline("build/app-base/app-base.js", 302);
if (!container.contains(viewContainer) && !areSame) {
_yuitest_coverline("build/app-base/app-base.js", 303);
container.appendChild(viewContainer);
}
_yuitest_coverline("build/app-base/app-base.js", 306);
return this;
},
/**
Sets which view is active/visible for the application. This will set the
app's `activeView` attribute to the specified `view`.
The `view` will be "attached" to this app, meaning it will be both rendered
into this app's `viewContainer` node and all of its events will bubble to
the app. The previous `activeView` will be "detached" from this app.
When a string-name is provided for a view which has been registered on this
app's `views` object, the referenced metadata will be used and the
`activeView` will be set to either a preserved view instance, or a new
instance of the registered view will be created using the specified `config`
object passed-into this method.
A callback function can be specified as either the third or fourth argument,
and this function will be called after the new `view` becomes the
`activeView`, is rendered to the `viewContainer`, and is ready to use.
@example
var app = new Y.App({
views: {
usersView: {
// Imagine that `Y.UsersView` has been defined.
type: Y.UsersView
}
},
users: new Y.ModelList()
});
app.route('/users/', function () {
this.showView('usersView', {users: this.get('users')});
});
app.render();
app.navigate('/uses/'); // => Creates a new `Y.UsersView` and shows it.
@method showView
@param {String|View} view The name of a view defined in the `views` object,
or a view instance which should become this app's `activeView`.
@param {Object} [config] Optional configuration to use when creating a new
view instance. This config object can also be used to update an existing
or preserved view's attributes when `options.update` is `true`.
@param {Object} [options] Optional object containing any of the following
properties:
@param {Function} [options.callback] Optional callback function to call
after new `activeView` is ready to use, the function will be passed:
@param {View} options.callback.view A reference to the new
`activeView`.
@param {Boolean} [options.prepend=false] Whether the `view` should be
prepended instead of appended to the `viewContainer`.
@param {Boolean} [options.render] Whether the `view` should be rendered.
**Note:** If no value is specified, a view instance will only be
rendered if it's newly created by this method.
@param {Boolean} [options.update=false] Whether an existing view should
have its attributes updated by passing the `config` object to its
`setAttrs()` method. **Note:** This option does not have an effect if
the `view` instance is created as a result of calling this method.
@param {Function} [callback] Optional callback Function to call after the
new `activeView` is ready to use. **Note:** this will override
`options.callback` and it can be specified as either the third or fourth
argument. The function will be passed the following:
@param {View} callback.view A reference to the new `activeView`.
@chainable
@since 3.5.0
**/
showView: function (view, config, options, callback) {
_yuitest_coverfunc("build/app-base/app-base.js", "showView", 375);
_yuitest_coverline("build/app-base/app-base.js", 376);
var viewInfo, created;
_yuitest_coverline("build/app-base/app-base.js", 378);
options || (options = {});
// Support the callback function being either the third or fourth arg.
_yuitest_coverline("build/app-base/app-base.js", 381);
if (callback) {
_yuitest_coverline("build/app-base/app-base.js", 382);
options = Y.merge(options, {callback: callback});
} else {_yuitest_coverline("build/app-base/app-base.js", 383);
if (Lang.isFunction(options)) {
_yuitest_coverline("build/app-base/app-base.js", 384);
options = {callback: options};
}}
_yuitest_coverline("build/app-base/app-base.js", 387);
if (Lang.isString(view)) {
_yuitest_coverline("build/app-base/app-base.js", 388);
viewInfo = this.getViewInfo(view);
// Use the preserved view instance, or create a new view.
// TODO: Maybe we can remove the strict check for `preserve` and
// assume we'll use a View instance if it is there, and just check
// `preserve` when detaching?
_yuitest_coverline("build/app-base/app-base.js", 394);
if (viewInfo && viewInfo.preserve && viewInfo.instance) {
_yuitest_coverline("build/app-base/app-base.js", 395);
view = viewInfo.instance;
// Make sure there's a mapping back to the view metadata.
_yuitest_coverline("build/app-base/app-base.js", 398);
this._viewInfoMap[Y.stamp(view, true)] = viewInfo;
} else {
// TODO: Add the app as a bubble target during construction, but
// make sure to check that it isn't already in `bubbleTargets`!
// This will allow the app to be notified for about _all_ of the
// view's events. **Note:** This should _only_ happen if the
// view is created _after_ `activeViewChange`.
_yuitest_coverline("build/app-base/app-base.js", 406);
view = this.createView(view, config);
_yuitest_coverline("build/app-base/app-base.js", 407);
created = true;
}
}
// Update the specified or preserved `view` when signaled to do so.
// There's no need to updated a view if it was _just_ created.
_yuitest_coverline("build/app-base/app-base.js", 413);
if (options.update && !created) {
_yuitest_coverline("build/app-base/app-base.js", 414);
view.setAttrs(config);
}
// TODO: Hold off on rendering the view until after it has been
// "attached", and move the call to render into `_attachView()`.
// When a value is specified for `options.render`, prefer it because it
// represents the developer's intent. When no value is specified, the
// `view` will only be rendered if it was just created.
_yuitest_coverline("build/app-base/app-base.js", 423);
if ('render' in options) {
_yuitest_coverline("build/app-base/app-base.js", 424);
if (options.render) {
_yuitest_coverline("build/app-base/app-base.js", 425);
view.render();
}
} else {_yuitest_coverline("build/app-base/app-base.js", 427);
if (created) {
_yuitest_coverline("build/app-base/app-base.js", 428);
view.render();
}}
_yuitest_coverline("build/app-base/app-base.js", 431);
return this._set('activeView', view, {options: options});
},
// -- Protected Methods ----------------------------------------------------
/**
Helper method to attach the view instance to the application by making the
app a bubble target of the view, append the view to the `viewContainer`, and
assign it to the `instance` property of the associated view info metadata.
@method _attachView
@param {View} view View to attach.
@param {Boolean} prepend=false Whether the view should be prepended instead
of appended to the `viewContainer`.
@protected
@since 3.5.0
**/
_attachView: function (view, prepend) {
_yuitest_coverfunc("build/app-base/app-base.js", "_attachView", 448);
_yuitest_coverline("build/app-base/app-base.js", 449);
if (!view) {
_yuitest_coverline("build/app-base/app-base.js", 450);
return;
}
_yuitest_coverline("build/app-base/app-base.js", 453);
var viewInfo = this.getViewInfo(view),
viewContainer = this.get('viewContainer');
// Bubble the view's events to this app.
_yuitest_coverline("build/app-base/app-base.js", 457);
view.addTarget(this);
// Save the view instance in the `views` registry.
_yuitest_coverline("build/app-base/app-base.js", 460);
if (viewInfo) {
_yuitest_coverline("build/app-base/app-base.js", 461);
viewInfo.instance = view;
}
// TODO: Attach events here for persevered Views?
// See related TODO in `_detachView`.
// TODO: Actually render the view here so that it gets "attached" before
// it gets rendered?
// Insert view into the DOM.
_yuitest_coverline("build/app-base/app-base.js", 471);
viewContainer[prepend ? 'prepend' : 'append'](view.get('container'));
},
/**
Overrides View's container destruction to deal with the `viewContainer` and
checks to make sure not to remove and purge the `<body>`.
@method _destroyContainer
@protected
@see View._destroyContainer()
**/
_destroyContainer: function () {
_yuitest_coverfunc("build/app-base/app-base.js", "_destroyContainer", 482);
_yuitest_coverline("build/app-base/app-base.js", 483);
var CLASS_NAMES = Y.App.CLASS_NAMES,
container = this.get('container'),
viewContainer = this.get('viewContainer'),
areSame = container.compareTo(viewContainer);
// We do not want to remove or destroy the `<body>`.
_yuitest_coverline("build/app-base/app-base.js", 489);
if (Y.one('body').compareTo(container)) {
// Just clean-up our events listeners.
_yuitest_coverline("build/app-base/app-base.js", 491);
this.detachEvents();
// Clean-up `yui3-app` CSS class on the `container`.
_yuitest_coverline("build/app-base/app-base.js", 494);
container.removeClass(CLASS_NAMES.app);
_yuitest_coverline("build/app-base/app-base.js", 496);
if (areSame) {
// Clean-up `yui3-app-views` CSS class on the `container`.
_yuitest_coverline("build/app-base/app-base.js", 498);
container.removeClass(CLASS_NAMES.views);
} else {
// Destroy and purge the `viewContainer`.
_yuitest_coverline("build/app-base/app-base.js", 501);
viewContainer.remove(true);
}
_yuitest_coverline("build/app-base/app-base.js", 504);
return;
}
// Remove and purge events from both containers.
_yuitest_coverline("build/app-base/app-base.js", 509);
viewContainer.remove(true);
_yuitest_coverline("build/app-base/app-base.js", 511);
if (!areSame) {
_yuitest_coverline("build/app-base/app-base.js", 512);
container.remove(true);
}
},
/**
Helper method to detach the view instance from the application by removing
the application as a bubble target of the view, and either just removing the
view if it is intended to be preserved, or destroying the instance
completely.
@method _detachView
@param {View} view View to detach.
@protected
@since 3.5.0
**/
_detachView: function (view) {
_yuitest_coverfunc("build/app-base/app-base.js", "_detachView", 527);
_yuitest_coverline("build/app-base/app-base.js", 528);
if (!view) {
_yuitest_coverline("build/app-base/app-base.js", 529);
return;
}
_yuitest_coverline("build/app-base/app-base.js", 532);
var viewInfo = this.getViewInfo(view) || {};
_yuitest_coverline("build/app-base/app-base.js", 534);
if (viewInfo.preserve) {
_yuitest_coverline("build/app-base/app-base.js", 535);
view.remove();
// TODO: Detach events here for preserved Views? It is possible that
// some event subscriptions are made on elements other than the
// View's `container`.
} else {
_yuitest_coverline("build/app-base/app-base.js", 540);
view.destroy({remove: true});
// TODO: The following should probably happen automagically from
// `destroy()` being called! Possibly `removeTarget()` as well.
// Remove from view to view-info map.
_yuitest_coverline("build/app-base/app-base.js", 546);
delete this._viewInfoMap[Y.stamp(view, true)];
// Remove from view-info instance property.
_yuitest_coverline("build/app-base/app-base.js", 549);
if (view === viewInfo.instance) {
_yuitest_coverline("build/app-base/app-base.js", 550);
delete viewInfo.instance;
}
}
_yuitest_coverline("build/app-base/app-base.js", 554);
view.removeTarget(this);
},
/**
Getter for the `viewContainer` attribute.
@method _getViewContainer
@param {Node|null} value Current attribute value.
@return {Node} View container node.
@protected
@since 3.5.0
**/
_getViewContainer: function (value) {
// This wackiness is necessary to enable fully lazy creation of the
// container node both when no container is specified and when one is
// specified via a valueFn.
_yuitest_coverfunc("build/app-base/app-base.js", "_getViewContainer", 566);
_yuitest_coverline("build/app-base/app-base.js", 571);
if (!value && !this._viewContainer) {
// Create a default container and set that as the new attribute
// value. The `this._viewContainer` property prevents infinite
// recursion.
_yuitest_coverline("build/app-base/app-base.js", 575);
value = this._viewContainer = this.create();
_yuitest_coverline("build/app-base/app-base.js", 576);
this._set('viewContainer', value);
}
_yuitest_coverline("build/app-base/app-base.js", 579);
return value;
},
/**
Provides the default value for the `html5` attribute.
The value returned is dependent on the value of the `serverRouting`
attribute. When `serverRouting` is explicit set to `false` (not just falsy),
the default value for `html5` will be set to `false` for *all* browsers.
When `serverRouting` is `true` or `undefined` the returned value will be
dependent on the browser's capability of using HTML5 history.
@method _initHtml5
@return {Boolean} Whether or not HTML5 history should be used.
@protected
@since 3.5.0
**/
_initHtml5: function () {
// When `serverRouting` is explicitly set to `false` (not just falsy),
// forcing hash-based URLs in all browsers.
_yuitest_coverfunc("build/app-base/app-base.js", "_initHtml5", 597);
_yuitest_coverline("build/app-base/app-base.js", 600);
if (this.get('serverRouting') === false) {
_yuitest_coverline("build/app-base/app-base.js", 601);
return false;
}
// Defaults to whether or not the browser supports HTML5 history.
_yuitest_coverline("build/app-base/app-base.js", 605);
return Router.html5;
},
/**
Determines if the specified `view` is configured as a child of the specified
`parent` view. This requires both views to be either named-views, or view
instances created using configuration data that exists in the `views`
object, e.g. created by the `createView()` or `showView()` method.
@method _isChildView
@param {View|String} view The name of a view defined in the `views` object,
or a view instance.
@param {View|String} parent The name of a view defined in the `views`
object, or a view instance.
@return {Boolean} Whether the view is configured as a child of the parent.
@protected
@since 3.5.0
**/
_isChildView: function (view, parent) {
_yuitest_coverfunc("build/app-base/app-base.js", "_isChildView", 623);
_yuitest_coverline("build/app-base/app-base.js", 624);
var viewInfo = this.getViewInfo(view),
parentInfo = this.getViewInfo(parent);
_yuitest_coverline("build/app-base/app-base.js", 627);
if (viewInfo && parentInfo) {
_yuitest_coverline("build/app-base/app-base.js", 628);
return this.getViewInfo(viewInfo.parent) === parentInfo;
}
_yuitest_coverline("build/app-base/app-base.js", 631);
return false;
},
/**
Determines if the specified `view` is configured as the parent of the
specified `child` view. This requires both views to be either named-views,
or view instances created using configuration data that exists in the
`views` object, e.g. created by the `createView()` or `showView()` method.
@method _isParentView
@param {View|String} view The name of a view defined in the `views` object,
or a view instance.
@param {View|String} parent The name of a view defined in the `views`
object, or a view instance.
@return {Boolean} Whether the view is configured as the parent of the child.
@protected
@since 3.5.0
**/
_isParentView: function (view, child) {
_yuitest_coverfunc("build/app-base/app-base.js", "_isParentView", 649);
_yuitest_coverline("build/app-base/app-base.js", 650);
var viewInfo = this.getViewInfo(view),
childInfo = this.getViewInfo(child);
_yuitest_coverline("build/app-base/app-base.js", 653);
if (viewInfo && childInfo) {
_yuitest_coverline("build/app-base/app-base.js", 654);
return this.getViewInfo(childInfo.parent) === viewInfo;
}
_yuitest_coverline("build/app-base/app-base.js", 657);
return false;
},
/**
Underlying implementation for `navigate()`.
@method _navigate
@param {String} url The fully-resolved URL that the app should dispatch to
its route handlers to fulfill the enhanced navigation "request", or use to
update `window.location` in non-HTML5 history capable browsers when
`serverRouting` is `true`.
@param {Object} [options] Additional options to configure the navigation.
These are mixed into the `navigate` event facade.
@param {Boolean} [options.replace] Whether or not the current history
entry will be replaced, or a new entry will be created. Will default
to `true` if the specified `url` is the same as the current URL.
@param {Boolean} [options.force] Whether the enhanced navigation
should occur even in browsers without HTML5 history. Will default to
`true` when `serverRouting` is falsy.
@protected
@see PjaxBase._navigate()
**/
_navigate: function (url, options) {
_yuitest_coverfunc("build/app-base/app-base.js", "_navigate", 679);
_yuitest_coverline("build/app-base/app-base.js", 680);
if (!this.get('serverRouting')) {
// Force navigation to be enhanced and handled by the app when
// `serverRouting` is falsy because the server might not be able to
// properly handle the request.
_yuitest_coverline("build/app-base/app-base.js", 684);
options = Y.merge({force: true}, options);
}
_yuitest_coverline("build/app-base/app-base.js", 687);
return PjaxBase.prototype._navigate.call(this, url, options);
},
/**
Will either save a history entry using `pushState()` or the location hash,
or gracefully-degrade to sending a request to the server causing a full-page
reload.
Overrides Router's `_save()` method to preform graceful-degradation when the
app's `serverRouting` is `true` and `html5` is `false` by updating the full
URL via standard assignment to `window.location` or by calling
`window.location.replace()`; both of which will cause a request to the
server resulting in a full-page reload.
Otherwise this will just delegate off to Router's `_save()` method allowing
the client-side enhanced routing to occur.
@method _save
@param {String} [url] URL for the history entry.
@param {Boolean} [replace=false] If `true`, the current history entry will
be replaced instead of a new one being added.
@chainable
@protected
@see Router._save()
**/
_save: function (url, replace) {
_yuitest_coverfunc("build/app-base/app-base.js", "_save", 712);
_yuitest_coverline("build/app-base/app-base.js", 713);
var path;
// Forces full-path URLs to always be used by modifying
// `window.location` in non-HTML5 history capable browsers.
_yuitest_coverline("build/app-base/app-base.js", 717);
if (this.get('serverRouting') && !this.get('html5')) {
// Perform same-origin check on the specified URL.
_yuitest_coverline("build/app-base/app-base.js", 719);
if (!this._hasSameOrigin(url)) {
_yuitest_coverline("build/app-base/app-base.js", 720);
Y.error('Security error: The new URL must be of the same origin as the current URL.');
_yuitest_coverline("build/app-base/app-base.js", 721);
return this;
}
// Either replace the current history entry or create a new one
// while navigating to the `url`.
_yuitest_coverline("build/app-base/app-base.js", 726);
if (win) {
// Results in the URL's full path starting with '/'.
_yuitest_coverline("build/app-base/app-base.js", 728);
path = this._joinURL(url || '');
_yuitest_coverline("build/app-base/app-base.js", 730);
if (replace) {
_yuitest_coverline("build/app-base/app-base.js", 731);
win.location.replace(path);
} else {
_yuitest_coverline("build/app-base/app-base.js", 733);
win.location = path;
}
}
_yuitest_coverline("build/app-base/app-base.js", 737);
return this;
}
_yuitest_coverline("build/app-base/app-base.js", 740);
return Router.prototype._save.apply(this, arguments);
},
/**
Performs the actual change of this app's `activeView` by attaching the
`newView` to this app, and detaching the `oldView` from this app using any
specified `options`.
The `newView` is attached to the app by rendering it to the `viewContainer`,
and making this app a bubble target of its events.
The `oldView` is detached from the app by removing it from the
`viewContainer`, and removing this app as a bubble target for its events.
The `oldView` will either be preserved or properly destroyed.
**Note:** The `activeView` attribute is read-only and can be changed by
calling the `showView()` method.
@method _uiSetActiveView
@param {View} newView The View which is now this app's `activeView`.
@param {View} [oldView] The View which was this app's `activeView`.
@param {Object} [options] Optional object containing any of the following
properties:
@param {Function} [options.callback] Optional callback function to call
after new `activeView` is ready to use, the function will be passed:
@param {View} options.callback.view A reference to the new
`activeView`.
@param {Boolean} [options.prepend=false] Whether the `view` should be
prepended instead of appended to the `viewContainer`.
@param {Boolean} [options.render] Whether the `view` should be rendered.
**Note:** If no value is specified, a view instance will only be
rendered if it's newly created by this method.
@param {Boolean} [options.update=false] Whether an existing view should
have its attributes updated by passing the `config` object to its
`setAttrs()` method. **Note:** This option does not have an effect if
the `view` instance is created as a result of calling this method.
@protected
@since 3.5.0
**/
_uiSetActiveView: function (newView, oldView, options) {
_yuitest_coverfunc("build/app-base/app-base.js", "_uiSetActiveView", 779);
_yuitest_coverline("build/app-base/app-base.js", 780);
options || (options = {});
_yuitest_coverline("build/app-base/app-base.js", 782);
var callback = options.callback,
isChild = this._isChildView(newView, oldView),
isParent = !isChild && this._isParentView(newView, oldView),
prepend = !!options.prepend || isParent;
// Prevent detaching (thus removing) the view we want to show. Also hard
// to animate out and in, the same view.
_yuitest_coverline("build/app-base/app-base.js", 789);
if (newView === oldView) {
_yuitest_coverline("build/app-base/app-base.js", 790);
return callback && callback.call(this, newView);
}
_yuitest_coverline("build/app-base/app-base.js", 793);
this._attachView(newView, prepend);
_yuitest_coverline("build/app-base/app-base.js", 794);
this._detachView(oldView);
_yuitest_coverline("build/app-base/app-base.js", 796);
if (callback) {
_yuitest_coverline("build/app-base/app-base.js", 797);
callback.call(this, newView);
}
},
// -- Protected Event Handlers ---------------------------------------------
/**
Handles the application's `activeViewChange` event (which is fired when the
`activeView` attribute changes) by detaching the old view, attaching the new
view.
The `activeView` attribute is read-only, so the public API to change its
value is through the `showView()` method.
@method _afterActiveViewChange
@param {EventFacade} e
@protected
@since 3.5.0
**/
_afterActiveViewChange: function (e) {
_yuitest_coverfunc("build/app-base/app-base.js", "_afterActiveViewChange", 816);
_yuitest_coverline("build/app-base/app-base.js", 817);
this._uiSetActiveView(e.newVal, e.prevVal, e.options);
}
}, {
ATTRS: {
/**
The application's active/visible view.
This attribute is read-only, to set the `activeView` use the
`showView()` method.
@attribute activeView
@type View
@default null
@readOnly
@see App.Base.showView()
@since 3.5.0
**/
activeView: {
value : null,
readOnly: true
},
/**
Container node which represents the application's bounding-box, into
which this app's content will be rendered.
The container node serves as the host for all DOM events attached by the
app. Delegation is used to handle events on children of the container,
allowing the container's contents to be re-rendered at any time without
losing event subscriptions.
The default container is the `<body>` Node, but you can override this in
a subclass, or by passing in a custom `container` config value at
instantiation time.
When `container` is overridden by a subclass or passed as a config
option at instantiation time, it may be provided as a selector string, a
DOM element, or a `Y.Node` instance. During initialization, this app's
`create()` method will be called to convert the container into a
`Y.Node` instance if it isn't one already and stamp it with the CSS
class: `"yui3-app"`.
The container is not added to the page automatically. This allows you to
have full control over how and when your app is actually rendered to
the page.
@attribute container
@type HTMLElement|Node|String
@default Y.one('body')
@initOnly
**/
container: {
valueFn: function () {
_yuitest_coverfunc("build/app-base/app-base.js", "valueFn", 869);
_yuitest_coverline("build/app-base/app-base.js", 870);
return Y.one('body');
}
},
/**
Whether or not this browser is capable of using HTML5 history.
This value is dependent on the value of `serverRouting` and will default
accordingly.
Setting this to `false` will force the use of hash-based history even on
HTML5 browsers, but please don't do this unless you understand the
consequences.
@attribute html5
@type Boolean
@initOnly
@see serverRouting
**/
html5: {
valueFn: '_initHtml5'
},
/**
CSS selector string used to filter link click events so that only the
links which match it will have the enhanced-navigation behavior of pjax
applied.
When a link is clicked and that link matches this selector, navigating
to the link's `href` URL using the enhanced, pjax, behavior will be
attempted; and the browser's default way to navigate to new pages will
be the fallback.
By default this selector will match _all_ links on the page.
@attribute linkSelector
@type String|Function
@default "a"
**/
linkSelector: {
value: 'a'
},
/**
Whether or not this application's server is capable of properly routing
all requests and rendering the initial state in the HTML responses.
This can have three different values, each having particular
implications on how the app will handle routing and navigation:
* `undefined`: The best form of URLs will be chosen based on the
capabilities of the browser. Given no information about the server
environmentm a balanced approach to routing and navigation is
chosen.
The server should be capable of handling full-path requests, since
full-URLs will be generated by browsers using HTML5 history. If this
is a client-side-only app the server could handle full-URL requests
by sending a redirect back to the root with a hash-based URL, e.g:
Request: http://example.com/users/1
Redirect to: http://example.com/#/users/1
* `true`: The server is *fully* capable of properly handling requests
to all full-path URLs the app can produce.
This is the best option for progressive-enhancement because it will
cause **all URLs to always have full-paths**, which means the server
will be able to accurately handle all URLs this app produces. e.g.
http://example.com/users/1
To meet this strict full-URL requirement, browsers which are not
capable of using HTML5 history will make requests to the server
resulting in full-page reloads.
* `false`: The server is *not* capable of properly handling requests
to all full-path URLs the app can produce, therefore all routing
will be handled by this App instance.
Be aware that this will cause **all URLs to always be hash-based**,
even in browsers that are capable of using HTML5 history. e.g.
http://example.com/#/users/1
A single-page or client-side-only app where the server sends a
"shell" page with JavaScript to the client might have this
restriction. If you're setting this to `false`, read the following:
**Note:** When this is set to `false`, the server will *never* receive
the full URL because browsers do not send the fragment-part to the
server, that is everything after and including the "#".
Consider the following example:
URL shown in browser: http://example.com/#/users/1
URL sent to server: http://example.com/
You should feel bad about hurting our precious web if you forcefully set
either `serverRouting` or `html5` to `false`, because you're basically
punching the web in the face here with your lossy URLs! Please make sure
you know what you're doing and that you understand the implications.
Ideally you should always prefer full-path URLs (not /#/foo/), and want
full-page reloads when the client's browser is not capable of enhancing
the experience using the HTML5 history APIs. Setting this to `true` is
the best option for progressive-enhancement (and graceful-degradation).
@attribute serverRouting
@type Boolean
@default undefined
@initOnly
@since 3.5.0
**/
serverRouting: {
valueFn : function () { _yuitest_coverfunc("build/app-base/app-base.js", "valueFn", 985);
_yuitest_coverline("build/app-base/app-base.js", 985);
return Y.App.serverRouting; },
writeOnce: 'initOnly'
},
/**
The node into which this app's `views` will be rendered when they become
the `activeView`.
The view container node serves as the container to hold the app's
`activeView`. Each time the `activeView` is set via `showView()`, the
previous view will be removed from this node, and the new active view's
`container` node will be appended.
The default view container is a `<div>` Node, but you can override this
in a subclass, or by passing in a custom `viewContainer` config value at
instantiation time. The `viewContainer` may be provided as a selector
string, DOM element, or a `Y.Node` instance (having the `viewContainer`
and the `container` be the same node is also supported).
The app's `render()` method will stamp the view container with the CSS
class `"yui3-app-views"` and append it to the app's `container` node if
it isn't already, and any `activeView` will be appended to this node if
it isn't already.
@attribute viewContainer
@type HTMLElement|Node|String
@default Y.Node.create(this.containerTemplate)
@initOnly
@since 3.5.0
**/
viewContainer: {
getter : '_getViewContainer',
setter : Y.one,
writeOnce: true
}
},
/**
Properties that shouldn't be turned into ad-hoc attributes when passed to
App's constructor.
@property _NON_ATTRS_CFG
@type Array
@static
@protected
@since 3.5.0
**/
_NON_ATTRS_CFG: ['views']
});
// -- Namespace ----------------------------------------------------------------
_yuitest_coverline("build/app-base/app-base.js", 1036);
Y.namespace('App').Base = AppBase;
/**
Provides a top-level application component which manages navigation and views.
This gives you a foundation and structure on which to build your application; it
combines robust URL navigation with powerful routing and flexible view
management.
`Y.App` is both a namespace and constructor function. The `Y.App` class is
special in that any `Y.App` class extensions that are included in the YUI
instance will be **auto-mixed** on to the `Y.App` class. Consider this example:
YUI().use('app-base', 'app-transitions', function (Y) {
// This will create two YUI Apps, `basicApp` will not have transitions,
// but `fancyApp` will have transitions support included and turn it on.
var basicApp = new Y.App.Base(),
fancyApp = new Y.App({transitions: true});
});
@class App
@param {Object} [config] The following are configuration properties that can be
specified _in addition_ to default attribute values and the non-attribute
properties provided by `Y.Base`:
@param {Object} [config.views] Hash of view-name to metadata used to
declaratively describe an application's views and their relationship with
the app and other views. The views specified here will override any defaults
provided by the `views` object on the `prototype`.
@constructor
@extends App.Base
@uses App.Content
@uses App.Transitions
@uses PjaxContent
@since 3.5.0
**/
_yuitest_coverline("build/app-base/app-base.js", 1071);
Y.App = Y.mix(Y.Base.create('app', AppBase, []), Y.App, true);
/**
CSS classes used by `Y.App`.
@property CLASS_NAMES
@type Object
@default {}
@static
@since 3.6.0
**/
_yuitest_coverline("build/app-base/app-base.js", 1082);
Y.App.CLASS_NAMES = {
app : getClassName('app'),
views: getClassName('app', 'views')
};
/**
Default `serverRouting` attribute value for all apps.
@property serverRouting
@type Boolean
@default undefined
@static
@since 3.6.0
**/
}, '@VERSION@', {"requires": ["classnamemanager", "pjax-base", "router", "view"]});
| luanlmd/cdnjs | ajax/libs/yui/3.9.1/app-base/app-base-coverage.js | JavaScript | mit | 96,420 |
/*!
* jQuery JavaScript Library v2.1.1
* http://jquery.com/
*
* Includes Sizzle.js
* http://sizzlejs.com/
*
* Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-05-01T17:11Z
*/
(function( global, factory ) {
if ( typeof module === "object" && typeof module.exports === "object" ) {
// For CommonJS and CommonJS-like environments where a proper window is present,
// execute the factory and get jQuery
// For environments that do not inherently posses a window with a document
// (such as Node.js), expose a jQuery-making factory as module.exports
// This accentuates the need for the creation of a real window
// e.g. var jQuery = require("jquery")(window);
// See ticket #14549 for more info
module.exports = global.document ?
factory( global, true ) :
function( w ) {
if ( !w.document ) {
throw new Error( "jQuery requires a window with a document" );
}
return factory( w );
};
} else {
factory( global );
}
// Pass this if window is not defined yet
}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
// Can't do this because several apps including ASP.NET trace
// the stack via arguments.caller.callee and Firefox dies if
// you try to trace through "use strict" call chains. (#13335)
// Support: Firefox 18+
//
var arr = [];
var slice = arr.slice;
var concat = arr.concat;
var push = arr.push;
var indexOf = arr.indexOf;
var class2type = {};
var toString = class2type.toString;
var hasOwn = class2type.hasOwnProperty;
var support = {};
var
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
version = "2.1.1",
// Define a local copy of jQuery
jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
// Need init if jQuery is called (just allow error to be thrown if not included)
return new jQuery.fn.init( selector, context );
},
// Support: Android<4.1
// Make sure we trim BOM and NBSP
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
// Matches dashed string for camelizing
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn = jQuery.prototype = {
// The current version of jQuery being used
jquery: version,
constructor: jQuery,
// Start with an empty selector
selector: "",
// The default length of a jQuery object is 0
length: 0,
toArray: function() {
return slice.call( this );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num != null ?
// Return just the one element from the set
( num < 0 ? this[ num + this.length ] : this[ num ] ) :
// Return all the elements in a clean array
slice.call( this );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems ) {
// Build a new jQuery matched element set
var ret = jQuery.merge( this.constructor(), elems );
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ) );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
eq: function( i ) {
var len = this.length,
j = +i + ( i < 0 ? len : 0 );
return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: arr.sort,
splice: arr.splice
};
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
// skip the boolean and the target
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
// Unique for each copy of jQuery on the page
expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
// Assume jQuery is ready without the ready module
isReady: true,
error: function( msg ) {
throw new Error( msg );
},
noop: function() {},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray,
isWindow: function( obj ) {
return obj != null && obj === obj.window;
},
isNumeric: function( obj ) {
// parseFloat NaNs numeric-cast false positives (null|true|false|"")
// ...but misinterprets leading-number strings, particularly hex literals ("0x...")
// subtraction forces infinities to NaN
return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0;
},
isPlainObject: function( obj ) {
// Not plain objects:
// - Any object or value whose internal [[Class]] property is not "[object Object]"
// - DOM nodes
// - window
if ( jQuery.type( obj ) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.constructor &&
!hasOwn.call( obj.constructor.prototype, "isPrototypeOf" ) ) {
return false;
}
// If the function hasn't returned already, we're confident that
// |obj| is a plain object, created by {} or constructed with new Object
return true;
},
isEmptyObject: function( obj ) {
var name;
for ( name in obj ) {
return false;
}
return true;
},
type: function( obj ) {
if ( obj == null ) {
return obj + "";
}
// Support: Android < 4.0, iOS < 6 (functionish RegExp)
return typeof obj === "object" || typeof obj === "function" ?
class2type[ toString.call(obj) ] || "object" :
typeof obj;
},
// Evaluates a script in a global context
globalEval: function( code ) {
var script,
indirect = eval;
code = jQuery.trim( code );
if ( code ) {
// If the code includes a valid, prologue position
// strict mode pragma, execute code by injecting a
// script tag into the document.
if ( code.indexOf("use strict") === 1 ) {
script = document.createElement("script");
script.text = code;
document.head.appendChild( script ).parentNode.removeChild( script );
} else {
// Otherwise, avoid the DOM node creation, insertion
// and removal by using an indirect global eval
indirect( code );
}
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
// args is for internal usage only
each: function( obj, callback, args ) {
var value,
i = 0,
length = obj.length,
isArray = isArraylike( obj );
if ( args ) {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.apply( obj[ i ], args );
if ( value === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
} else {
for ( i in obj ) {
value = callback.call( obj[ i ], i, obj[ i ] );
if ( value === false ) {
break;
}
}
}
}
return obj;
},
// Support: Android<4.1
trim: function( text ) {
return text == null ?
"" :
( text + "" ).replace( rtrim, "" );
},
// results is for internal usage only
makeArray: function( arr, results ) {
var ret = results || [];
if ( arr != null ) {
if ( isArraylike( Object(arr) ) ) {
jQuery.merge( ret,
typeof arr === "string" ?
[ arr ] : arr
);
} else {
push.call( ret, arr );
}
}
return ret;
},
inArray: function( elem, arr, i ) {
return arr == null ? -1 : indexOf.call( arr, elem, i );
},
merge: function( first, second ) {
var len = +second.length,
j = 0,
i = first.length;
for ( ; j < len; j++ ) {
first[ i++ ] = second[ j ];
}
first.length = i;
return first;
},
grep: function( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value,
i = 0,
length = elems.length,
isArray = isArraylike( elems ),
ret = [];
// Go through the array, translating each of the items to their new values
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
// Go through every key on the object,
} else {
for ( i in elems ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret.push( value );
}
}
}
// Flatten any nested arrays
return concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
var tmp, args, proxy;
if ( typeof context === "string" ) {
tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
args = slice.call( arguments, 2 );
proxy = function() {
return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
now: Date.now,
// jQuery.support is not used in Core but other projects attach their
// properties to it so it needs to exist.
support: support
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
function isArraylike( obj ) {
var length = obj.length,
type = jQuery.type( obj );
if ( type === "function" || jQuery.isWindow( obj ) ) {
return false;
}
if ( obj.nodeType === 1 && length ) {
return true;
}
return type === "array" || length === 0 ||
typeof length === "number" && length > 0 && ( length - 1 ) in obj;
}
var Sizzle =
/*!
* Sizzle CSS Selector Engine v1.10.19
* http://sizzlejs.com/
*
* Copyright 2013 jQuery Foundation, Inc. and other contributors
* Released under the MIT license
* http://jquery.org/license
*
* Date: 2014-04-18
*/
(function( window ) {
var i,
support,
Expr,
getText,
isXML,
tokenize,
compile,
select,
outermostContext,
sortInput,
hasDuplicate,
// Local document vars
setDocument,
document,
docElem,
documentIsHTML,
rbuggyQSA,
rbuggyMatches,
matches,
contains,
// Instance-specific data
expando = "sizzle" + -(new Date()),
preferredDoc = window.document,
dirruns = 0,
done = 0,
classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
}
return 0;
},
// General-purpose constants
strundefined = typeof undefined,
MAX_NEGATIVE = 1 << 31,
// Instance methods
hasOwn = ({}).hasOwnProperty,
arr = [],
pop = arr.pop,
push_native = arr.push,
push = arr.push,
slice = arr.slice,
// Use a stripped-down indexOf if we can't use a native one
indexOf = arr.indexOf || function( elem ) {
var i = 0,
len = this.length;
for ( ; i < len; i++ ) {
if ( this[i] === elem ) {
return i;
}
}
return -1;
},
booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
// Regular expressions
// Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
whitespace = "[\\x20\\t\\r\\n\\f]",
// http://www.w3.org/TR/css3-syntax/#characters
characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
// Loosely modeled on CSS identifier characters
// An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
// Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
identifier = characterEncoding.replace( "w", "w#" ),
// Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
// Operator (capture 2)
"*([*^$|!~]?=)" + whitespace +
// "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
"*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((" +
// To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
// 1. quoted (capture 3; capture 4 or capture 5)
"('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
// 2. simple (capture 6)
"((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
// 3. anything else (capture 2)
".*" +
")\\)|)",
// Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
rpseudo = new RegExp( pseudos ),
ridentifier = new RegExp( "^" + identifier + "$" ),
matchExpr = {
"ID": new RegExp( "^#(" + characterEncoding + ")" ),
"CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
"TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
"ATTR": new RegExp( "^" + attributes ),
"PSEUDO": new RegExp( "^" + pseudos ),
"CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
"*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
"*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
"bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
// For use in libraries implementing .is()
// We use this for POS matching in `select`
"needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
},
rinputs = /^(?:input|select|textarea|button)$/i,
rheader = /^h\d$/i,
rnative = /^[^{]+\{\s*\[native \w/,
// Easily-parseable/retrievable ID or TAG or CLASS selectors
rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
rsibling = /[+~]/,
rescape = /'|\\/g,
// CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
funescape = function( _, escaped, escapedWhitespace ) {
var high = "0x" + escaped - 0x10000;
// NaN means non-codepoint
// Support: Firefox<24
// Workaround erroneous numeric interpretation of +"0x"
return high !== high || escapedWhitespace ?
escaped :
high < 0 ?
// BMP codepoint
String.fromCharCode( high + 0x10000 ) :
// Supplemental Plane codepoint (surrogate pair)
String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
};
// Optimize for push.apply( _, NodeList )
try {
push.apply(
(arr = slice.call( preferredDoc.childNodes )),
preferredDoc.childNodes
);
// Support: Android<4.0
// Detect silently failing push.apply
arr[ preferredDoc.childNodes.length ].nodeType;
} catch ( e ) {
push = { apply: arr.length ?
// Leverage slice if possible
function( target, els ) {
push_native.apply( target, slice.call(els) );
} :
// Support: IE<9
// Otherwise append directly
function( target, els ) {
var j = target.length,
i = 0;
// Can't trust NodeList.length
while ( (target[j++] = els[i++]) ) {}
target.length = j - 1;
}
};
}
function Sizzle( selector, context, results, seed ) {
var match, elem, m, nodeType,
// QSA vars
i, groups, old, nid, newContext, newSelector;
if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
setDocument( context );
}
context = context || document;
results = results || [];
if ( !selector || typeof selector !== "string" ) {
return results;
}
if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
return [];
}
if ( documentIsHTML && !seed ) {
// Shortcuts
if ( (match = rquickExpr.exec( selector )) ) {
// Speed-up: Sizzle("#ID")
if ( (m = match[1]) ) {
if ( nodeType === 9 ) {
elem = context.getElementById( m );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document (jQuery #6963)
if ( elem && elem.parentNode ) {
// Handle the case where IE, Opera, and Webkit return items
// by name instead of ID
if ( elem.id === m ) {
results.push( elem );
return results;
}
} else {
return results;
}
} else {
// Context is not a document
if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
contains( context, elem ) && elem.id === m ) {
results.push( elem );
return results;
}
}
// Speed-up: Sizzle("TAG")
} else if ( match[2] ) {
push.apply( results, context.getElementsByTagName( selector ) );
return results;
// Speed-up: Sizzle(".CLASS")
} else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
push.apply( results, context.getElementsByClassName( m ) );
return results;
}
}
// QSA path
if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
nid = old = expando;
newContext = context;
newSelector = nodeType === 9 && selector;
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
groups = tokenize( selector );
if ( (old = context.getAttribute("id")) ) {
nid = old.replace( rescape, "\\$&" );
} else {
context.setAttribute( "id", nid );
}
nid = "[id='" + nid + "'] ";
i = groups.length;
while ( i-- ) {
groups[i] = nid + toSelector( groups[i] );
}
newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
newSelector = groups.join(",");
}
if ( newSelector ) {
try {
push.apply( results,
newContext.querySelectorAll( newSelector )
);
return results;
} catch(qsaError) {
} finally {
if ( !old ) {
context.removeAttribute("id");
}
}
}
}
}
// All others
return select( selector.replace( rtrim, "$1" ), context, results, seed );
}
/**
* Create key-value caches of limited size
* @returns {Function(string, Object)} Returns the Object data after storing it on itself with
* property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
* deleting the oldest entry
*/
function createCache() {
var keys = [];
function cache( key, value ) {
// Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
if ( keys.push( key + " " ) > Expr.cacheLength ) {
// Only keep the most recent entries
delete cache[ keys.shift() ];
}
return (cache[ key + " " ] = value);
}
return cache;
}
/**
* Mark a function for special use by Sizzle
* @param {Function} fn The function to mark
*/
function markFunction( fn ) {
fn[ expando ] = true;
return fn;
}
/**
* Support testing using an element
* @param {Function} fn Passed the created div and expects a boolean result
*/
function assert( fn ) {
var div = document.createElement("div");
try {
return !!fn( div );
} catch (e) {
return false;
} finally {
// Remove from its parent by default
if ( div.parentNode ) {
div.parentNode.removeChild( div );
}
// release memory in IE
div = null;
}
}
/**
* Adds the same handler for all of the specified attrs
* @param {String} attrs Pipe-separated list of attributes
* @param {Function} handler The method that will be applied
*/
function addHandle( attrs, handler ) {
var arr = attrs.split("|"),
i = attrs.length;
while ( i-- ) {
Expr.attrHandle[ arr[i] ] = handler;
}
}
/**
* Checks document order of two siblings
* @param {Element} a
* @param {Element} b
* @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
*/
function siblingCheck( a, b ) {
var cur = b && a,
diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
( ~b.sourceIndex || MAX_NEGATIVE ) -
( ~a.sourceIndex || MAX_NEGATIVE );
// Use IE sourceIndex if available on both nodes
if ( diff ) {
return diff;
}
// Check if b follows a
if ( cur ) {
while ( (cur = cur.nextSibling) ) {
if ( cur === b ) {
return -1;
}
}
}
return a ? 1 : -1;
}
/**
* Returns a function to use in pseudos for input types
* @param {String} type
*/
function createInputPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for buttons
* @param {String} type
*/
function createButtonPseudo( type ) {
return function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
/**
* Returns a function to use in pseudos for positionals
* @param {Function} fn
*/
function createPositionalPseudo( fn ) {
return markFunction(function( argument ) {
argument = +argument;
return markFunction(function( seed, matches ) {
var j,
matchIndexes = fn( [], seed.length, argument ),
i = matchIndexes.length;
// Match elements found at the specified indexes
while ( i-- ) {
if ( seed[ (j = matchIndexes[i]) ] ) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
/**
* Checks a node for validity as a Sizzle context
* @param {Element|Object=} context
* @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
*/
function testContext( context ) {
return context && typeof context.getElementsByTagName !== strundefined && context;
}
// Expose support vars for convenience
support = Sizzle.support = {};
/**
* Detects XML nodes
* @param {Element|Object} elem An element or a document
* @returns {Boolean} True iff elem is a non-HTML XML node
*/
isXML = Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = elem && (elem.ownerDocument || elem).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
/**
* Sets document-related variables once based on the current document
* @param {Element|Object} [doc] An element or document object to use to set the document
* @returns {Object} Returns the current document
*/
setDocument = Sizzle.setDocument = function( node ) {
var hasCompare,
doc = node ? node.ownerDocument || node : preferredDoc,
parent = doc.defaultView;
// If no document and documentElement is available, return
if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
return document;
}
// Set our document
document = doc;
docElem = doc.documentElement;
// Support tests
documentIsHTML = !isXML( doc );
// Support: IE>8
// If iframe document is assigned to "document" variable and if iframe has been reloaded,
// IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
// IE6-8 do not support the defaultView property so parent will be undefined
if ( parent && parent !== parent.top ) {
// IE11 does not have attachEvent, so all must suffer
if ( parent.addEventListener ) {
parent.addEventListener( "unload", function() {
setDocument();
}, false );
} else if ( parent.attachEvent ) {
parent.attachEvent( "onunload", function() {
setDocument();
});
}
}
/* Attributes
---------------------------------------------------------------------- */
// Support: IE<8
// Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
support.attributes = assert(function( div ) {
div.className = "i";
return !div.getAttribute("className");
});
/* getElement(s)By*
---------------------------------------------------------------------- */
// Check if getElementsByTagName("*") returns only elements
support.getElementsByTagName = assert(function( div ) {
div.appendChild( doc.createComment("") );
return !div.getElementsByTagName("*").length;
});
// Check if getElementsByClassName can be trusted
support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) {
div.innerHTML = "<div class='a'></div><div class='a i'></div>";
// Support: Safari<4
// Catch class over-caching
div.firstChild.className = "i";
// Support: Opera<10
// Catch gEBCN failure to find non-leading classes
return div.getElementsByClassName("i").length === 2;
});
// Support: IE<10
// Check if getElementById returns elements by name
// The broken getElementById methods don't pick up programatically-set names,
// so use a roundabout getElementsByName test
support.getById = assert(function( div ) {
docElem.appendChild( div ).id = expando;
return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
});
// ID find and filter
if ( support.getById ) {
Expr.find["ID"] = function( id, context ) {
if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
var m = context.getElementById( id );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [ m ] : [];
}
};
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
return elem.getAttribute("id") === attrId;
};
};
} else {
// Support: IE6/7
// getElementById is not reliable as a find shortcut
delete Expr.find["ID"];
Expr.filter["ID"] = function( id ) {
var attrId = id.replace( runescape, funescape );
return function( elem ) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === attrId;
};
};
}
// Tag
Expr.find["TAG"] = support.getElementsByTagName ?
function( tag, context ) {
if ( typeof context.getElementsByTagName !== strundefined ) {
return context.getElementsByTagName( tag );
}
} :
function( tag, context ) {
var elem,
tmp = [],
i = 0,
results = context.getElementsByTagName( tag );
// Filter out possible comments
if ( tag === "*" ) {
while ( (elem = results[i++]) ) {
if ( elem.nodeType === 1 ) {
tmp.push( elem );
}
}
return tmp;
}
return results;
};
// Class
Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
return context.getElementsByClassName( className );
}
};
/* QSA/matchesSelector
---------------------------------------------------------------------- */
// QSA and matchesSelector support
// matchesSelector(:active) reports false when true (IE9/Opera 11.5)
rbuggyMatches = [];
// qSa(:focus) reports false when true (Chrome 21)
// We allow this because of a bug in IE8/9 that throws an error
// whenever `document.activeElement` is accessed on an iframe
// So, we allow :focus to pass through QSA all the time to avoid the IE error
// See http://bugs.jquery.com/ticket/13378
rbuggyQSA = [];
if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
// Build QSA regex
// Regex strategy adopted from Diego Perini
assert(function( div ) {
// Select is set to empty string on purpose
// This is to test IE's treatment of not explicitly
// setting a boolean content attribute,
// since its presence should be enough
// http://bugs.jquery.com/ticket/12359
div.innerHTML = "<select msallowclip=''><option selected=''></option></select>";
// Support: IE8, Opera 11-12.16
// Nothing should be selected when empty strings follow ^= or $= or *=
// The test attribute must be unknown in Opera but "safe" for WinRT
// http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
if ( div.querySelectorAll("[msallowclip^='']").length ) {
rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
}
// Support: IE8
// Boolean attributes and "value" are not treated correctly
if ( !div.querySelectorAll("[selected]").length ) {
rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
}
// Webkit/Opera - :checked should return selected option elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":checked").length ) {
rbuggyQSA.push(":checked");
}
});
assert(function( div ) {
// Support: Windows 8 Native Apps
// The type and name attributes are restricted during .innerHTML assignment
var input = doc.createElement("input");
input.setAttribute( "type", "hidden" );
div.appendChild( input ).setAttribute( "name", "D" );
// Support: IE8
// Enforce case-sensitivity of name attribute
if ( div.querySelectorAll("[name=d]").length ) {
rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
}
// FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
// IE8 throws error here and will not see later tests
if ( !div.querySelectorAll(":enabled").length ) {
rbuggyQSA.push( ":enabled", ":disabled" );
}
// Opera 10-11 does not throw on post-comma invalid pseudos
div.querySelectorAll("*,:x");
rbuggyQSA.push(",.*:");
});
}
if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
docElem.webkitMatchesSelector ||
docElem.mozMatchesSelector ||
docElem.oMatchesSelector ||
docElem.msMatchesSelector) )) ) {
assert(function( div ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9)
support.disconnectedMatch = matches.call( div, "div" );
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( div, "[s!='']:x" );
rbuggyMatches.push( "!=", pseudos );
});
}
rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
/* Contains
---------------------------------------------------------------------- */
hasCompare = rnative.test( docElem.compareDocumentPosition );
// Element contains another
// Purposefully does not implement inclusive descendent
// As in, an element does not contain itself
contains = hasCompare || rnative.test( docElem.contains ) ?
function( a, b ) {
var adown = a.nodeType === 9 ? a.documentElement : a,
bup = b && b.parentNode;
return a === bup || !!( bup && bup.nodeType === 1 && (
adown.contains ?
adown.contains( bup ) :
a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
));
} :
function( a, b ) {
if ( b ) {
while ( (b = b.parentNode) ) {
if ( b === a ) {
return true;
}
}
}
return false;
};
/* Sorting
---------------------------------------------------------------------- */
// Document order sorting
sortOrder = hasCompare ?
function( a, b ) {
// Flag for duplicate removal
if ( a === b ) {
hasDuplicate = true;
return 0;
}
// Sort on method existence if only one input has compareDocumentPosition
var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
if ( compare ) {
return compare;
}
// Calculate position if both inputs belong to the same document
compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
a.compareDocumentPosition( b ) :
// Otherwise we know they are disconnected
1;
// Disconnected nodes
if ( compare & 1 ||
(!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
// Choose the first element that is related to our preferred document
if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
return -1;
}
if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
return 1;
}
// Maintain original order
return sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
}
return compare & 4 ? -1 : 1;
} :
function( a, b ) {
// Exit early if the nodes are identical
if ( a === b ) {
hasDuplicate = true;
return 0;
}
var cur,
i = 0,
aup = a.parentNode,
bup = b.parentNode,
ap = [ a ],
bp = [ b ];
// Parentless nodes are either documents or disconnected
if ( !aup || !bup ) {
return a === doc ? -1 :
b === doc ? 1 :
aup ? -1 :
bup ? 1 :
sortInput ?
( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
0;
// If the nodes are siblings, we can do a quick check
} else if ( aup === bup ) {
return siblingCheck( a, b );
}
// Otherwise we need full lists of their ancestors for comparison
cur = a;
while ( (cur = cur.parentNode) ) {
ap.unshift( cur );
}
cur = b;
while ( (cur = cur.parentNode) ) {
bp.unshift( cur );
}
// Walk down the tree looking for a discrepancy
while ( ap[i] === bp[i] ) {
i++;
}
return i ?
// Do a sibling check if the nodes have a common ancestor
siblingCheck( ap[i], bp[i] ) :
// Otherwise nodes in our document sort first
ap[i] === preferredDoc ? -1 :
bp[i] === preferredDoc ? 1 :
0;
};
return doc;
};
Sizzle.matches = function( expr, elements ) {
return Sizzle( expr, null, null, elements );
};
Sizzle.matchesSelector = function( elem, expr ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
// Make sure that attribute selectors are quoted
expr = expr.replace( rattributeQuotes, "='$1']" );
if ( support.matchesSelector && documentIsHTML &&
( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
try {
var ret = matches.call( elem, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || support.disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9
elem.document && elem.document.nodeType !== 11 ) {
return ret;
}
} catch(e) {}
}
return Sizzle( expr, document, null, [ elem ] ).length > 0;
};
Sizzle.contains = function( context, elem ) {
// Set document vars if needed
if ( ( context.ownerDocument || context ) !== document ) {
setDocument( context );
}
return contains( context, elem );
};
Sizzle.attr = function( elem, name ) {
// Set document vars if needed
if ( ( elem.ownerDocument || elem ) !== document ) {
setDocument( elem );
}
var fn = Expr.attrHandle[ name.toLowerCase() ],
// Don't get fooled by Object.prototype properties (jQuery #13807)
val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
fn( elem, name, !documentIsHTML ) :
undefined;
return val !== undefined ?
val :
support.attributes || !documentIsHTML ?
elem.getAttribute( name ) :
(val = elem.getAttributeNode(name)) && val.specified ?
val.value :
null;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Document sorting and removing duplicates
* @param {ArrayLike} results
*/
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
j = 0,
i = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
sortInput = !support.sortStable && results.slice( 0 );
results.sort( sortOrder );
if ( hasDuplicate ) {
while ( (elem = results[i++]) ) {
if ( elem === results[ i ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
// Clear input after sorting to release objects
// See https://github.com/jquery/sizzle/pull/225
sortInput = null;
return results;
};
/**
* Utility function for retrieving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
getText = Sizzle.getText = function( elem ) {
var node,
ret = "",
i = 0,
nodeType = elem.nodeType;
if ( !nodeType ) {
// If no nodeType, this is expected to be an array
while ( (node = elem[i++]) ) {
// Do not traverse comment nodes
ret += getText( node );
}
} else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent for elements
// innerText usage removed for consistency of new lines (jQuery #11153)
if ( typeof elem.textContent === "string" ) {
return elem.textContent;
} else {
// Traverse its children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
// Do not include comment or processing instruction nodes
return ret;
};
Expr = Sizzle.selectors = {
// Can be adjusted by the user
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: {},
find: {},
relative: {
">": { dir: "parentNode", first: true },
" ": { dir: "parentNode" },
"+": { dir: "previousSibling", first: true },
"~": { dir: "previousSibling" }
},
preFilter: {
"ATTR": function( match ) {
match[1] = match[1].replace( runescape, funescape );
// Move the given value to match[3] whether quoted or unquoted
match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
if ( match[2] === "~=" ) {
match[3] = " " + match[3] + " ";
}
return match.slice( 0, 4 );
},
"CHILD": function( match ) {
/* matches from matchExpr["CHILD"]
1 type (only|nth|...)
2 what (child|of-type)
3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
4 xn-component of xn+y argument ([+-]?\d*n|)
5 sign of xn-component
6 x of xn-component
7 sign of y-component
8 y of y-component
*/
match[1] = match[1].toLowerCase();
if ( match[1].slice( 0, 3 ) === "nth" ) {
// nth-* requires argument
if ( !match[3] ) {
Sizzle.error( match[0] );
}
// numeric x and y parameters for Expr.filter.CHILD
// remember that false/true cast respectively to 0/1
match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
// other types prohibit arguments
} else if ( match[3] ) {
Sizzle.error( match[0] );
}
return match;
},
"PSEUDO": function( match ) {
var excess,
unquoted = !match[6] && match[2];
if ( matchExpr["CHILD"].test( match[0] ) ) {
return null;
}
// Accept quoted arguments as-is
if ( match[3] ) {
match[2] = match[4] || match[5] || "";
// Strip excess characters from unquoted arguments
} else if ( unquoted && rpseudo.test( unquoted ) &&
// Get excess from tokenize (recursively)
(excess = tokenize( unquoted, true )) &&
// advance to the next closing parenthesis
(excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
// excess is a negative index
match[0] = match[0].slice( 0, excess );
match[2] = unquoted.slice( 0, excess );
}
// Return only captures needed by the pseudo filter method (type and argument)
return match.slice( 0, 3 );
}
},
filter: {
"TAG": function( nodeNameSelector ) {
var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
return nodeNameSelector === "*" ?
function() { return true; } :
function( elem ) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function( className ) {
var pattern = classCache[ className + " " ];
return pattern ||
(pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
classCache( className, function( elem ) {
return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
});
},
"ATTR": function( name, operator, check ) {
return function( elem ) {
var result = Sizzle.attr( elem, name );
if ( result == null ) {
return operator === "!=";
}
if ( !operator ) {
return true;
}
result += "";
return operator === "=" ? result === check :
operator === "!=" ? result !== check :
operator === "^=" ? check && result.indexOf( check ) === 0 :
operator === "*=" ? check && result.indexOf( check ) > -1 :
operator === "$=" ? check && result.slice( -check.length ) === check :
operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
false;
};
},
"CHILD": function( type, what, argument, first, last ) {
var simple = type.slice( 0, 3 ) !== "nth",
forward = type.slice( -4 ) !== "last",
ofType = what === "of-type";
return first === 1 && last === 0 ?
// Shortcut for :nth-*(n)
function( elem ) {
return !!elem.parentNode;
} :
function( elem, context, xml ) {
var cache, outerCache, node, diff, nodeIndex, start,
dir = simple !== forward ? "nextSibling" : "previousSibling",
parent = elem.parentNode,
name = ofType && elem.nodeName.toLowerCase(),
useCache = !xml && !ofType;
if ( parent ) {
// :(first|last|only)-(child|of-type)
if ( simple ) {
while ( dir ) {
node = elem;
while ( (node = node[ dir ]) ) {
if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
return false;
}
}
// Reverse direction for :only-* (if we haven't yet done so)
start = dir = type === "only" && !start && "nextSibling";
}
return true;
}
start = [ forward ? parent.firstChild : parent.lastChild ];
// non-xml :nth-child(...) stores cache data on `parent`
if ( forward && useCache ) {
// Seek `elem` from a previously-cached index
outerCache = parent[ expando ] || (parent[ expando ] = {});
cache = outerCache[ type ] || [];
nodeIndex = cache[0] === dirruns && cache[1];
diff = cache[0] === dirruns && cache[2];
node = nodeIndex && parent.childNodes[ nodeIndex ];
while ( (node = ++nodeIndex && node && node[ dir ] ||
// Fallback to seeking `elem` from the start
(diff = nodeIndex = 0) || start.pop()) ) {
// When found, cache indexes on `parent` and break
if ( node.nodeType === 1 && ++diff && node === elem ) {
outerCache[ type ] = [ dirruns, nodeIndex, diff ];
break;
}
}
// Use previously-cached element index if available
} else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
diff = cache[1];
// xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
} else {
// Use the same loop as above to seek `elem` from the start
while ( (node = ++nodeIndex && node && node[ dir ] ||
(diff = nodeIndex = 0) || start.pop()) ) {
if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
// Cache the index of each encountered element
if ( useCache ) {
(node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
}
if ( node === elem ) {
break;
}
}
}
}
// Incorporate the offset, then check against cycle size
diff -= last;
return diff === first || ( diff % first === 0 && diff / first >= 0 );
}
};
},
"PSEUDO": function( pseudo, argument ) {
// pseudo-class names are case-insensitive
// http://www.w3.org/TR/selectors/#pseudo-classes
// Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
// Remember that setFilters inherits from pseudos
var args,
fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
Sizzle.error( "unsupported pseudo: " + pseudo );
// The user may use createPseudo to indicate that
// arguments are needed to create the filter function
// just as Sizzle does
if ( fn[ expando ] ) {
return fn( argument );
}
// But maintain support for old signatures
if ( fn.length > 1 ) {
args = [ pseudo, pseudo, "", argument ];
return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
markFunction(function( seed, matches ) {
var idx,
matched = fn( seed, argument ),
i = matched.length;
while ( i-- ) {
idx = indexOf.call( seed, matched[i] );
seed[ idx ] = !( matches[ idx ] = matched[i] );
}
}) :
function( elem ) {
return fn( elem, 0, args );
};
}
return fn;
}
},
pseudos: {
// Potentially complex pseudos
"not": markFunction(function( selector ) {
// Trim the selector passed to compile
// to avoid treating leading and trailing
// spaces as combinators
var input = [],
results = [],
matcher = compile( selector.replace( rtrim, "$1" ) );
return matcher[ expando ] ?
markFunction(function( seed, matches, context, xml ) {
var elem,
unmatched = matcher( seed, null, xml, [] ),
i = seed.length;
// Match elements unmatched by `matcher`
while ( i-- ) {
if ( (elem = unmatched[i]) ) {
seed[i] = !(matches[i] = elem);
}
}
}) :
function( elem, context, xml ) {
input[0] = elem;
matcher( input, null, xml, results );
return !results.pop();
};
}),
"has": markFunction(function( selector ) {
return function( elem ) {
return Sizzle( selector, elem ).length > 0;
};
}),
"contains": markFunction(function( text ) {
return function( elem ) {
return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
};
}),
// "Whether an element is represented by a :lang() selector
// is based solely on the element's language value
// being equal to the identifier C,
// or beginning with the identifier C immediately followed by "-".
// The matching of C against the element's language value is performed case-insensitively.
// The identifier C does not have to be a valid language name."
// http://www.w3.org/TR/selectors/#lang-pseudo
"lang": markFunction( function( lang ) {
// lang value must be a valid identifier
if ( !ridentifier.test(lang || "") ) {
Sizzle.error( "unsupported lang: " + lang );
}
lang = lang.replace( runescape, funescape ).toLowerCase();
return function( elem ) {
var elemLang;
do {
if ( (elemLang = documentIsHTML ?
elem.lang :
elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
elemLang = elemLang.toLowerCase();
return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
}
} while ( (elem = elem.parentNode) && elem.nodeType === 1 );
return false;
};
}),
// Miscellaneous
"target": function( elem ) {
var hash = window.location && window.location.hash;
return hash && hash.slice( 1 ) === elem.id;
},
"root": function( elem ) {
return elem === docElem;
},
"focus": function( elem ) {
return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
},
// Boolean properties
"enabled": function( elem ) {
return elem.disabled === false;
},
"disabled": function( elem ) {
return elem.disabled === true;
},
"checked": function( elem ) {
// In CSS3, :checked should return both checked and selected elements
// http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
},
"selected": function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
// Contents
"empty": function( elem ) {
// http://www.w3.org/TR/selectors/#empty-pseudo
// :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
// but not by others (comment: 8; processing instruction: 7; etc.)
// nodeType < 6 works because attributes (2) do not appear as children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
if ( elem.nodeType < 6 ) {
return false;
}
}
return true;
},
"parent": function( elem ) {
return !Expr.pseudos["empty"]( elem );
},
// Element/input types
"header": function( elem ) {
return rheader.test( elem.nodeName );
},
"input": function( elem ) {
return rinputs.test( elem.nodeName );
},
"button": function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"text": function( elem ) {
var attr;
return elem.nodeName.toLowerCase() === "input" &&
elem.type === "text" &&
// Support: IE<8
// New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
},
// Position-in-collection
"first": createPositionalPseudo(function() {
return [ 0 ];
}),
"last": createPositionalPseudo(function( matchIndexes, length ) {
return [ length - 1 ];
}),
"eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
return [ argument < 0 ? argument + length : argument ];
}),
"even": createPositionalPseudo(function( matchIndexes, length ) {
var i = 0;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function( matchIndexes, length ) {
var i = 1;
for ( ; i < length; i += 2 ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; --i >= 0; ) {
matchIndexes.push( i );
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
var i = argument < 0 ? argument + length : argument;
for ( ; ++i < length; ) {
matchIndexes.push( i );
}
return matchIndexes;
})
}
};
Expr.pseudos["nth"] = Expr.pseudos["eq"];
// Add button/input type pseudos
for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
Expr.pseudos[ i ] = createInputPseudo( i );
}
for ( i in { submit: true, reset: true } ) {
Expr.pseudos[ i ] = createButtonPseudo( i );
}
// Easy API for creating new setFilters
function setFilters() {}
setFilters.prototype = Expr.filters = Expr.pseudos;
Expr.setFilters = new setFilters();
tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
var matched, match, tokens, type,
soFar, groups, preFilters,
cached = tokenCache[ selector + " " ];
if ( cached ) {
return parseOnly ? 0 : cached.slice( 0 );
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while ( soFar ) {
// Comma and first run
if ( !matched || (match = rcomma.exec( soFar )) ) {
if ( match ) {
// Don't consume trailing commas as valid
soFar = soFar.slice( match[0].length ) || soFar;
}
groups.push( (tokens = []) );
}
matched = false;
// Combinators
if ( (match = rcombinators.exec( soFar )) ) {
matched = match.shift();
tokens.push({
value: matched,
// Cast descendant combinators to space
type: match[0].replace( rtrim, " " )
});
soFar = soFar.slice( matched.length );
}
// Filters
for ( type in Expr.filter ) {
if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
(match = preFilters[ type ]( match ))) ) {
matched = match.shift();
tokens.push({
value: matched,
type: type,
matches: match
});
soFar = soFar.slice( matched.length );
}
}
if ( !matched ) {
break;
}
}
// Return the length of the invalid excess
// if we're just parsing
// Otherwise, throw an error or return tokens
return parseOnly ?
soFar.length :
soFar ?
Sizzle.error( selector ) :
// Cache the tokens
tokenCache( selector, groups ).slice( 0 );
};
function toSelector( tokens ) {
var i = 0,
len = tokens.length,
selector = "";
for ( ; i < len; i++ ) {
selector += tokens[i].value;
}
return selector;
}
function addCombinator( matcher, combinator, base ) {
var dir = combinator.dir,
checkNonElements = base && dir === "parentNode",
doneName = done++;
return combinator.first ?
// Check against closest ancestor/preceding element
function( elem, context, xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
return matcher( elem, context, xml );
}
}
} :
// Check against all ancestor/preceding elements
function( elem, context, xml ) {
var oldCache, outerCache,
newCache = [ dirruns, doneName ];
// We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
if ( xml ) {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
if ( matcher( elem, context, xml ) ) {
return true;
}
}
}
} else {
while ( (elem = elem[ dir ]) ) {
if ( elem.nodeType === 1 || checkNonElements ) {
outerCache = elem[ expando ] || (elem[ expando ] = {});
if ( (oldCache = outerCache[ dir ]) &&
oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
// Assign to newCache so results back-propagate to previous elements
return (newCache[ 2 ] = oldCache[ 2 ]);
} else {
// Reuse newcache so results back-propagate to previous elements
outerCache[ dir ] = newCache;
// A match means we're done; a fail means we have to keep checking
if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
return true;
}
}
}
}
}
};
}
function elementMatcher( matchers ) {
return matchers.length > 1 ?
function( elem, context, xml ) {
var i = matchers.length;
while ( i-- ) {
if ( !matchers[i]( elem, context, xml ) ) {
return false;
}
}
return true;
} :
matchers[0];
}
function multipleContexts( selector, contexts, results ) {
var i = 0,
len = contexts.length;
for ( ; i < len; i++ ) {
Sizzle( selector, contexts[i], results );
}
return results;
}
function condense( unmatched, map, filter, context, xml ) {
var elem,
newUnmatched = [],
i = 0,
len = unmatched.length,
mapped = map != null;
for ( ; i < len; i++ ) {
if ( (elem = unmatched[i]) ) {
if ( !filter || filter( elem, context, xml ) ) {
newUnmatched.push( elem );
if ( mapped ) {
map.push( i );
}
}
}
}
return newUnmatched;
}
function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
if ( postFilter && !postFilter[ expando ] ) {
postFilter = setMatcher( postFilter );
}
if ( postFinder && !postFinder[ expando ] ) {
postFinder = setMatcher( postFinder, postSelector );
}
return markFunction(function( seed, results, context, xml ) {
var temp, i, elem,
preMap = [],
postMap = [],
preexisting = results.length,
// Get initial elements from seed or context
elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
// Prefilter to get matcher input, preserving a map for seed-results synchronization
matcherIn = preFilter && ( seed || !selector ) ?
condense( elems, preMap, preFilter, context, xml ) :
elems,
matcherOut = matcher ?
// If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
// ...intermediate processing is necessary
[] :
// ...otherwise use results directly
results :
matcherIn;
// Find primary matches
if ( matcher ) {
matcher( matcherIn, matcherOut, context, xml );
}
// Apply postFilter
if ( postFilter ) {
temp = condense( matcherOut, postMap );
postFilter( temp, [], context, xml );
// Un-match failing elements by moving them back to matcherIn
i = temp.length;
while ( i-- ) {
if ( (elem = temp[i]) ) {
matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
}
}
}
if ( seed ) {
if ( postFinder || preFilter ) {
if ( postFinder ) {
// Get the final matcherOut by condensing this intermediate into postFinder contexts
temp = [];
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) ) {
// Restore matcherIn since elem is not yet a final match
temp.push( (matcherIn[i] = elem) );
}
}
postFinder( null, (matcherOut = []), temp, xml );
}
// Move matched elements from seed to results to keep them synchronized
i = matcherOut.length;
while ( i-- ) {
if ( (elem = matcherOut[i]) &&
(temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
seed[temp] = !(results[temp] = elem);
}
}
}
// Add elements to results, through postFinder if defined
} else {
matcherOut = condense(
matcherOut === results ?
matcherOut.splice( preexisting, matcherOut.length ) :
matcherOut
);
if ( postFinder ) {
postFinder( null, results, matcherOut, xml );
} else {
push.apply( results, matcherOut );
}
}
});
}
function matcherFromTokens( tokens ) {
var checkContext, matcher, j,
len = tokens.length,
leadingRelative = Expr.relative[ tokens[0].type ],
implicitRelative = leadingRelative || Expr.relative[" "],
i = leadingRelative ? 1 : 0,
// The foundational matcher ensures that elements are reachable from top-level context(s)
matchContext = addCombinator( function( elem ) {
return elem === checkContext;
}, implicitRelative, true ),
matchAnyContext = addCombinator( function( elem ) {
return indexOf.call( checkContext, elem ) > -1;
}, implicitRelative, true ),
matchers = [ function( elem, context, xml ) {
return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
(checkContext = context).nodeType ?
matchContext( elem, context, xml ) :
matchAnyContext( elem, context, xml ) );
} ];
for ( ; i < len; i++ ) {
if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
} else {
matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
// Return special upon seeing a positional matcher
if ( matcher[ expando ] ) {
// Find the next relative operator (if any) for proper handling
j = ++i;
for ( ; j < len; j++ ) {
if ( Expr.relative[ tokens[j].type ] ) {
break;
}
}
return setMatcher(
i > 1 && elementMatcher( matchers ),
i > 1 && toSelector(
// If the preceding token was a descendant combinator, insert an implicit any-element `*`
tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
).replace( rtrim, "$1" ),
matcher,
i < j && matcherFromTokens( tokens.slice( i, j ) ),
j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
j < len && toSelector( tokens )
);
}
matchers.push( matcher );
}
}
return elementMatcher( matchers );
}
function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
var bySet = setMatchers.length > 0,
byElement = elementMatchers.length > 0,
superMatcher = function( seed, context, xml, results, outermost ) {
var elem, j, matcher,
matchedCount = 0,
i = "0",
unmatched = seed && [],
setMatched = [],
contextBackup = outermostContext,
// We must always have either seed elements or outermost context
elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
// Use integer dirruns iff this is the outermost matcher
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
len = elems.length;
if ( outermost ) {
outermostContext = context !== document && context;
}
// Add elements passing elementMatchers directly to results
// Keep `i` a string if there are no elements so `matchedCount` will be "00" below
// Support: IE<9, Safari
// Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
if ( byElement && elem ) {
j = 0;
while ( (matcher = elementMatchers[j++]) ) {
if ( matcher( elem, context, xml ) ) {
results.push( elem );
break;
}
}
if ( outermost ) {
dirruns = dirrunsUnique;
}
}
// Track unmatched elements for set filters
if ( bySet ) {
// They will have gone through all possible matchers
if ( (elem = !matcher && elem) ) {
matchedCount--;
}
// Lengthen the array for every element, matched or not
if ( seed ) {
unmatched.push( elem );
}
}
}
// Apply set filters to unmatched elements
matchedCount += i;
if ( bySet && i !== matchedCount ) {
j = 0;
while ( (matcher = setMatchers[j++]) ) {
matcher( unmatched, setMatched, context, xml );
}
if ( seed ) {
// Reintegrate element matches to eliminate the need for sorting
if ( matchedCount > 0 ) {
while ( i-- ) {
if ( !(unmatched[i] || setMatched[i]) ) {
setMatched[i] = pop.call( results );
}
}
}
// Discard index placeholder values to get only actual matches
setMatched = condense( setMatched );
}
// Add matches to results
push.apply( results, setMatched );
// Seedless set matches succeeding multiple successful matchers stipulate sorting
if ( outermost && !seed && setMatched.length > 0 &&
( matchedCount + setMatchers.length ) > 1 ) {
Sizzle.uniqueSort( results );
}
}
// Override manipulation of globals by nested matchers
if ( outermost ) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
return bySet ?
markFunction( superMatcher ) :
superMatcher;
}
compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
var i,
setMatchers = [],
elementMatchers = [],
cached = compilerCache[ selector + " " ];
if ( !cached ) {
// Generate a function of recursive functions that can be used to check each element
if ( !match ) {
match = tokenize( selector );
}
i = match.length;
while ( i-- ) {
cached = matcherFromTokens( match[i] );
if ( cached[ expando ] ) {
setMatchers.push( cached );
} else {
elementMatchers.push( cached );
}
}
// Cache the compiled function
cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
// Save selector and tokenization
cached.selector = selector;
}
return cached;
};
/**
* A low-level selection function that works with Sizzle's compiled
* selector functions
* @param {String|Function} selector A selector or a pre-compiled
* selector function built with Sizzle.compile
* @param {Element} context
* @param {Array} [results]
* @param {Array} [seed] A set of elements to match against
*/
select = Sizzle.select = function( selector, context, results, seed ) {
var i, tokens, token, type, find,
compiled = typeof selector === "function" && selector,
match = !seed && tokenize( (selector = compiled.selector || selector) );
results = results || [];
// Try to minimize operations if there is no seed and only one group
if ( match.length === 1 ) {
// Take a shortcut and set the context if the root selector is an ID
tokens = match[0] = match[0].slice( 0 );
if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
support.getById && context.nodeType === 9 && documentIsHTML &&
Expr.relative[ tokens[1].type ] ) {
context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
if ( !context ) {
return results;
// Precompiled matchers will still verify ancestry, so step up a level
} else if ( compiled ) {
context = context.parentNode;
}
selector = selector.slice( tokens.shift().value.length );
}
// Fetch a seed set for right-to-left matching
i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
while ( i-- ) {
token = tokens[i];
// Abort if we hit a combinator
if ( Expr.relative[ (type = token.type) ] ) {
break;
}
if ( (find = Expr.find[ type ]) ) {
// Search, expanding context for leading sibling combinators
if ( (seed = find(
token.matches[0].replace( runescape, funescape ),
rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
)) ) {
// If seed is empty or no tokens remain, we can return early
tokens.splice( i, 1 );
selector = seed.length && toSelector( tokens );
if ( !selector ) {
push.apply( results, seed );
return results;
}
break;
}
}
}
}
// Compile and execute a filtering function if one is not provided
// Provide `match` to avoid retokenization if we modified the selector above
( compiled || compile( selector, match ) )(
seed,
context,
!documentIsHTML,
results,
rsibling.test( selector ) && testContext( context.parentNode ) || context
);
return results;
};
// One-time assignments
// Sort stability
support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
// Support: Chrome<14
// Always assume duplicates if they aren't passed to the comparison function
support.detectDuplicates = !!hasDuplicate;
// Initialize against the default document
setDocument();
// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
// Detached nodes confoundingly follow *each other*
support.sortDetached = assert(function( div1 ) {
// Should return 1, but returns 4 (following)
return div1.compareDocumentPosition( document.createElement("div") ) & 1;
});
// Support: IE<8
// Prevent attribute/property "interpolation"
// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
if ( !assert(function( div ) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild.getAttribute("href") === "#" ;
}) ) {
addHandle( "type|href|height|width", function( elem, name, isXML ) {
if ( !isXML ) {
return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
}
});
}
// Support: IE<9
// Use defaultValue in place of getAttribute("value")
if ( !support.attributes || !assert(function( div ) {
div.innerHTML = "<input/>";
div.firstChild.setAttribute( "value", "" );
return div.firstChild.getAttribute( "value" ) === "";
}) ) {
addHandle( "value", function( elem, name, isXML ) {
if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
return elem.defaultValue;
}
});
}
// Support: IE<9
// Use getAttributeNode to fetch booleans when getAttribute lies
if ( !assert(function( div ) {
return div.getAttribute("disabled") == null;
}) ) {
addHandle( booleans, function( elem, name, isXML ) {
var val;
if ( !isXML ) {
return elem[ name ] === true ? name.toLowerCase() :
(val = elem.getAttributeNode( name )) && val.specified ?
val.value :
null;
}
});
}
return Sizzle;
})( window );
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.pseudos;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
var rneedsContext = jQuery.expr.match.needsContext;
var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
var risSimple = /^.[^:#\[\.,]*$/;
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, not ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep( elements, function( elem, i ) {
/* jshint -W018 */
return !!qualifier.call( elem, i, elem ) !== not;
});
}
if ( qualifier.nodeType ) {
return jQuery.grep( elements, function( elem ) {
return ( elem === qualifier ) !== not;
});
}
if ( typeof qualifier === "string" ) {
if ( risSimple.test( qualifier ) ) {
return jQuery.filter( qualifier, elements, not );
}
qualifier = jQuery.filter( qualifier, elements );
}
return jQuery.grep( elements, function( elem ) {
return ( indexOf.call( qualifier, elem ) >= 0 ) !== not;
});
}
jQuery.filter = function( expr, elems, not ) {
var elem = elems[ 0 ];
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 && elem.nodeType === 1 ?
jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
return elem.nodeType === 1;
}));
};
jQuery.fn.extend({
find: function( selector ) {
var i,
len = this.length,
ret = [],
self = this;
if ( typeof selector !== "string" ) {
return this.pushStack( jQuery( selector ).filter(function() {
for ( i = 0; i < len; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
}) );
}
for ( i = 0; i < len; i++ ) {
jQuery.find( selector, self[ i ], ret );
}
// Needed because $( selector, context ) becomes $( context ).find( selector )
ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
ret.selector = this.selector ? this.selector + " " + selector : selector;
return ret;
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector || [], false) );
},
not: function( selector ) {
return this.pushStack( winnow(this, selector || [], true) );
},
is: function( selector ) {
return !!winnow(
this,
// If this is a positional/relative selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
typeof selector === "string" && rneedsContext.test( selector ) ?
jQuery( selector ) :
selector || [],
false
).length;
}
});
// Initialize a jQuery object
// A central reference to the root jQuery(document)
var rootjQuery,
// A simple way to check for HTML strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
// Strict HTML recognition (#11290: must start with <)
rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
init = jQuery.fn.init = function( selector, context ) {
var match, elem;
// HANDLE: $(""), $(null), $(undefined), $(false)
if ( !selector ) {
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
if ( selector[0] === "<" && selector[ selector.length - 1 ] === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = rquickExpr.exec( selector );
}
// Match html or make sure no context is specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
// scripts is true for back-compat
// Intentionally let the error be thrown if parseHTML is not present
jQuery.merge( this, jQuery.parseHTML(
match[1],
context && context.nodeType ? context.ownerDocument || context : document,
true
) );
// HANDLE: $(html, props)
if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
for ( match in context ) {
// Properties of context are called as methods if possible
if ( jQuery.isFunction( this[ match ] ) ) {
this[ match ]( context[ match ] );
// ...and otherwise set as attributes
} else {
this.attr( match, context[ match ] );
}
}
}
return this;
// HANDLE: $(#id)
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(DOMElement)
} else if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return typeof rootjQuery.ready !== "undefined" ?
rootjQuery.ready( selector ) :
// Execute immediately if ready is not present
selector( jQuery );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
};
// Give the init function the jQuery prototype for later instantiation
init.prototype = jQuery.fn;
// Initialize central reference
rootjQuery = jQuery( document );
var rparentsprev = /^(?:parents|prev(?:Until|All))/,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.extend({
dir: function( elem, dir, until ) {
var matched = [],
truncate = until !== undefined;
while ( (elem = elem[ dir ]) && elem.nodeType !== 9 ) {
if ( elem.nodeType === 1 ) {
if ( truncate && jQuery( elem ).is( until ) ) {
break;
}
matched.push( elem );
}
}
return matched;
},
sibling: function( n, elem ) {
var matched = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
matched.push( n );
}
}
return matched;
}
});
jQuery.fn.extend({
has: function( target ) {
var targets = jQuery( target, this ),
l = targets.length;
return this.filter(function() {
var i = 0;
for ( ; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
closest: function( selectors, context ) {
var cur,
i = 0,
l = this.length,
matched = [],
pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( ; i < l; i++ ) {
for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
// Always skip document fragments
if ( cur.nodeType < 11 && (pos ?
pos.index(cur) > -1 :
// Don't pass non-elements to Sizzle
cur.nodeType === 1 &&
jQuery.find.matchesSelector(cur, selectors)) ) {
matched.push( cur );
break;
}
}
}
return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[ 0 ] && this[ 0 ].parentNode ) ? this.first().prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return indexOf.call( jQuery( elem ), this[ 0 ] );
}
// Locate the position of the desired element
return indexOf.call( this,
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[ 0 ] : elem
);
},
add: function( selector, context ) {
return this.pushStack(
jQuery.unique(
jQuery.merge( this.get(), jQuery( selector, context ) )
)
);
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
});
function sibling( cur, dir ) {
while ( (cur = cur[dir]) && cur.nodeType !== 1 ) {}
return cur;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return sibling( elem, "nextSibling" );
},
prev: function( elem ) {
return sibling( elem, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return elem.contentDocument || jQuery.merge( [], elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var matched = jQuery.map( this, fn, until );
if ( name.slice( -5 ) !== "Until" ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
matched = jQuery.filter( selector, matched );
}
if ( this.length > 1 ) {
// Remove duplicates
if ( !guaranteedUnique[ name ] ) {
jQuery.unique( matched );
}
// Reverse order for parents* and prev-derivatives
if ( rparentsprev.test( name ) ) {
matched.reverse();
}
}
return this.pushStack( matched );
};
});
var rnotwhite = (/\S+/g);
// String to Object options format cache
var optionsCache = {};
// Convert String-formatted options into Object-formatted ones and store in cache
function createOptions( options ) {
var object = optionsCache[ options ] = {};
jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
object[ flag ] = true;
});
return object;
}
/*
* Create a callback list using the following parameters:
*
* options: an optional list of space-separated options that will change how
* the callback list behaves or a more traditional option object
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible options:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( options ) {
// Convert options from String-formatted to Object-formatted if needed
// (we check in cache first)
options = typeof options === "string" ?
( optionsCache[ options ] || createOptions( options ) ) :
jQuery.extend( {}, options );
var // Last fire value (for non-forgettable lists)
memory,
// Flag to know if list was already fired
fired,
// Flag to know if list is currently firing
firing,
// First callback to fire (used internally by add and fireWith)
firingStart,
// End of the loop when firing
firingLength,
// Index of currently firing callback (modified by remove if needed)
firingIndex,
// Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = !options.once && [],
// Fire callbacks
fire = function( data ) {
memory = options.memory && data;
fired = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
firing = true;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
memory = false; // To prevent further calls using add
break;
}
}
firing = false;
if ( list ) {
if ( stack ) {
if ( stack.length ) {
fire( stack.shift() );
}
} else if ( memory ) {
list = [];
} else {
self.disable();
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
// First, we save the current length
var start = list.length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
var type = jQuery.type( arg );
if ( type === "function" ) {
if ( !options.unique || !self.has( arg ) ) {
list.push( arg );
}
} else if ( arg && arg.length && type !== "string" ) {
// Inspect recursively
add( arg );
}
});
})( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away
} else if ( memory ) {
firingStart = start;
fire( memory );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
jQuery.each( arguments, function( _, arg ) {
var index;
while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
list.splice( index, 1 );
// Handle firing indexes
if ( firing ) {
if ( index <= firingLength ) {
firingLength--;
}
if ( index <= firingIndex ) {
firingIndex--;
}
}
}
});
}
return this;
},
// Check if a given callback is in the list.
// If no argument is given, return whether or not list has callbacks attached.
has: function( fn ) {
return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
},
// Remove all callbacks from the list
empty: function() {
list = [];
firingLength = 0;
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( list && ( !fired || stack ) ) {
args = args || [];
args = [ context, args.slice ? args.slice() : args ];
if ( firing ) {
stack.push( args );
} else {
fire( args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function( func ) {
var tuples = [
// action, add listener, listener list, final state
[ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
[ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
[ "notify", "progress", jQuery.Callbacks("memory") ]
],
state = "pending",
promise = {
state: function() {
return state;
},
always: function() {
deferred.done( arguments ).fail( arguments );
return this;
},
then: function( /* fnDone, fnFail, fnProgress */ ) {
var fns = arguments;
return jQuery.Deferred(function( newDefer ) {
jQuery.each( tuples, function( i, tuple ) {
var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
// deferred[ done | fail | progress ] for forwarding actions to newDefer
deferred[ tuple[1] ](function() {
var returned = fn && fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise()
.done( newDefer.resolve )
.fail( newDefer.reject )
.progress( newDefer.notify );
} else {
newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
}
});
});
fns = null;
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
return obj != null ? jQuery.extend( obj, promise ) : promise;
}
},
deferred = {};
// Keep pipe for back-compat
promise.pipe = promise.then;
// Add list-specific methods
jQuery.each( tuples, function( i, tuple ) {
var list = tuple[ 2 ],
stateString = tuple[ 3 ];
// promise[ done | fail | progress ] = list.add
promise[ tuple[1] ] = list.add;
// Handle state
if ( stateString ) {
list.add(function() {
// state = [ resolved | rejected ]
state = stateString;
// [ reject_list | resolve_list ].disable; progress_list.lock
}, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
}
// deferred[ resolve | reject | notify ]
deferred[ tuple[0] ] = function() {
deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
return this;
};
deferred[ tuple[0] + "With" ] = list.fireWith;
});
// Make the deferred a promise
promise.promise( deferred );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( subordinate /* , ..., subordinateN */ ) {
var i = 0,
resolveValues = slice.call( arguments ),
length = resolveValues.length,
// the count of uncompleted subordinates
remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
// the master Deferred. If resolveValues consist of only a single Deferred, just use that.
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
// Update function for both resolve and progress values
updateFunc = function( i, contexts, values ) {
return function( value ) {
contexts[ i ] = this;
values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
if ( values === progressValues ) {
deferred.notifyWith( contexts, values );
} else if ( !( --remaining ) ) {
deferred.resolveWith( contexts, values );
}
};
},
progressValues, progressContexts, resolveContexts;
// add listeners to Deferred subordinates; treat others as resolved
if ( length > 1 ) {
progressValues = new Array( length );
progressContexts = new Array( length );
resolveContexts = new Array( length );
for ( ; i < length; i++ ) {
if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
resolveValues[ i ].promise()
.done( updateFunc( i, resolveContexts, resolveValues ) )
.fail( deferred.reject )
.progress( updateFunc( i, progressContexts, progressValues ) );
} else {
--remaining;
}
}
}
// if we're not waiting on anything, resolve the master
if ( !remaining ) {
deferred.resolveWith( resolveContexts, resolveValues );
}
return deferred.promise();
}
});
// The deferred used on DOM ready
var readyList;
jQuery.fn.ready = function( fn ) {
// Add the callback
jQuery.ready.promise().done( fn );
return this;
};
jQuery.extend({
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Abort if there are pending holds or we're already ready
if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
return;
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.resolveWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.triggerHandler ) {
jQuery( document ).triggerHandler( "ready" );
jQuery( document ).off( "ready" );
}
}
});
/**
* The ready event handler and self cleanup method
*/
function completed() {
document.removeEventListener( "DOMContentLoaded", completed, false );
window.removeEventListener( "load", completed, false );
jQuery.ready();
}
jQuery.ready.promise = function( obj ) {
if ( !readyList ) {
readyList = jQuery.Deferred();
// Catch cases where $(document).ready() is called after the browser event has already occurred.
// we once tried to use readyState "interactive" here, but it caused issues like the one
// discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
setTimeout( jQuery.ready );
} else {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", completed, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", completed, false );
}
}
return readyList.promise( obj );
};
// Kick off the DOM ready check even if the user does not
jQuery.ready.promise();
// Multifunctional method to get and set values of a collection
// The value/s can optionally be executed if it's a function
var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
var i = 0,
len = elems.length,
bulk = key == null;
// Sets many values
if ( jQuery.type( key ) === "object" ) {
chainable = true;
for ( i in key ) {
jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
}
// Sets one value
} else if ( value !== undefined ) {
chainable = true;
if ( !jQuery.isFunction( value ) ) {
raw = true;
}
if ( bulk ) {
// Bulk operations run against the entire set
if ( raw ) {
fn.call( elems, value );
fn = null;
// ...except when executing function values
} else {
bulk = fn;
fn = function( elem, key, value ) {
return bulk.call( jQuery( elem ), value );
};
}
}
if ( fn ) {
for ( ; i < len; i++ ) {
fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
}
}
}
return chainable ?
elems :
// Gets
bulk ?
fn.call( elems ) :
len ? fn( elems[0], key ) : emptyGet;
};
/**
* Determines whether an object can have data
*/
jQuery.acceptData = function( owner ) {
// Accepts only:
// - Node
// - Node.ELEMENT_NODE
// - Node.DOCUMENT_NODE
// - Object
// - Any
/* jshint -W018 */
return owner.nodeType === 1 || owner.nodeType === 9 || !( +owner.nodeType );
};
function Data() {
// Support: Android < 4,
// Old WebKit does not have Object.preventExtensions/freeze method,
// return new empty object instead with no [[set]] accessor
Object.defineProperty( this.cache = {}, 0, {
get: function() {
return {};
}
});
this.expando = jQuery.expando + Math.random();
}
Data.uid = 1;
Data.accepts = jQuery.acceptData;
Data.prototype = {
key: function( owner ) {
// We can accept data for non-element nodes in modern browsers,
// but we should not, see #8335.
// Always return the key for a frozen object.
if ( !Data.accepts( owner ) ) {
return 0;
}
var descriptor = {},
// Check if the owner object already has a cache key
unlock = owner[ this.expando ];
// If not, create one
if ( !unlock ) {
unlock = Data.uid++;
// Secure it in a non-enumerable, non-writable property
try {
descriptor[ this.expando ] = { value: unlock };
Object.defineProperties( owner, descriptor );
// Support: Android < 4
// Fallback to a less secure definition
} catch ( e ) {
descriptor[ this.expando ] = unlock;
jQuery.extend( owner, descriptor );
}
}
// Ensure the cache object
if ( !this.cache[ unlock ] ) {
this.cache[ unlock ] = {};
}
return unlock;
},
set: function( owner, data, value ) {
var prop,
// There may be an unlock assigned to this node,
// if there is no entry for this "owner", create one inline
// and set the unlock as though an owner entry had always existed
unlock = this.key( owner ),
cache = this.cache[ unlock ];
// Handle: [ owner, key, value ] args
if ( typeof data === "string" ) {
cache[ data ] = value;
// Handle: [ owner, { properties } ] args
} else {
// Fresh assignments by object are shallow copied
if ( jQuery.isEmptyObject( cache ) ) {
jQuery.extend( this.cache[ unlock ], data );
// Otherwise, copy the properties one-by-one to the cache object
} else {
for ( prop in data ) {
cache[ prop ] = data[ prop ];
}
}
}
return cache;
},
get: function( owner, key ) {
// Either a valid cache is found, or will be created.
// New caches will be created and the unlock returned,
// allowing direct access to the newly created
// empty data object. A valid owner object must be provided.
var cache = this.cache[ this.key( owner ) ];
return key === undefined ?
cache : cache[ key ];
},
access: function( owner, key, value ) {
var stored;
// In cases where either:
//
// 1. No key was specified
// 2. A string key was specified, but no value provided
//
// Take the "read" path and allow the get method to determine
// which value to return, respectively either:
//
// 1. The entire cache object
// 2. The data stored at the key
//
if ( key === undefined ||
((key && typeof key === "string") && value === undefined) ) {
stored = this.get( owner, key );
return stored !== undefined ?
stored : this.get( owner, jQuery.camelCase(key) );
}
// [*]When the key is not a string, or both a key and value
// are specified, set or extend (existing objects) with either:
//
// 1. An object of properties
// 2. A key and value
//
this.set( owner, key, value );
// Since the "set" path can have two possible entry points
// return the expected data based on which path was taken[*]
return value !== undefined ? value : key;
},
remove: function( owner, key ) {
var i, name, camel,
unlock = this.key( owner ),
cache = this.cache[ unlock ];
if ( key === undefined ) {
this.cache[ unlock ] = {};
} else {
// Support array or space separated string of keys
if ( jQuery.isArray( key ) ) {
// If "name" is an array of keys...
// When data is initially created, via ("key", "val") signature,
// keys will be converted to camelCase.
// Since there is no way to tell _how_ a key was added, remove
// both plain key and camelCase key. #12786
// This will only penalize the array argument path.
name = key.concat( key.map( jQuery.camelCase ) );
} else {
camel = jQuery.camelCase( key );
// Try the string as a key before any manipulation
if ( key in cache ) {
name = [ key, camel ];
} else {
// If a key with the spaces exists, use it.
// Otherwise, create an array by matching non-whitespace
name = camel;
name = name in cache ?
[ name ] : ( name.match( rnotwhite ) || [] );
}
}
i = name.length;
while ( i-- ) {
delete cache[ name[ i ] ];
}
}
},
hasData: function( owner ) {
return !jQuery.isEmptyObject(
this.cache[ owner[ this.expando ] ] || {}
);
},
discard: function( owner ) {
if ( owner[ this.expando ] ) {
delete this.cache[ owner[ this.expando ] ];
}
}
};
var data_priv = new Data();
var data_user = new Data();
/*
Implementation Summary
1. Enforce API surface and semantic compatibility with 1.9.x branch
2. Improve the module's maintainability by reducing the storage
paths to a single mechanism.
3. Use the same single mechanism to support "private" and "user" data.
4. _Never_ expose "private" data to user code (TODO: Drop _data, _removeData)
5. Avoid exposing implementation details on user objects (eg. expando properties)
6. Provide a clear path for implementation upgrade to WeakMap in 2014
*/
var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
rmultiDash = /([A-Z])/g;
function dataAttr( elem, key, data ) {
var name;
// If nothing was found internally, try to fetch any
// data from the HTML5 data-* attribute
if ( data === undefined && elem.nodeType === 1 ) {
name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
data = elem.getAttribute( name );
if ( typeof data === "string" ) {
try {
data = data === "true" ? true :
data === "false" ? false :
data === "null" ? null :
// Only convert to a number if it doesn't change the string
+data + "" === data ? +data :
rbrace.test( data ) ? jQuery.parseJSON( data ) :
data;
} catch( e ) {}
// Make sure we set the data so it isn't changed later
data_user.set( elem, key, data );
} else {
data = undefined;
}
}
return data;
}
jQuery.extend({
hasData: function( elem ) {
return data_user.hasData( elem ) || data_priv.hasData( elem );
},
data: function( elem, name, data ) {
return data_user.access( elem, name, data );
},
removeData: function( elem, name ) {
data_user.remove( elem, name );
},
// TODO: Now that all calls to _data and _removeData have been replaced
// with direct calls to data_priv methods, these can be deprecated.
_data: function( elem, name, data ) {
return data_priv.access( elem, name, data );
},
_removeData: function( elem, name ) {
data_priv.remove( elem, name );
}
});
jQuery.fn.extend({
data: function( key, value ) {
var i, name, data,
elem = this[ 0 ],
attrs = elem && elem.attributes;
// Gets all values
if ( key === undefined ) {
if ( this.length ) {
data = data_user.get( elem );
if ( elem.nodeType === 1 && !data_priv.get( elem, "hasDataAttrs" ) ) {
i = attrs.length;
while ( i-- ) {
// Support: IE11+
// The attrs elements can be null (#14894)
if ( attrs[ i ] ) {
name = attrs[ i ].name;
if ( name.indexOf( "data-" ) === 0 ) {
name = jQuery.camelCase( name.slice(5) );
dataAttr( elem, name, data[ name ] );
}
}
}
data_priv.set( elem, "hasDataAttrs", true );
}
}
return data;
}
// Sets multiple values
if ( typeof key === "object" ) {
return this.each(function() {
data_user.set( this, key );
});
}
return access( this, function( value ) {
var data,
camelKey = jQuery.camelCase( key );
// The calling jQuery object (element matches) is not empty
// (and therefore has an element appears at this[ 0 ]) and the
// `value` parameter was not undefined. An empty jQuery object
// will result in `undefined` for elem = this[ 0 ] which will
// throw an exception if an attempt to read a data cache is made.
if ( elem && value === undefined ) {
// Attempt to get data from the cache
// with the key as-is
data = data_user.get( elem, key );
if ( data !== undefined ) {
return data;
}
// Attempt to get data from the cache
// with the key camelized
data = data_user.get( elem, camelKey );
if ( data !== undefined ) {
return data;
}
// Attempt to "discover" the data in
// HTML5 custom data-* attrs
data = dataAttr( elem, camelKey, undefined );
if ( data !== undefined ) {
return data;
}
// We tried really hard, but the data doesn't exist.
return;
}
// Set the data...
this.each(function() {
// First, attempt to store a copy or reference of any
// data that might've been store with a camelCased key.
var data = data_user.get( this, camelKey );
// For HTML5 data-* attribute interop, we have to
// store property names with dashes in a camelCase form.
// This might not apply to all properties...*
data_user.set( this, camelKey, value );
// *... In the case of properties that might _actually_
// have dashes, we need to also store a copy of that
// unchanged property.
if ( key.indexOf("-") !== -1 && data !== undefined ) {
data_user.set( this, key, value );
}
});
}, null, value, arguments.length > 1, null, true );
},
removeData: function( key ) {
return this.each(function() {
data_user.remove( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
var queue;
if ( elem ) {
type = ( type || "fx" ) + "queue";
queue = data_priv.get( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !queue || jQuery.isArray( data ) ) {
queue = data_priv.access( elem, type, jQuery.makeArray(data) );
} else {
queue.push( data );
}
}
return queue || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
startLength = queue.length,
fn = queue.shift(),
hooks = jQuery._queueHooks( elem, type ),
next = function() {
jQuery.dequeue( elem, type );
};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
startLength--;
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
// clear up the last queue stop function
delete hooks.stop;
fn.call( elem, next, hooks );
}
if ( !startLength && hooks ) {
hooks.empty.fire();
}
},
// not intended for public consumption - generates a queueHooks object, or returns the current one
_queueHooks: function( elem, type ) {
var key = type + "queueHooks";
return data_priv.get( elem, key ) || data_priv.access( elem, key, {
empty: jQuery.Callbacks("once memory").add(function() {
data_priv.remove( elem, [ type + "queue", key ] );
})
});
}
});
jQuery.fn.extend({
queue: function( type, data ) {
var setter = 2;
if ( typeof type !== "string" ) {
data = type;
type = "fx";
setter--;
}
if ( arguments.length < setter ) {
return jQuery.queue( this[0], type );
}
return data === undefined ?
this :
this.each(function() {
var queue = jQuery.queue( this, type, data );
// ensure a hooks for this queue
jQuery._queueHooks( this, type );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, obj ) {
var tmp,
count = 1,
defer = jQuery.Deferred(),
elements = this,
i = this.length,
resolve = function() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
};
if ( typeof type !== "string" ) {
obj = type;
type = undefined;
}
type = type || "fx";
while ( i-- ) {
tmp = data_priv.get( elements[ i ], type + "queueHooks" );
if ( tmp && tmp.empty ) {
count++;
tmp.empty.add( resolve );
}
}
resolve();
return defer.promise( obj );
}
});
var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
var isHidden = function( elem, el ) {
// isHidden might be called from jQuery#filter function;
// in that case, element will be second argument
elem = el || elem;
return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
};
var rcheckableType = (/^(?:checkbox|radio)$/i);
(function() {
var fragment = document.createDocumentFragment(),
div = fragment.appendChild( document.createElement( "div" ) ),
input = document.createElement( "input" );
// #11217 - WebKit loses check when the name is after the checked attribute
// Support: Windows Web Apps (WWA)
// `name` and `type` need .setAttribute for WWA
input.setAttribute( "type", "radio" );
input.setAttribute( "checked", "checked" );
input.setAttribute( "name", "t" );
div.appendChild( input );
// Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
// old WebKit doesn't clone checked state correctly in fragments
support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
// Make sure textarea (and checkbox) defaultValue is properly cloned
// Support: IE9-IE11+
div.innerHTML = "<textarea>x</textarea>";
support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
})();
var strundefined = typeof undefined;
support.focusinBubbles = "onfocusin" in window;
var
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
function returnTrue() {
return true;
}
function returnFalse() {
return false;
}
function safeActiveElement() {
try {
return document.activeElement;
} catch ( err ) { }
}
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
global: {},
add: function( elem, types, handler, data, selector ) {
var handleObjIn, eventHandle, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.get( elem );
// Don't attach events to noData or text/comment nodes (but allow plain objects)
if ( !elemData ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
// Make sure that the handler has a unique ID, used to find/remove it later
if ( !handler.guid ) {
handler.guid = jQuery.guid++;
}
// Init the element's event structure and main handler, if this is the first
if ( !(events = elemData.events) ) {
events = elemData.events = {};
}
if ( !(eventHandle = elemData.handle) ) {
eventHandle = elemData.handle = function( e ) {
// Discard the second event of a jQuery.event.trigger() and
// when an event is called after a page has unloaded
return typeof jQuery !== strundefined && jQuery.event.triggered !== e.type ?
jQuery.event.dispatch.apply( elem, arguments ) : undefined;
};
}
// Handle multiple events separated by a space
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// There *must* be a type, no attaching namespace-only handlers
if ( !type ) {
continue;
}
// If event changes its type, use the special event handlers for the changed type
special = jQuery.event.special[ type ] || {};
// If selector defined, determine special event api type, otherwise given type
type = ( selector ? special.delegateType : special.bindType ) || type;
// Update special based on newly reset type
special = jQuery.event.special[ type ] || {};
// handleObj is passed to all event handlers
handleObj = jQuery.extend({
type: type,
origType: origType,
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
if ( !(handlers = events[ type ]) ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var j, origCount, tmp,
events, t, handleObj,
special, handlers, type, namespaces, origType,
elemData = data_priv.hasData( elem ) && data_priv.get( elem );
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = ( types || "" ).match( rnotwhite ) || [ "" ];
t = types.length;
while ( t-- ) {
tmp = rtypenamespace.exec( types[t] ) || [];
type = origType = tmp[1];
namespaces = ( tmp[2] || "" ).split( "." ).sort();
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector ? special.delegateType : special.bindType ) || type;
handlers = events[ type ] || [];
tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
// Remove matching events
origCount = j = handlers.length;
while ( j-- ) {
handleObj = handlers[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !tmp || tmp.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
handlers.splice( j, 1 );
if ( handleObj.selector ) {
handlers.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( origCount && !handlers.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
delete elemData.handle;
data_priv.remove( elem, "events" );
}
},
trigger: function( event, data, elem, onlyHandlers ) {
var i, cur, tmp, bubbleType, ontype, handle, special,
eventPath = [ elem || document ],
type = hasOwn.call( event, "type" ) ? event.type : event,
namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
cur = tmp = elem = elem || document;
// Don't do events on text and comment nodes
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf(".") >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
ontype = type.indexOf(":") < 0 && "on" + type;
// Caller can pass in a jQuery.Event object, Object, or just an event type string
event = event[ jQuery.expando ] ?
event :
new jQuery.Event( type, typeof event === "object" && event );
// Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
event.isTrigger = onlyHandlers ? 2 : 3;
event.namespace = namespaces.join(".");
event.namespace_re = event.namespace ?
new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
null;
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data == null ?
[ event ] :
jQuery.makeArray( data, [ event ] );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
if ( !rfocusMorph.test( bubbleType + type ) ) {
cur = cur.parentNode;
}
for ( ; cur; cur = cur.parentNode ) {
eventPath.push( cur );
tmp = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( tmp === (elem.ownerDocument || document) ) {
eventPath.push( tmp.defaultView || tmp.parentWindow || window );
}
}
// Fire handlers on the event path
i = 0;
while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
event.type = i > 1 ?
bubbleType :
special.bindType || type;
// jQuery handler
handle = ( data_priv.get( cur, "events" ) || {} )[ event.type ] && data_priv.get( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Native handler
handle = ontype && cur[ ontype ];
if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
event.result = handle.apply( cur, data );
if ( event.result === false ) {
event.preventDefault();
}
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Don't do default actions on window, that's where global variables be (#6170)
if ( ontype && jQuery.isFunction( elem[ type ] ) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
tmp = elem[ ontype ];
if ( tmp ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( tmp ) {
elem[ ontype ] = tmp;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event );
var i, j, ret, matched, handleObj,
handlerQueue = [],
args = slice.call( arguments ),
handlers = ( data_priv.get( this, "events" ) || {} )[ event.type ] || [],
special = jQuery.event.special[ event.type ] || {};
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// Call the preDispatch hook for the mapped type, and let it bail if desired
if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
return;
}
// Determine handlers
handlerQueue = jQuery.event.handlers.call( this, event, handlers );
// Run delegates first; they may want to stop propagation beneath us
i = 0;
while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
event.currentTarget = matched.elem;
j = 0;
while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
// Triggered event must either 1) have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
event.handleObj = handleObj;
event.data = handleObj.data;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// Call the postDispatch hook for the mapped type
if ( special.postDispatch ) {
special.postDispatch.call( this, event );
}
return event.result;
},
handlers: function( event, handlers ) {
var i, matches, sel, handleObj,
handlerQueue = [],
delegateCount = handlers.delegateCount,
cur = event.target;
// Find delegate handlers
// Black-hole SVG <use> instance trees (#13180)
// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
for ( ; cur !== this; cur = cur.parentNode || this ) {
// Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
if ( cur.disabled !== true || event.type !== "click" ) {
matches = [];
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
// Don't conflict with Object.prototype properties (#13203)
sel = handleObj.selector + " ";
if ( matches[ sel ] === undefined ) {
matches[ sel ] = handleObj.needsContext ?
jQuery( sel, this ).index( cur ) >= 0 :
jQuery.find( sel, this, null, [ cur ] ).length;
}
if ( matches[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, handlers: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( delegateCount < handlers.length ) {
handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
}
return handlerQueue;
},
// Includes some event props shared by KeyEvent and MouseEvent
props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
fixHooks: {},
keyHooks: {
props: "char charCode key keyCode".split(" "),
filter: function( event, original ) {
// Add which for key events
if ( event.which == null ) {
event.which = original.charCode != null ? original.charCode : original.keyCode;
}
return event;
}
},
mouseHooks: {
props: "button buttons clientX clientY offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
filter: function( event, original ) {
var eventDoc, doc, body,
button = original.button;
// Calculate pageX/Y if missing and clientX/Y available
if ( event.pageX == null && original.clientX != null ) {
eventDoc = event.target.ownerDocument || document;
doc = eventDoc.documentElement;
body = eventDoc.body;
event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
}
// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && button !== undefined ) {
event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
}
return event;
}
},
fix: function( event ) {
if ( event[ jQuery.expando ] ) {
return event;
}
// Create a writable copy of the event object and normalize some properties
var i, prop, copy,
type = event.type,
originalEvent = event,
fixHook = this.fixHooks[ type ];
if ( !fixHook ) {
this.fixHooks[ type ] = fixHook =
rmouseEvent.test( type ) ? this.mouseHooks :
rkeyEvent.test( type ) ? this.keyHooks :
{};
}
copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
event = new jQuery.Event( originalEvent );
i = copy.length;
while ( i-- ) {
prop = copy[ i ];
event[ prop ] = originalEvent[ prop ];
}
// Support: Cordova 2.5 (WebKit) (#13255)
// All events should have a target; Cordova deviceready doesn't
if ( !event.target ) {
event.target = document;
}
// Support: Safari 6.0+, Chrome < 28
// Target should not be a text node (#504, #13143)
if ( event.target.nodeType === 3 ) {
event.target = event.target.parentNode;
}
return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
},
special: {
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
// Fire native event if possible so blur/focus sequence is correct
trigger: function() {
if ( this !== safeActiveElement() && this.focus ) {
this.focus();
return false;
}
},
delegateType: "focusin"
},
blur: {
trigger: function() {
if ( this === safeActiveElement() && this.blur ) {
this.blur();
return false;
}
},
delegateType: "focusout"
},
click: {
// For checkbox, fire native event so checked state will be right
trigger: function() {
if ( this.type === "checkbox" && this.click && jQuery.nodeName( this, "input" ) ) {
this.click();
return false;
}
},
// For cross-browser consistency, don't fire native .click() on links
_default: function( event ) {
return jQuery.nodeName( event.target, "a" );
}
},
beforeunload: {
postDispatch: function( event ) {
// Support: Firefox 20+
// Firefox doesn't alert if the returnValue field is not set.
if ( event.result !== undefined && event.originalEvent ) {
event.originalEvent.returnValue = event.result;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{
type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
jQuery.removeEvent = function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = src.defaultPrevented ||
src.defaultPrevented === undefined &&
// Support: Android < 4.0
src.returnValue === false ?
returnTrue :
returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse,
preventDefault: function() {
var e = this.originalEvent;
this.isDefaultPrevented = returnTrue;
if ( e && e.preventDefault ) {
e.preventDefault();
}
},
stopPropagation: function() {
var e = this.originalEvent;
this.isPropagationStopped = returnTrue;
if ( e && e.stopPropagation ) {
e.stopPropagation();
}
},
stopImmediatePropagation: function() {
var e = this.originalEvent;
this.isImmediatePropagationStopped = returnTrue;
if ( e && e.stopImmediatePropagation ) {
e.stopImmediatePropagation();
}
this.stopPropagation();
}
};
// Create mouseenter/leave events using mouseover/out and event-time checks
// Support: Chrome 15+
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout",
pointerenter: "pointerover",
pointerleave: "pointerout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var ret,
target = this,
related = event.relatedTarget,
handleObj = event.handleObj;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// Create "bubbling" focus and blur events
// Support: Firefox, Chrome, Safari
if ( !support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler on the document while someone wants focusin/focusout
var handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix );
if ( !attaches ) {
doc.addEventListener( orig, handler, true );
}
data_priv.access( doc, fix, ( attaches || 0 ) + 1 );
},
teardown: function() {
var doc = this.ownerDocument || this,
attaches = data_priv.access( doc, fix ) - 1;
if ( !attaches ) {
doc.removeEventListener( orig, handler, true );
data_priv.remove( doc, fix );
} else {
data_priv.access( doc, fix, attaches );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) {
// ( types-Object, data )
data = data || selector;
selector = undefined;
}
for ( type in types ) {
this.on( type, selector, data, types[ type ], one );
}
return this;
}
if ( data == null && fn == null ) {
// ( types, fn )
fn = selector;
data = selector = undefined;
} else if ( fn == null ) {
if ( typeof selector === "string" ) {
// ( types, selector, fn )
fn = data;
data = undefined;
} else {
// ( types, data, fn )
fn = data;
data = selector;
selector = undefined;
}
}
if ( fn === false ) {
fn = returnFalse;
} else if ( !fn ) {
return this;
}
if ( one === 1 ) {
origFn = fn;
fn = function( event ) {
// Can use an empty set, since event contains the info
jQuery().off( event );
return origFn.apply( this, arguments );
};
// Use same guid so caller can remove using origFn
fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
}
return this.each( function() {
jQuery.event.add( this, types, fn, data, selector );
});
},
one: function( types, selector, data, fn ) {
return this.on( types, selector, data, fn, 1 );
},
off: function( types, selector, fn ) {
var handleObj, type;
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
handleObj = types.handleObj;
jQuery( types.delegateTarget ).off(
handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
handleObj.selector,
handleObj.handler
);
return this;
}
if ( typeof types === "object" ) {
// ( types-object [, selector] )
for ( type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
var elem = this[0];
if ( elem ) {
return jQuery.event.trigger( type, data, elem, true );
}
}
});
var
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /^$|\/(?:java|ecma)script/i,
rscriptTypeMasked = /^true\/(.*)/,
rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
// We have to close these tags to support XHTML (#13200)
wrapMap = {
// Support: IE 9
option: [ 1, "<select multiple='multiple'>", "</select>" ],
thead: [ 1, "<table>", "</table>" ],
col: [ 2, "<table><colgroup>", "</colgroup></table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
_default: [ 0, "", "" ]
};
// Support: IE 9
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// Support: 1.x compatibility
// Manipulating tables requires a tbody
function manipulationTarget( elem, content ) {
return jQuery.nodeName( elem, "table" ) &&
jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
elem.getElementsByTagName("tbody")[0] ||
elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
elem;
}
// Replace/restore the type attribute of script elements for safe DOM manipulation
function disableScript( elem ) {
elem.type = (elem.getAttribute("type") !== null) + "/" + elem.type;
return elem;
}
function restoreScript( elem ) {
var match = rscriptTypeMasked.exec( elem.type );
if ( match ) {
elem.type = match[ 1 ];
} else {
elem.removeAttribute("type");
}
return elem;
}
// Mark scripts as having already been evaluated
function setGlobalEval( elems, refElements ) {
var i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
data_priv.set(
elems[ i ], "globalEval", !refElements || data_priv.get( refElements[ i ], "globalEval" )
);
}
}
function cloneCopyEvent( src, dest ) {
var i, l, type, pdataOld, pdataCur, udataOld, udataCur, events;
if ( dest.nodeType !== 1 ) {
return;
}
// 1. Copy private data: events, handlers, etc.
if ( data_priv.hasData( src ) ) {
pdataOld = data_priv.access( src );
pdataCur = data_priv.set( dest, pdataOld );
events = pdataOld.events;
if ( events ) {
delete pdataCur.handle;
pdataCur.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
}
// 2. Copy user data
if ( data_user.hasData( src ) ) {
udataOld = data_user.access( src );
udataCur = jQuery.extend( {}, udataOld );
data_user.set( dest, udataCur );
}
}
function getAll( context, tag ) {
var ret = context.getElementsByTagName ? context.getElementsByTagName( tag || "*" ) :
context.querySelectorAll ? context.querySelectorAll( tag || "*" ) :
[];
return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
jQuery.merge( [ context ], ret ) :
ret;
}
// Support: IE >= 9
function fixInput( src, dest ) {
var nodeName = dest.nodeName.toLowerCase();
// Fails to persist the checked state of a cloned checkbox or radio button.
if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
dest.checked = src.checked;
// Fails to return the selected option to the default selected state when cloning options
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
}
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var i, l, srcElements, destElements,
clone = elem.cloneNode( true ),
inPage = jQuery.contains( elem.ownerDocument, elem );
// Support: IE >= 9
// Fix Cloning issues
if ( !support.noCloneChecked && ( elem.nodeType === 1 || elem.nodeType === 11 ) &&
!jQuery.isXMLDoc( elem ) ) {
// We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
destElements = getAll( clone );
srcElements = getAll( elem );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
fixInput( srcElements[ i ], destElements[ i ] );
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
if ( deepDataAndEvents ) {
srcElements = srcElements || getAll( elem );
destElements = destElements || getAll( clone );
for ( i = 0, l = srcElements.length; i < l; i++ ) {
cloneCopyEvent( srcElements[ i ], destElements[ i ] );
}
} else {
cloneCopyEvent( elem, clone );
}
}
// Preserve script evaluation history
destElements = getAll( clone, "script" );
if ( destElements.length > 0 ) {
setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
}
// Return the cloned set
return clone;
},
buildFragment: function( elems, context, scripts, selection ) {
var elem, tmp, tag, wrap, contains, j,
fragment = context.createDocumentFragment(),
nodes = [],
i = 0,
l = elems.length;
for ( ; i < l; i++ ) {
elem = elems[ i ];
if ( elem || elem === 0 ) {
// Add nodes directly
if ( jQuery.type( elem ) === "object" ) {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
// Convert non-html into a text node
} else if ( !rhtml.test( elem ) ) {
nodes.push( context.createTextNode( elem ) );
// Convert html into DOM nodes
} else {
tmp = tmp || fragment.appendChild( context.createElement("div") );
// Deserialize a standard representation
tag = ( rtagName.exec( elem ) || [ "", "" ] )[ 1 ].toLowerCase();
wrap = wrapMap[ tag ] || wrapMap._default;
tmp.innerHTML = wrap[ 1 ] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[ 2 ];
// Descend through wrappers to the right content
j = wrap[ 0 ];
while ( j-- ) {
tmp = tmp.lastChild;
}
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( nodes, tmp.childNodes );
// Remember the top-level container
tmp = fragment.firstChild;
// Fixes #12346
// Support: Webkit, IE
tmp.textContent = "";
}
}
}
// Remove wrapper from fragment
fragment.textContent = "";
i = 0;
while ( (elem = nodes[ i++ ]) ) {
// #4087 - If origin and destination elements are the same, and this is
// that element, do not do anything
if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
continue;
}
contains = jQuery.contains( elem.ownerDocument, elem );
// Append to fragment
tmp = getAll( fragment.appendChild( elem ), "script" );
// Preserve script evaluation history
if ( contains ) {
setGlobalEval( tmp );
}
// Capture executables
if ( scripts ) {
j = 0;
while ( (elem = tmp[ j++ ]) ) {
if ( rscriptType.test( elem.type || "" ) ) {
scripts.push( elem );
}
}
}
}
return fragment;
},
cleanData: function( elems ) {
var data, elem, type, key,
special = jQuery.event.special,
i = 0;
for ( ; (elem = elems[ i ]) !== undefined; i++ ) {
if ( jQuery.acceptData( elem ) ) {
key = elem[ data_priv.expando ];
if ( key && (data = data_priv.cache[ key ]) ) {
if ( data.events ) {
for ( type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
}
if ( data_priv.cache[ key ] ) {
// Discard any remaining `private` data
delete data_priv.cache[ key ];
}
}
}
// Discard any remaining `user` data
delete data_user.cache[ elem[ data_user.expando ] ];
}
}
});
jQuery.fn.extend({
text: function( value ) {
return access( this, function( value ) {
return value === undefined ?
jQuery.text( this ) :
this.empty().each(function() {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
this.textContent = value;
}
});
}, null, value, arguments.length );
},
append: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip( arguments, function( elem ) {
if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
var target = manipulationTarget( this, elem );
target.insertBefore( elem, target.firstChild );
}
});
},
before: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this );
}
});
},
after: function() {
return this.domManip( arguments, function( elem ) {
if ( this.parentNode ) {
this.parentNode.insertBefore( elem, this.nextSibling );
}
});
},
remove: function( selector, keepData /* Internal Use Only */ ) {
var elem,
elems = selector ? jQuery.filter( selector, this ) : this,
i = 0;
for ( ; (elem = elems[i]) != null; i++ ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem ) );
}
if ( elem.parentNode ) {
if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
setGlobalEval( getAll( elem, "script" ) );
}
elem.parentNode.removeChild( elem );
}
}
return this;
},
empty: function() {
var elem,
i = 0;
for ( ; (elem = this[i]) != null; i++ ) {
if ( elem.nodeType === 1 ) {
// Prevent memory leaks
jQuery.cleanData( getAll( elem, false ) );
// Remove any remaining nodes
elem.textContent = "";
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map(function() {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
return access( this, function( value ) {
var elem = this[ 0 ] || {},
i = 0,
l = this.length;
if ( value === undefined && elem.nodeType === 1 ) {
return elem.innerHTML;
}
// See if we can take a shortcut and just use innerHTML
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
!wrapMap[ ( rtagName.exec( value ) || [ "", "" ] )[ 1 ].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for ( ; i < l; i++ ) {
elem = this[ i ] || {};
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( getAll( elem, false ) );
elem.innerHTML = value;
}
}
elem = 0;
// If using innerHTML throws an exception, use the fallback method
} catch( e ) {}
}
if ( elem ) {
this.empty().append( value );
}
}, null, value, arguments.length );
},
replaceWith: function() {
var arg = arguments[ 0 ];
// Make the changes, replacing each context element with the new content
this.domManip( arguments, function( elem ) {
arg = this.parentNode;
jQuery.cleanData( getAll( this ) );
if ( arg ) {
arg.replaceChild( elem, this );
}
});
// Force removal if there was no new content (e.g., from empty arguments)
return arg && (arg.length || arg.nodeType) ? this : this.remove();
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, callback ) {
// Flatten any nested arrays
args = concat.apply( [], args );
var fragment, first, scripts, hasScripts, node, doc,
i = 0,
l = this.length,
set = this,
iNoClone = l - 1,
value = args[ 0 ],
isFunction = jQuery.isFunction( value );
// We can't cloneNode fragments that contain checked, in WebKit
if ( isFunction ||
( l > 1 && typeof value === "string" &&
!support.checkClone && rchecked.test( value ) ) ) {
return this.each(function( index ) {
var self = set.eq( index );
if ( isFunction ) {
args[ 0 ] = value.call( this, index, self.html() );
}
self.domManip( args, callback );
});
}
if ( l ) {
fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
first = fragment.firstChild;
if ( fragment.childNodes.length === 1 ) {
fragment = first;
}
if ( first ) {
scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
hasScripts = scripts.length;
// Use the original fragment for the last item instead of the first because it can end up
// being emptied incorrectly in certain situations (#8070).
for ( ; i < l; i++ ) {
node = fragment;
if ( i !== iNoClone ) {
node = jQuery.clone( node, true, true );
// Keep references to cloned scripts for later restoration
if ( hasScripts ) {
// Support: QtWebKit
// jQuery.merge because push.apply(_, arraylike) throws
jQuery.merge( scripts, getAll( node, "script" ) );
}
}
callback.call( this[ i ], node, i );
}
if ( hasScripts ) {
doc = scripts[ scripts.length - 1 ].ownerDocument;
// Reenable scripts
jQuery.map( scripts, restoreScript );
// Evaluate executable scripts on first document insertion
for ( i = 0; i < hasScripts; i++ ) {
node = scripts[ i ];
if ( rscriptType.test( node.type || "" ) &&
!data_priv.access( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
if ( node.src ) {
// Optional AJAX dependency, but won't run scripts if not present
if ( jQuery._evalUrl ) {
jQuery._evalUrl( node.src );
}
} else {
jQuery.globalEval( node.textContent.replace( rcleanScript, "" ) );
}
}
}
}
}
}
return this;
}
});
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var elems,
ret = [],
insert = jQuery( selector ),
last = insert.length - 1,
i = 0;
for ( ; i <= last; i++ ) {
elems = i === last ? this : this.clone( true );
jQuery( insert[ i ] )[ original ]( elems );
// Support: QtWebKit
// .get() because push.apply(_, arraylike) throws
push.apply( ret, elems.get() );
}
return this.pushStack( ret );
};
});
var iframe,
elemdisplay = {};
/**
* Retrieve the actual display of a element
* @param {String} name nodeName of the element
* @param {Object} doc Document object
*/
// Called only from within defaultDisplay
function actualDisplay( name, doc ) {
var style,
elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
// getDefaultComputedStyle might be reliably used only on attached element
display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
// Use of this method is a temporary fix (more like optmization) until something better comes along,
// since it was removed from specification and supported only in FF
style.display : jQuery.css( elem[ 0 ], "display" );
// We don't have any data stored on the element,
// so use "detach" method as fast way to get rid of the element
elem.detach();
return display;
}
/**
* Try to determine the default display value of an element
* @param {String} nodeName
*/
function defaultDisplay( nodeName ) {
var doc = document,
display = elemdisplay[ nodeName ];
if ( !display ) {
display = actualDisplay( nodeName, doc );
// If the simple way fails, read from inside an iframe
if ( display === "none" || !display ) {
// Use the already-created iframe if possible
iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
// Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
doc = iframe[ 0 ].contentDocument;
// Support: IE
doc.write();
doc.close();
display = actualDisplay( nodeName, doc );
iframe.detach();
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return display;
}
var rmargin = (/^margin/);
var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
var getStyles = function( elem ) {
return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
};
function curCSS( elem, name, computed ) {
var width, minWidth, maxWidth, ret,
style = elem.style;
computed = computed || getStyles( elem );
// Support: IE9
// getPropertyValue is only needed for .css('filter') in IE9, see #12537
if ( computed ) {
ret = computed.getPropertyValue( name ) || computed[ name ];
}
if ( computed ) {
if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
ret = jQuery.style( elem, name );
}
// Support: iOS < 6
// A tribute to the "awesome hack by Dean Edwards"
// iOS < 6 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
// this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
// Remember the original values
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
// Put in the new values to get a computed value out
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
// Revert the changed values
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret !== undefined ?
// Support: IE
// IE returns zIndex value as an integer.
ret + "" :
ret;
}
function addGetHookIf( conditionFn, hookFn ) {
// Define the hook, we'll check on the first run if it's really needed.
return {
get: function() {
if ( conditionFn() ) {
// Hook not needed (or it's not possible to use it due to missing dependency),
// remove it.
// Since there are no other hooks for marginRight, remove the whole object.
delete this.get;
return;
}
// Hook needed; redefine it so that the support test is not executed again.
return (this.get = hookFn).apply( this, arguments );
}
};
}
(function() {
var pixelPositionVal, boxSizingReliableVal,
docElem = document.documentElement,
container = document.createElement( "div" ),
div = document.createElement( "div" );
if ( !div.style ) {
return;
}
div.style.backgroundClip = "content-box";
div.cloneNode( true ).style.backgroundClip = "";
support.clearCloneStyle = div.style.backgroundClip === "content-box";
container.style.cssText = "border:0;width:0;height:0;top:0;left:-9999px;margin-top:1px;" +
"position:absolute";
container.appendChild( div );
// Executing both pixelPosition & boxSizingReliable tests require only one layout
// so they're executed at the same time to save the second computation.
function computePixelPositionAndBoxSizingReliable() {
div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
"box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
"border:1px;padding:1px;width:4px;position:absolute";
div.innerHTML = "";
docElem.appendChild( container );
var divStyle = window.getComputedStyle( div, null );
pixelPositionVal = divStyle.top !== "1%";
boxSizingReliableVal = divStyle.width === "4px";
docElem.removeChild( container );
}
// Support: node.js jsdom
// Don't assume that getComputedStyle is a property of the global object
if ( window.getComputedStyle ) {
jQuery.extend( support, {
pixelPosition: function() {
// This test is executed only once but we still do memoizing
// since we can use the boxSizingReliable pre-computing.
// No need to check if the test was already performed, though.
computePixelPositionAndBoxSizingReliable();
return pixelPositionVal;
},
boxSizingReliable: function() {
if ( boxSizingReliableVal == null ) {
computePixelPositionAndBoxSizingReliable();
}
return boxSizingReliableVal;
},
reliableMarginRight: function() {
// Support: Android 2.3
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. (#3333)
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// This support function is only executed once so no memoizing is needed.
var ret,
marginDiv = div.appendChild( document.createElement( "div" ) );
// Reset CSS: box-sizing; display; margin; border; padding
marginDiv.style.cssText = div.style.cssText =
// Support: Firefox<29, Android 2.3
// Vendor-prefix box-sizing
"-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
"box-sizing:content-box;display:block;margin:0;border:0;padding:0";
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
docElem.appendChild( container );
ret = !parseFloat( window.getComputedStyle( marginDiv, null ).marginRight );
docElem.removeChild( container );
return ret;
}
});
}
})();
// A method for quickly swapping in/out CSS properties to get correct calculations.
jQuery.swap = function( elem, options, callback, args ) {
var ret, name,
old = {};
// Remember the old values, and insert the new ones
for ( name in options ) {
old[ name ] = elem.style[ name ];
elem.style[ name ] = options[ name ];
}
ret = callback.apply( elem, args || [] );
// Revert the old values
for ( name in options ) {
elem.style[ name ] = old[ name ];
}
return ret;
};
var
// swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
// see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
cssNormalTransform = {
letterSpacing: "0",
fontWeight: "400"
},
cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
// return a css property mapped to a potentially vendor prefixed property
function vendorPropName( style, name ) {
// shortcut for names that are not vendor prefixed
if ( name in style ) {
return name;
}
// check for vendor prefixed names
var capName = name[0].toUpperCase() + name.slice(1),
origName = name,
i = cssPrefixes.length;
while ( i-- ) {
name = cssPrefixes[ i ] + capName;
if ( name in style ) {
return name;
}
}
return origName;
}
function setPositiveNumber( elem, value, subtract ) {
var matches = rnumsplit.exec( value );
return matches ?
// Guard against undefined "subtract", e.g., when used as in cssHooks
Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
value;
}
function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
var i = extra === ( isBorderBox ? "border" : "content" ) ?
// If we already have the right measurement, avoid augmentation
4 :
// Otherwise initialize for horizontal or vertical properties
name === "width" ? 1 : 0,
val = 0;
for ( ; i < 4; i += 2 ) {
// both box models exclude margin, so add it if we want it
if ( extra === "margin" ) {
val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
}
if ( isBorderBox ) {
// border-box includes padding, so remove it if we want content
if ( extra === "content" ) {
val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
}
// at this point, extra isn't border nor margin, so remove border
if ( extra !== "margin" ) {
val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
} else {
// at this point, extra isn't content, so add padding
val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
// at this point, extra isn't content nor padding, so add border
if ( extra !== "padding" ) {
val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
}
}
}
return val;
}
function getWidthOrHeight( elem, name, extra ) {
// Start with offset property, which is equivalent to the border-box value
var valueIsBorderBox = true,
val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
styles = getStyles( elem ),
isBorderBox = jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
// some non-html elements return undefined for offsetWidth, so check for null/undefined
// svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
// MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
if ( val <= 0 || val == null ) {
// Fall back to computed then uncomputed css if necessary
val = curCSS( elem, name, styles );
if ( val < 0 || val == null ) {
val = elem.style[ name ];
}
// Computed unit is not pixels. Stop here and return.
if ( rnumnonpx.test(val) ) {
return val;
}
// we need the check for style in case a browser which returns unreliable values
// for getComputedStyle silently falls back to the reliable elem.style
valueIsBorderBox = isBorderBox &&
( support.boxSizingReliable() || val === elem.style[ name ] );
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
}
// use the active box-sizing model to add/subtract irrelevant styles
return ( val +
augmentWidthOrHeight(
elem,
name,
extra || ( isBorderBox ? "border" : "content" ),
valueIsBorderBox,
styles
)
) + "px";
}
function showHide( elements, show ) {
var display, elem, hidden,
values = [],
index = 0,
length = elements.length;
for ( ; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
values[ index ] = data_priv.get( elem, "olddisplay" );
display = elem.style.display;
if ( show ) {
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !values[ index ] && display === "none" ) {
elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( elem.style.display === "" && isHidden( elem ) ) {
values[ index ] = data_priv.access( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
} else {
hidden = isHidden( elem );
if ( display !== "none" || !hidden ) {
data_priv.set( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( index = 0; index < length; index++ ) {
elem = elements[ index ];
if ( !elem.style ) {
continue;
}
if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
elem.style.display = show ? values[ index ] || "" : "none";
}
}
return elements;
}
jQuery.extend({
// Add in style property hooks for overriding the default
// behavior of getting and setting a style property
cssHooks: {
opacity: {
get: function( elem, computed ) {
if ( computed ) {
// We should always get a number back from opacity
var ret = curCSS( elem, "opacity" );
return ret === "" ? "1" : ret;
}
}
}
},
// Don't automatically add "px" to these possibly-unitless properties
cssNumber: {
"columnCount": true,
"fillOpacity": true,
"flexGrow": true,
"flexShrink": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"order": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": "cssFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, hooks,
origName = jQuery.camelCase( name ),
style = elem.style;
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that null and NaN values aren't set. See: #7116
if ( value == null || value !== value ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// Fixes #8908, it can be done more correctly by specifying setters in cssHooks,
// but it would mean to define eight (for every problematic property) identical functions
if ( !support.clearCloneStyle && value === "" && name.indexOf( "background" ) === 0 ) {
style[ name ] = "inherit";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
style[ name ] = value;
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra, styles ) {
var val, num, hooks,
origName = jQuery.camelCase( name );
// Make sure that we're working with the right name
name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
// gets hook for the prefixed version
// followed by the unprefixed version
hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks ) {
val = hooks.get( elem, true, extra );
}
// Otherwise, if a way to get the computed value exists, use that
if ( val === undefined ) {
val = curCSS( elem, name, styles );
}
//convert "normal" to computed value
if ( val === "normal" && name in cssNormalTransform ) {
val = cssNormalTransform[ name ];
}
// Return, converting to number if forced or a qualifier was provided and val looks numeric
if ( extra === "" || extra ) {
num = parseFloat( val );
return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
}
return val;
}
});
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
// certain elements can have dimension info if we invisibly show them
// however, it must have a current display style that would benefit from this
return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
}) :
getWidthOrHeight( elem, name, extra );
}
},
set: function( elem, value, extra ) {
var styles = extra && getStyles( elem );
return setPositiveNumber( elem, value, extra ?
augmentWidthOrHeight(
elem,
name,
extra,
jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
styles
) : 0
);
}
};
});
// Support: Android 2.3
jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
function( elem, computed ) {
if ( computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" },
curCSS, [ elem, "marginRight" ] );
}
}
);
// These hooks are used by animate to expand properties
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function( prefix, suffix ) {
jQuery.cssHooks[ prefix + suffix ] = {
expand: function( value ) {
var i = 0,
expanded = {},
// assumes a single number if not a string
parts = typeof value === "string" ? value.split(" ") : [ value ];
for ( ; i < 4; i++ ) {
expanded[ prefix + cssExpand[ i ] + suffix ] =
parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
}
return expanded;
}
};
if ( !rmargin.test( prefix ) ) {
jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
}
});
jQuery.fn.extend({
css: function( name, value ) {
return access( this, function( elem, name, value ) {
var styles, len,
map = {},
i = 0;
if ( jQuery.isArray( name ) ) {
styles = getStyles( elem );
len = name.length;
for ( ; i < len; i++ ) {
map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
}
return map;
}
return value !== undefined ?
jQuery.style( elem, name, value ) :
jQuery.css( elem, name );
}, name, value, arguments.length > 1 );
},
show: function() {
return showHide( this, true );
},
hide: function() {
return showHide( this );
},
toggle: function( state ) {
if ( typeof state === "boolean" ) {
return state ? this.show() : this.hide();
}
return this.each(function() {
if ( isHidden( this ) ) {
jQuery( this ).show();
} else {
jQuery( this ).hide();
}
});
}
});
function Tween( elem, options, prop, end, easing ) {
return new Tween.prototype.init( elem, options, prop, end, easing );
}
jQuery.Tween = Tween;
Tween.prototype = {
constructor: Tween,
init: function( elem, options, prop, end, easing, unit ) {
this.elem = elem;
this.prop = prop;
this.easing = easing || "swing";
this.options = options;
this.start = this.now = this.cur();
this.end = end;
this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
},
cur: function() {
var hooks = Tween.propHooks[ this.prop ];
return hooks && hooks.get ?
hooks.get( this ) :
Tween.propHooks._default.get( this );
},
run: function( percent ) {
var eased,
hooks = Tween.propHooks[ this.prop ];
if ( this.options.duration ) {
this.pos = eased = jQuery.easing[ this.easing ](
percent, this.options.duration * percent, 0, 1, this.options.duration
);
} else {
this.pos = eased = percent;
}
this.now = ( this.end - this.start ) * eased + this.start;
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
if ( hooks && hooks.set ) {
hooks.set( this );
} else {
Tween.propHooks._default.set( this );
}
return this;
}
};
Tween.prototype.init.prototype = Tween.prototype;
Tween.propHooks = {
_default: {
get: function( tween ) {
var result;
if ( tween.elem[ tween.prop ] != null &&
(!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
return tween.elem[ tween.prop ];
}
// passing an empty string as a 3rd parameter to .css will automatically
// attempt a parseFloat and fallback to a string if the parse fails
// so, simple values such as "10px" are parsed to Float.
// complex values such as "rotate(1rad)" are returned as is.
result = jQuery.css( tween.elem, tween.prop, "" );
// Empty strings, null, undefined and "auto" are converted to 0.
return !result || result === "auto" ? 0 : result;
},
set: function( tween ) {
// use step hook for back compat - use cssHook if its there - use .style if its
// available and use plain properties where available
if ( jQuery.fx.step[ tween.prop ] ) {
jQuery.fx.step[ tween.prop ]( tween );
} else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
} else {
tween.elem[ tween.prop ] = tween.now;
}
}
}
};
// Support: IE9
// Panic based approach to setting things on disconnected nodes
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function( tween ) {
if ( tween.elem.nodeType && tween.elem.parentNode ) {
tween.elem[ tween.prop ] = tween.now;
}
}
};
jQuery.easing = {
linear: function( p ) {
return p;
},
swing: function( p ) {
return 0.5 - Math.cos( p * Math.PI ) / 2;
}
};
jQuery.fx = Tween.prototype.init;
// Back Compat <1.8 extension point
jQuery.fx.step = {};
var
fxNow, timerId,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
rrun = /queueHooks$/,
animationPrefilters = [ defaultPrefilter ],
tweeners = {
"*": [ function( prop, value ) {
var tween = this.createTween( prop, value ),
target = tween.cur(),
parts = rfxnum.exec( value ),
unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
// Starting value computation is required for potential unit mismatches
start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
rfxnum.exec( jQuery.css( tween.elem, prop ) ),
scale = 1,
maxIterations = 20;
if ( start && start[ 3 ] !== unit ) {
// Trust units reported by jQuery.css
unit = unit || start[ 3 ];
// Make sure we update the tween properties later on
parts = parts || [];
// Iteratively approximate from a nonzero starting point
start = +target || 1;
do {
// If previous iteration zeroed out, double until we get *something*
// Use a string for doubling factor so we don't accidentally see scale as unchanged below
scale = scale || ".5";
// Adjust and apply
start = start / scale;
jQuery.style( tween.elem, prop, start + unit );
// Update scale, tolerating zero or NaN from tween.cur()
// And breaking the loop if scale is unchanged or perfect, or if we've just had enough
} while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
}
// Update tween properties
if ( parts ) {
start = tween.start = +start || +target || 0;
tween.unit = unit;
// If a +=/-= token was provided, we're doing a relative animation
tween.end = parts[ 1 ] ?
start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+parts[ 2 ];
}
return tween;
} ]
};
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
});
return ( fxNow = jQuery.now() );
}
// Generate parameters to create a standard animation
function genFx( type, includeWidth ) {
var which,
i = 0,
attrs = { height: type };
// if we include width, step value is 1 to do all cssExpand values,
// if we don't include width, step value is 2 to skip over Left and Right
includeWidth = includeWidth ? 1 : 0;
for ( ; i < 4 ; i += 2 - includeWidth ) {
which = cssExpand[ i ];
attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
}
if ( includeWidth ) {
attrs.opacity = attrs.width = type;
}
return attrs;
}
function createTween( value, prop, animation ) {
var tween,
collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
index = 0,
length = collection.length;
for ( ; index < length; index++ ) {
if ( (tween = collection[ index ].call( animation, prop, value )) ) {
// we're done with this property
return tween;
}
}
}
function defaultPrefilter( elem, props, opts ) {
/* jshint validthis: true */
var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
anim = this,
orig = {},
style = elem.style,
hidden = elem.nodeType && isHidden( elem ),
dataShow = data_priv.get( elem, "fxshow" );
// handle queue: false promises
if ( !opts.queue ) {
hooks = jQuery._queueHooks( elem, "fx" );
if ( hooks.unqueued == null ) {
hooks.unqueued = 0;
oldfire = hooks.empty.fire;
hooks.empty.fire = function() {
if ( !hooks.unqueued ) {
oldfire();
}
};
}
hooks.unqueued++;
anim.always(function() {
// doing this makes sure that the complete handler will be called
// before this completes
anim.always(function() {
hooks.unqueued--;
if ( !jQuery.queue( elem, "fx" ).length ) {
hooks.empty.fire();
}
});
});
}
// height/width overflow pass
if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE9-10 do not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
display = jQuery.css( elem, "display" );
// Test default display if display is currently "none"
checkDisplay = display === "none" ?
data_priv.get( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
style.display = "inline-block";
}
}
if ( opts.overflow ) {
style.overflow = "hidden";
anim.always(function() {
style.overflow = opts.overflow[ 0 ];
style.overflowX = opts.overflow[ 1 ];
style.overflowY = opts.overflow[ 2 ];
});
}
// show/hide pass
for ( prop in props ) {
value = props[ prop ];
if ( rfxtypes.exec( value ) ) {
delete props[ prop ];
toggle = toggle || value === "toggle";
if ( value === ( hidden ? "hide" : "show" ) ) {
// If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
hidden = true;
} else {
continue;
}
}
orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
// Any non-fx value stops us from restoring the original display value
} else {
display = undefined;
}
}
if ( !jQuery.isEmptyObject( orig ) ) {
if ( dataShow ) {
if ( "hidden" in dataShow ) {
hidden = dataShow.hidden;
}
} else {
dataShow = data_priv.access( elem, "fxshow", {} );
}
// store state if its toggle - enables .stop().toggle() to "reverse"
if ( toggle ) {
dataShow.hidden = !hidden;
}
if ( hidden ) {
jQuery( elem ).show();
} else {
anim.done(function() {
jQuery( elem ).hide();
});
}
anim.done(function() {
var prop;
data_priv.remove( elem, "fxshow" );
for ( prop in orig ) {
jQuery.style( elem, prop, orig[ prop ] );
}
});
for ( prop in orig ) {
tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
if ( !( prop in dataShow ) ) {
dataShow[ prop ] = tween.start;
if ( hidden ) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
// If this is a noop like .hide().hide(), restore an overwritten display value
} else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
style.display = display;
}
}
function propFilter( props, specialEasing ) {
var index, name, easing, value, hooks;
// camelCase, specialEasing and expand cssHook pass
for ( index in props ) {
name = jQuery.camelCase( index );
easing = specialEasing[ name ];
value = props[ index ];
if ( jQuery.isArray( value ) ) {
easing = value[ 1 ];
value = props[ index ] = value[ 0 ];
}
if ( index !== name ) {
props[ name ] = value;
delete props[ index ];
}
hooks = jQuery.cssHooks[ name ];
if ( hooks && "expand" in hooks ) {
value = hooks.expand( value );
delete props[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'index' from above because we have the correct "name"
for ( index in value ) {
if ( !( index in props ) ) {
props[ index ] = value[ index ];
specialEasing[ index ] = easing;
}
}
} else {
specialEasing[ name ] = easing;
}
}
}
function Animation( elem, properties, options ) {
var result,
stopped,
index = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred().always( function() {
// don't match elem in the :animated selector
delete tick.elem;
}),
tick = function() {
if ( stopped ) {
return false;
}
var currentTime = fxNow || createFxNow(),
remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
// archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
temp = remaining / animation.duration || 0,
percent = 1 - temp,
index = 0,
length = animation.tweens.length;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( percent );
}
deferred.notifyWith( elem, [ animation, percent, remaining ]);
if ( percent < 1 && length ) {
return remaining;
} else {
deferred.resolveWith( elem, [ animation ] );
return false;
}
},
animation = deferred.promise({
elem: elem,
props: jQuery.extend( {}, properties ),
opts: jQuery.extend( true, { specialEasing: {} }, options ),
originalProperties: properties,
originalOptions: options,
startTime: fxNow || createFxNow(),
duration: options.duration,
tweens: [],
createTween: function( prop, end ) {
var tween = jQuery.Tween( elem, animation.opts, prop, end,
animation.opts.specialEasing[ prop ] || animation.opts.easing );
animation.tweens.push( tween );
return tween;
},
stop: function( gotoEnd ) {
var index = 0,
// if we are going to the end, we want to run all the tweens
// otherwise we skip this part
length = gotoEnd ? animation.tweens.length : 0;
if ( stopped ) {
return this;
}
stopped = true;
for ( ; index < length ; index++ ) {
animation.tweens[ index ].run( 1 );
}
// resolve when we played the last frame
// otherwise, reject
if ( gotoEnd ) {
deferred.resolveWith( elem, [ animation, gotoEnd ] );
} else {
deferred.rejectWith( elem, [ animation, gotoEnd ] );
}
return this;
}
}),
props = animation.props;
propFilter( props, animation.opts.specialEasing );
for ( ; index < length ; index++ ) {
result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
if ( result ) {
return result;
}
}
jQuery.map( props, createTween, animation );
if ( jQuery.isFunction( animation.opts.start ) ) {
animation.opts.start.call( elem, animation );
}
jQuery.fx.timer(
jQuery.extend( tick, {
elem: elem,
anim: animation,
queue: animation.opts.queue
})
);
// attach callbacks from options
return animation.progress( animation.opts.progress )
.done( animation.opts.done, animation.opts.complete )
.fail( animation.opts.fail )
.always( animation.opts.always );
}
jQuery.Animation = jQuery.extend( Animation, {
tweener: function( props, callback ) {
if ( jQuery.isFunction( props ) ) {
callback = props;
props = [ "*" ];
} else {
props = props.split(" ");
}
var prop,
index = 0,
length = props.length;
for ( ; index < length ; index++ ) {
prop = props[ index ];
tweeners[ prop ] = tweeners[ prop ] || [];
tweeners[ prop ].unshift( callback );
}
},
prefilter: function( callback, prepend ) {
if ( prepend ) {
animationPrefilters.unshift( callback );
} else {
animationPrefilters.push( callback );
}
}
});
jQuery.speed = function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function() {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
}
};
return opt;
};
jQuery.fn.extend({
fadeTo: function( speed, to, easing, callback ) {
// show any hidden elements after setting opacity to 0
return this.filter( isHidden ).css( "opacity", 0 ).show()
// animate to the value specified
.end().animate({ opacity: to }, speed, easing, callback );
},
animate: function( prop, speed, easing, callback ) {
var empty = jQuery.isEmptyObject( prop ),
optall = jQuery.speed( speed, easing, callback ),
doAnimation = function() {
// Operate on a copy of prop so per-property easing won't be lost
var anim = Animation( this, jQuery.extend( {}, prop ), optall );
// Empty animations, or finishing resolves immediately
if ( empty || data_priv.get( this, "finish" ) ) {
anim.stop( true );
}
};
doAnimation.finish = doAnimation;
return empty || optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
var stopQueue = function( hooks ) {
var stop = hooks.stop;
delete hooks.stop;
stop( gotoEnd );
};
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var dequeue = true,
index = type != null && type + "queueHooks",
timers = jQuery.timers,
data = data_priv.get( this );
if ( index ) {
if ( data[ index ] && data[ index ].stop ) {
stopQueue( data[ index ] );
}
} else {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
stopQueue( data[ index ] );
}
}
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
timers[ index ].anim.stop( gotoEnd );
dequeue = false;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( dequeue || !gotoEnd ) {
jQuery.dequeue( this, type );
}
});
},
finish: function( type ) {
if ( type !== false ) {
type = type || "fx";
}
return this.each(function() {
var index,
data = data_priv.get( this ),
queue = data[ type + "queue" ],
hooks = data[ type + "queueHooks" ],
timers = jQuery.timers,
length = queue ? queue.length : 0;
// enable finishing flag on private data
data.finish = true;
// empty the queue first
jQuery.queue( this, type, [] );
if ( hooks && hooks.stop ) {
hooks.stop.call( this, true );
}
// look for any active animations, and finish them
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
timers[ index ].anim.stop( true );
timers.splice( index, 1 );
}
}
// look for any animations in the old queue and finish them
for ( index = 0; index < length; index++ ) {
if ( queue[ index ] && queue[ index ].finish ) {
queue[ index ].finish.call( this );
}
}
// turn off finishing flag
delete data.finish;
});
}
});
jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
var cssFn = jQuery.fn[ name ];
jQuery.fn[ name ] = function( speed, easing, callback ) {
return speed == null || typeof speed === "boolean" ?
cssFn.apply( this, arguments ) :
this.animate( genFx( name, true ), speed, easing, callback );
};
});
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx("show"),
slideUp: genFx("hide"),
slideToggle: genFx("toggle"),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.timers = [];
jQuery.fx.tick = function() {
var timer,
i = 0,
timers = jQuery.timers;
fxNow = jQuery.now();
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
fxNow = undefined;
};
jQuery.fx.timer = function( timer ) {
jQuery.timers.push( timer );
if ( timer() ) {
jQuery.fx.start();
} else {
jQuery.timers.pop();
}
};
jQuery.fx.interval = 13;
jQuery.fx.start = function() {
if ( !timerId ) {
timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
}
};
jQuery.fx.stop = function() {
clearInterval( timerId );
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
// Default speed
_default: 400
};
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
jQuery.fn.delay = function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
};
(function() {
var input = document.createElement( "input" ),
select = document.createElement( "select" ),
opt = select.appendChild( document.createElement( "option" ) );
input.type = "checkbox";
// Support: iOS 5.1, Android 4.x, Android 2.3
// Check the default checkbox/radio value ("" on old WebKit; "on" elsewhere)
support.checkOn = input.value !== "";
// Must access the parent to make an option select properly
// Support: IE9, IE10
support.optSelected = opt.selected;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Check if an input maintains its value after becoming a radio
// Support: IE9, IE10
input = document.createElement( "input" );
input.value = "t";
input.type = "radio";
support.radioValue = input.value === "t";
})();
var nodeHook, boolHook,
attrHandle = jQuery.expr.attrHandle;
jQuery.fn.extend({
attr: function( name, value ) {
return access( this, jQuery.attr, name, value, arguments.length > 1 );
},
removeAttr: function( name ) {
return this.each(function() {
jQuery.removeAttr( this, name );
});
}
});
jQuery.extend({
attr: function( elem, name, value ) {
var hooks, ret,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === strundefined ) {
return jQuery.prop( elem, name, value );
}
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] ||
( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
} else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, value + "" );
return value;
}
} else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = jQuery.find.attr( elem, name );
// Non-existent attributes return null, we normalize to undefined
return ret == null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var name, propName,
i = 0,
attrNames = value && value.match( rnotwhite );
if ( attrNames && elem.nodeType === 1 ) {
while ( (name = attrNames[i++]) ) {
propName = jQuery.propFix[ name ] || name;
// Boolean attributes get special treatment (#10870)
if ( jQuery.expr.match.bool.test( name ) ) {
// Set corresponding property to false
elem[ propName ] = false;
}
elem.removeAttribute( name );
}
}
},
attrHooks: {
type: {
set: function( elem, value ) {
if ( !support.radioValue && value === "radio" &&
jQuery.nodeName( elem, "input" ) ) {
// Setting the type on a radio button after the value resets the value in IE6-9
// Reset value to default in case type is set after value during creation
var val = elem.value;
elem.setAttribute( "type", value );
if ( val ) {
elem.value = val;
}
return value;
}
}
}
}
});
// Hooks for boolean attributes
boolHook = {
set: function( elem, value, name ) {
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
elem.setAttribute( name, name );
}
return name;
}
};
jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
var getter = attrHandle[ name ] || jQuery.find.attr;
attrHandle[ name ] = function( elem, name, isXML ) {
var ret, handle;
if ( !isXML ) {
// Avoid an infinite loop by temporarily removing this function from the getter
handle = attrHandle[ name ];
attrHandle[ name ] = ret;
ret = getter( elem, name, isXML ) != null ?
name.toLowerCase() :
null;
attrHandle[ name ] = handle;
}
return ret;
};
});
var rfocusable = /^(?:input|select|textarea|button)$/i;
jQuery.fn.extend({
prop: function( name, value ) {
return access( this, jQuery.prop, name, value, arguments.length > 1 );
},
removeProp: function( name ) {
return this.each(function() {
delete this[ jQuery.propFix[ name ] || name ];
});
}
});
jQuery.extend({
propFix: {
"for": "htmlFor",
"class": "className"
},
prop: function( elem, name, value ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set properties on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
if ( notxml ) {
// Fix name and attach hooks
name = jQuery.propFix[ name ] || name;
hooks = jQuery.propHooks[ name ];
}
if ( value !== undefined ) {
return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
ret :
( elem[ name ] = value );
} else {
return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
ret :
elem[ name ];
}
},
propHooks: {
tabIndex: {
get: function( elem ) {
return elem.hasAttribute( "tabindex" ) || rfocusable.test( elem.nodeName ) || elem.href ?
elem.tabIndex :
-1;
}
}
}
});
// Support: IE9+
// Selectedness for an option in an optgroup can be inaccurate
if ( !support.optSelected ) {
jQuery.propHooks.selected = {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent && parent.parentNode ) {
parent.parentNode.selectedIndex;
}
return null;
}
};
}
jQuery.each([
"tabIndex",
"readOnly",
"maxLength",
"cellSpacing",
"cellPadding",
"rowSpan",
"colSpan",
"useMap",
"frameBorder",
"contentEditable"
], function() {
jQuery.propFix[ this.toLowerCase() ] = this;
});
var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
addClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).addClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
// The disjunction here is for better compressibility (see removeClass)
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
" "
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
cur += clazz + " ";
}
}
// only assign if different to avoid unneeded rendering.
finalValue = jQuery.trim( cur );
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
removeClass: function( value ) {
var classes, elem, cur, clazz, j, finalValue,
proceed = arguments.length === 0 || typeof value === "string" && value,
i = 0,
len = this.length;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call( this, j, this.className ) );
});
}
if ( proceed ) {
classes = ( value || "" ).match( rnotwhite ) || [];
for ( ; i < len; i++ ) {
elem = this[ i ];
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && ( elem.className ?
( " " + elem.className + " " ).replace( rclass, " " ) :
""
);
if ( cur ) {
j = 0;
while ( (clazz = classes[j++]) ) {
// Remove *all* instances
while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
cur = cur.replace( " " + clazz + " ", " " );
}
}
// only assign if different to avoid unneeded rendering.
finalValue = value ? jQuery.trim( cur ) : "";
if ( elem.className !== finalValue ) {
elem.className = finalValue;
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value;
if ( typeof stateVal === "boolean" && type === "string" ) {
return stateVal ? this.addClass( value ) : this.removeClass( value );
}
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
classNames = value.match( rnotwhite ) || [];
while ( (className = classNames[ i++ ]) ) {
// check each className given, space separated list
if ( self.hasClass( className ) ) {
self.removeClass( className );
} else {
self.addClass( className );
}
}
// Toggle whole class name
} else if ( type === strundefined || type === "boolean" ) {
if ( this.className ) {
// store className if set
data_priv.set( this, "__className__", this.className );
}
// If the element has a class name or if we're passed "false",
// then remove the whole classname (if there was one, the above saved it).
// Otherwise bring back whatever was previously saved (if anything),
// falling back to the empty string if nothing was stored.
this.className = this.className || value === false ? "" : data_priv.get( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
return true;
}
}
return false;
}
});
var rreturn = /\r/g;
jQuery.fn.extend({
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ?
// handle most common string cases
ret.replace(rreturn, "") :
// handle cases where value is null/undef or number
ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction( value );
return this.each(function( i ) {
var val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, jQuery( this ).val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map( val, function( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
// If set returns undefined, fall back to normal setting
if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function( elem ) {
var val = jQuery.find.attr( elem, "value" );
return val != null ?
val :
// Support: IE10-11+
// option.text throws exceptions (#14686, #14858)
jQuery.trim( jQuery.text( elem ) );
}
},
select: {
get: function( elem ) {
var value, option,
options = elem.options,
index = elem.selectedIndex,
one = elem.type === "select-one" || index < 0,
values = one ? null : [],
max = one ? index + 1 : options.length,
i = index < 0 ?
max :
one ? index : 0;
// Loop through all the selected options
for ( ; i < max; i++ ) {
option = options[ i ];
// IE6-9 doesn't update selected after form reset (#2551)
if ( ( option.selected || i === index ) &&
// Don't return options that are disabled or in a disabled optgroup
( support.optDisabled ? !option.disabled : option.getAttribute( "disabled" ) === null ) &&
( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
},
set: function( elem, value ) {
var optionSet, option,
options = elem.options,
values = jQuery.makeArray( value ),
i = options.length;
while ( i-- ) {
option = options[ i ];
if ( (option.selected = jQuery.inArray( option.value, values ) >= 0) ) {
optionSet = true;
}
}
// force browsers to behave consistently when non-matching value is set
if ( !optionSet ) {
elem.selectedIndex = -1;
}
return values;
}
}
}
});
// Radios and checkboxes getter/setter
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
};
if ( !support.checkOn ) {
jQuery.valHooks[ this ].get = function( elem ) {
// Support: Webkit
// "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
};
}
});
// Return jQuery for attributes-only inclusion
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
});
jQuery.fn.extend({
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
}
});
var nonce = jQuery.now();
var rquery = (/\?/);
// Support: Android 2.3
// Workaround failure to string-cast null input
jQuery.parseJSON = function( data ) {
return JSON.parse( data + "" );
};
// Cross-browser xml parsing
jQuery.parseXML = function( data ) {
var xml, tmp;
if ( !data || typeof data !== "string" ) {
return null;
}
// Support: IE9
try {
tmp = new DOMParser();
xml = tmp.parseFromString( data, "text/xml" );
} catch ( e ) {
xml = undefined;
}
if ( !xml || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
};
var
// Document location
ajaxLocParts,
ajaxLocation,
rhash = /#.*$/,
rts = /([?&])_=[^&]*/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)$/mg,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = "*/".concat("*");
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType,
i = 0,
dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
if ( jQuery.isFunction( func ) ) {
// For each dataType in the dataTypeExpression
while ( (dataType = dataTypes[i++]) ) {
// Prepend if requested
if ( dataType[0] === "+" ) {
dataType = dataType.slice( 1 ) || "*";
(structure[ dataType ] = structure[ dataType ] || []).unshift( func );
// Otherwise append
} else {
(structure[ dataType ] = structure[ dataType ] || []).push( func );
}
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
var inspected = {},
seekingTransport = ( structure === transports );
function inspect( dataType ) {
var selected;
inspected[ dataType ] = true;
jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
options.dataTypes.unshift( dataTypeOrTransport );
inspect( dataTypeOrTransport );
return false;
} else if ( seekingTransport ) {
return !( selected = dataTypeOrTransport );
}
});
return selected;
}
return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
return target;
}
/* Handles responses to an ajax request:
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var ct, type, finalDataType, firstDataType,
contents = s.contents,
dataTypes = s.dataTypes;
// Remove auto dataType and get content-type in the process
while ( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
/* Chain conversions given the request and the original response
* Also sets the responseXXX fields on the jqXHR instance
*/
function ajaxConvert( s, response, jqXHR, isSuccess ) {
var conv2, current, conv, tmp, prev,
converters = {},
// Work with a copy of dataTypes in case we need to modify it for conversion
dataTypes = s.dataTypes.slice();
// Create converters map with lowercased keys
if ( dataTypes[ 1 ] ) {
for ( conv in s.converters ) {
converters[ conv.toLowerCase() ] = s.converters[ conv ];
}
}
current = dataTypes.shift();
// Convert to each sequential dataType
while ( current ) {
if ( s.responseFields[ current ] ) {
jqXHR[ s.responseFields[ current ] ] = response;
}
// Apply the dataFilter if provided
if ( !prev && isSuccess && s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
prev = current;
current = dataTypes.shift();
if ( current ) {
// There's only work to do if current dataType is non-auto
if ( current === "*" ) {
current = prev;
// Convert response if prev dataType is non-auto and differs from current
} else if ( prev !== "*" && prev !== current ) {
// Seek a direct converter
conv = converters[ prev + " " + current ] || converters[ "* " + current ];
// If none found, seek a pair
if ( !conv ) {
for ( conv2 in converters ) {
// If conv2 outputs current
tmp = conv2.split( " " );
if ( tmp[ 1 ] === current ) {
// If prev can be converted to accepted input
conv = converters[ prev + " " + tmp[ 0 ] ] ||
converters[ "* " + tmp[ 0 ] ];
if ( conv ) {
// Condense equivalence converters
if ( conv === true ) {
conv = converters[ conv2 ];
// Otherwise, insert the intermediate dataType
} else if ( converters[ conv2 ] !== true ) {
current = tmp[ 0 ];
dataTypes.unshift( tmp[ 1 ] );
}
break;
}
}
}
}
// Apply converter (if not an equivalence)
if ( conv !== true ) {
// Unless errors are allowed to bubble, catch and return them
if ( conv && s[ "throws" ] ) {
response = conv( response );
} else {
try {
response = conv( response );
} catch ( e ) {
return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
}
}
}
}
}
}
return { state: "success", data: response };
}
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajaxSettings: {
url: ajaxLocation,
type: "GET",
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
processData: true,
async: true,
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
throws: false,
traditional: false,
headers: {},
*/
accepts: {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText",
json: "responseJSON"
},
// Data converters
// Keys separate source (or catchall "*") and destination types with a single space
converters: {
// Convert anything to text
"* text": String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
url: true,
context: true
}
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
return settings ?
// Building a settings object
ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
// Extending ajaxSettings
ajaxExtend( jQuery.ajaxSettings, target );
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var transport,
// URL without anti-cache param
cacheURL,
// Response headers
responseHeadersString,
responseHeaders,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events is callbackContext if it is a DOM node or jQuery collection
globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
jQuery( callbackContext ) :
jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// The jqXHR state
state = 0,
// Default abort message
strAbort = "canceled",
// Fake xhr
jqXHR = {
readyState: 0,
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while ( (match = rheaders.exec( responseHeadersString )) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match == null ? null : match;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Caches the header
setRequestHeader: function( name, value ) {
var lname = name.toLowerCase();
if ( !state ) {
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Status-dependent callbacks
statusCode: function( map ) {
var code;
if ( map ) {
if ( state < 2 ) {
for ( code in map ) {
// Lazy-add the new callback in a way that preserves old ones
statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
}
} else {
// Execute the appropriate callbacks
jqXHR.always( map[ jqXHR.status ] );
}
}
return this;
},
// Cancel the request
abort: function( statusText ) {
var finalText = statusText || strAbort;
if ( transport ) {
transport.abort( finalText );
}
done( 0, finalText );
return this;
}
};
// Attach deferreds
deferred.promise( jqXHR ).complete = completeDeferred.add;
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (prefilters might expect it)
// Handle falsy url in the settings object (#10093: consistency with old signature)
// We also use the url parameter if available
s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" )
.replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Alias method option to type as per ticket #12004
s.type = options.method || options.type || s.method || s.type;
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
// A cross-domain request is in order when we have a protocol:host:port mismatch
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return jqXHR;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger("ajaxStart");
}
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Save the URL in case we're toying with the If-Modified-Since
// and/or If-None-Match header later on
cacheURL = s.url;
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Add anti-cache in url if needed
if ( s.cache === false ) {
s.url = rts.test( cacheURL ) ?
// If there is already a '_' parameter, set its value
cacheURL.replace( rts, "$1_=" + nonce++ ) :
// Otherwise add one to the end
cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
}
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
}
if ( jQuery.etag[ cacheURL ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already and return
return jqXHR.abort();
}
// aborting is no longer a cancellation
strAbort = "abort";
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch ( e ) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
// Callback for when everything is done
function done( status, nativeStatusText, responses, headers ) {
var isSuccess, success, error, response, modified,
statusText = nativeStatusText;
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
// Determine if successful
isSuccess = status >= 200 && status < 300 || status === 304;
// Get response data
if ( responses ) {
response = ajaxHandleResponses( s, jqXHR, responses );
}
// Convert no matter what (that way responseXXX fields are always set)
response = ajaxConvert( s, response, jqXHR, isSuccess );
// If successful, handle type chaining
if ( isSuccess ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
modified = jqXHR.getResponseHeader("Last-Modified");
if ( modified ) {
jQuery.lastModified[ cacheURL ] = modified;
}
modified = jqXHR.getResponseHeader("etag");
if ( modified ) {
jQuery.etag[ cacheURL ] = modified;
}
}
// if no content
if ( status === 204 || s.type === "HEAD" ) {
statusText = "nocontent";
// if not modified
} else if ( status === 304 ) {
statusText = "notmodified";
// If we have data, let's convert it
} else {
statusText = response.state;
success = response.data;
error = response.error;
isSuccess = !error;
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( status || !statusText ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = ( nativeStatusText || statusText ) + "";
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger("ajaxStop");
}
}
}
return jqXHR;
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
}
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
url: url,
type: method,
dataType: type,
data: data,
success: callback
});
};
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
jQuery.fn[ type ] = function( fn ) {
return this.on( type, fn );
};
});
jQuery._evalUrl = function( url ) {
return jQuery.ajax({
url: url,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
};
jQuery.fn.extend({
wrapAll: function( html ) {
var wrap;
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapAll( html.call(this, i) );
});
}
if ( this[ 0 ] ) {
// The elements to wrap the target around
wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
if ( this[ 0 ].parentNode ) {
wrap.insertBefore( this[ 0 ] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstElementChild ) {
elem = elem.firstElementChild;
}
return elem;
}).append( this );
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function( i ) {
jQuery( this ).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ),
contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
var isFunction = jQuery.isFunction( html );
return this.each(function( i ) {
jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
}
});
jQuery.expr.filters.hidden = function( elem ) {
// Support: Opera <= 12.12
// Opera reports offsetWidths and offsetHeights less than zero on some elements
return elem.offsetWidth <= 0 && elem.offsetHeight <= 0;
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
rsubmittable = /^(?:input|select|textarea|keygen)/i;
function buildParams( prefix, obj, traditional, add ) {
var name;
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// Item is non-scalar (array or object), encode its numeric index.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// Serialize an array of form elements or a set of
// key/values into a query string
jQuery.param = function( a, traditional ) {
var prefix,
s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
};
jQuery.fn.extend({
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function() {
// Can add propHook for "elements" to filter or add form elements
var elements = jQuery.prop( this, "elements" );
return elements ? jQuery.makeArray( elements ) : this;
})
.filter(function() {
var type = this.type;
// Use .is( ":disabled" ) so that fieldset[disabled] works
return this.name && !jQuery( this ).is( ":disabled" ) &&
rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
( this.checked || !rcheckableType.test( type ) );
})
.map(function( i, elem ) {
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val ) {
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
jQuery.ajaxSettings.xhr = function() {
try {
return new XMLHttpRequest();
} catch( e ) {}
};
var xhrId = 0,
xhrCallbacks = {},
xhrSuccessStatus = {
// file protocol always yields status code 0, assume 200
0: 200,
// Support: IE9
// #1450: sometimes IE returns 1223 when it should be 204
1223: 204
},
xhrSupported = jQuery.ajaxSettings.xhr();
// Support: IE9
// Open requests must be manually aborted on unload (#5280)
if ( window.ActiveXObject ) {
jQuery( window ).on( "unload", function() {
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]();
}
});
}
support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
support.ajax = xhrSupported = !!xhrSupported;
jQuery.ajaxTransport(function( options ) {
var callback;
// Cross domain only allowed if supported through XMLHttpRequest
if ( support.cors || xhrSupported && !options.crossDomain ) {
return {
send: function( headers, complete ) {
var i,
xhr = options.xhr(),
id = ++xhrId;
xhr.open( options.type, options.url, options.async, options.username, options.password );
// Apply custom fields if provided
if ( options.xhrFields ) {
for ( i in options.xhrFields ) {
xhr[ i ] = options.xhrFields[ i ];
}
}
// Override mime type if needed
if ( options.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( options.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !options.crossDomain && !headers["X-Requested-With"] ) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
// Set headers
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
// Callback
callback = function( type ) {
return function() {
if ( callback ) {
delete xhrCallbacks[ id ];
callback = xhr.onload = xhr.onerror = null;
if ( type === "abort" ) {
xhr.abort();
} else if ( type === "error" ) {
complete(
// file: protocol always yields status 0; see #8605, #14207
xhr.status,
xhr.statusText
);
} else {
complete(
xhrSuccessStatus[ xhr.status ] || xhr.status,
xhr.statusText,
// Support: IE9
// Accessing binary-data responseText throws an exception
// (#11426)
typeof xhr.responseText === "string" ? {
text: xhr.responseText
} : undefined,
xhr.getAllResponseHeaders()
);
}
}
};
};
// Listen to events
xhr.onload = callback();
xhr.onerror = callback("error");
// Create the abort callback
callback = xhrCallbacks[ id ] = callback("abort");
try {
// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );
} catch ( e ) {
// #14683: Only rethrow if this hasn't been notified as an error yet
if ( callback ) {
throw e;
}
}
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /(?:java|ecma)script/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and crossDomain
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function( s ) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script, callback;
return {
send: function( _, complete ) {
script = jQuery("<script>").prop({
async: true,
charset: s.scriptCharset,
src: s.url
}).on(
"load error",
callback = function( evt ) {
script.remove();
callback = null;
if ( evt ) {
complete( evt.type === "error" ? 404 : 200, evt.type );
}
}
);
document.head.appendChild( script[ 0 ] );
},
abort: function() {
if ( callback ) {
callback();
}
}
};
}
});
var oldCallbacks = [],
rjsonp = /(=)\?(?=&|$)|\?\?/;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
this[ callback ] = true;
return callback;
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var callbackName, overwritten, responseContainer,
jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
"url" :
typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
);
// Handle iff the expected data type is "jsonp" or we have a parameter to set
if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
// Get callback name, remembering preexisting value associated with it
callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
s.jsonpCallback() :
s.jsonpCallback;
// Insert callback into url or form data
if ( jsonProp ) {
s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
} else if ( s.jsonp !== false ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
}
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( callbackName + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Install callback
overwritten = window[ callbackName ];
window[ callbackName ] = function() {
responseContainer = arguments;
};
// Clean-up function (fires after converters)
jqXHR.always(function() {
// Restore preexisting value
window[ callbackName ] = overwritten;
// Save back as free
if ( s[ callbackName ] ) {
// make sure that re-using the options doesn't screw things around
s.jsonpCallback = originalSettings.jsonpCallback;
// save the callback name for future use
oldCallbacks.push( callbackName );
}
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( overwritten ) ) {
overwritten( responseContainer[ 0 ] );
}
responseContainer = overwritten = undefined;
});
// Delegate to script
return "script";
}
});
// data: string of html
// context (optional): If specified, the fragment will be created in this context, defaults to document
// keepScripts (optional): If true, will include scripts passed in the html string
jQuery.parseHTML = function( data, context, keepScripts ) {
if ( !data || typeof data !== "string" ) {
return null;
}
if ( typeof context === "boolean" ) {
keepScripts = context;
context = false;
}
context = context || document;
var parsed = rsingleTag.exec( data ),
scripts = !keepScripts && [];
// Single tag
if ( parsed ) {
return [ context.createElement( parsed[1] ) ];
}
parsed = jQuery.buildFragment( [ data ], context, scripts );
if ( scripts && scripts.length ) {
jQuery( scripts ).remove();
}
return jQuery.merge( [], parsed.childNodes );
};
// Keep a copy of the old load method
var _load = jQuery.fn.load;
/**
* Load a url into a page
*/
jQuery.fn.load = function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
}
var selector, type, response,
self = this,
off = url.indexOf(" ");
if ( off >= 0 ) {
selector = jQuery.trim( url.slice( off ) );
url = url.slice( 0, off );
}
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( params && typeof params === "object" ) {
type = "POST";
}
// If we have elements to modify, make the request
if ( self.length > 0 ) {
jQuery.ajax({
url: url,
// if "type" variable is undefined, then "GET" method will be used
type: type,
dataType: "html",
data: params
}).done(function( responseText ) {
// Save response for use in complete callback
response = arguments;
self.html( selector ?
// If a selector was specified, locate the right elements in a dummy div
// Exclude scripts to avoid IE 'Permission Denied' errors
jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
// Otherwise use the full result
responseText );
}).complete( callback && function( jqXHR, status ) {
self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
});
}
return this;
};
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
var docElem = window.document.documentElement;
/**
* Gets a window from an element
*/
function getWindow( elem ) {
return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 && elem.defaultView;
}
jQuery.offset = {
setOffset: function( elem, options, i ) {
var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
position = jQuery.css( elem, "position" ),
curElem = jQuery( elem ),
props = {};
// Set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
curOffset = curElem.offset();
curCSSTop = jQuery.css( elem, "top" );
curCSSLeft = jQuery.css( elem, "left" );
calculatePosition = ( position === "absolute" || position === "fixed" ) &&
( curCSSTop + curCSSLeft ).indexOf("auto") > -1;
// Need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
offset: function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var docElem, win,
elem = this[ 0 ],
box = { top: 0, left: 0 },
doc = elem && elem.ownerDocument;
if ( !doc ) {
return;
}
docElem = doc.documentElement;
// Make sure it's not a disconnected DOM node
if ( !jQuery.contains( docElem, elem ) ) {
return box;
}
// If we don't have gBCR, just use 0,0 rather than error
// BlackBerry 5, iOS 3 (original iPhone)
if ( typeof elem.getBoundingClientRect !== strundefined ) {
box = elem.getBoundingClientRect();
}
win = getWindow( doc );
return {
top: box.top + win.pageYOffset - docElem.clientTop,
left: box.left + win.pageXOffset - docElem.clientLeft
};
},
position: function() {
if ( !this[ 0 ] ) {
return;
}
var offsetParent, offset,
elem = this[ 0 ],
parentOffset = { top: 0, left: 0 };
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
if ( jQuery.css( elem, "position" ) === "fixed" ) {
// We assume that getBoundingClientRect is available when computed position is fixed
offset = elem.getBoundingClientRect();
} else {
// Get *real* offsetParent
offsetParent = this.offsetParent();
// Get correct offsets
offset = this.offset();
if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
parentOffset = offsetParent.offset();
}
// Add offsetParent borders
parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
}
// Subtract parent offsets and element margins
return {
top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true )
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || docElem;
while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent || docElem;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
var top = "pageYOffset" === prop;
jQuery.fn[ method ] = function( val ) {
return access( this, function( elem, method, val ) {
var win = getWindow( elem );
if ( val === undefined ) {
return win ? win[ prop ] : elem[ method ];
}
if ( win ) {
win.scrollTo(
!top ? val : window.pageXOffset,
top ? val : window.pageYOffset
);
} else {
elem[ method ] = val;
}
}, method, val, arguments.length, null );
};
});
// Add the top/left cssHooks using jQuery.fn.position
// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
// getComputedStyle returns percent when specified for top/left/bottom/right
// rather than make the css module depend on the offset module, we just check for it here
jQuery.each( [ "top", "left" ], function( i, prop ) {
jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
function( elem, computed ) {
if ( computed ) {
computed = curCSS( elem, prop );
// if curCSS returns percentage, fallback to offset
return rnumnonpx.test( computed ) ?
jQuery( elem ).position()[ prop ] + "px" :
computed;
}
}
);
});
// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
// margin is only for outerHeight, outerWidth
jQuery.fn[ funcName ] = function( margin, value ) {
var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
return access( this, function( elem, type, value ) {
var doc;
if ( jQuery.isWindow( elem ) ) {
// As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
// isn't a whole lot we can do. See pull request at this URL for discussion:
// https://github.com/jquery/jquery/pull/764
return elem.document.documentElement[ "client" + name ];
}
// Get document width or height
if ( elem.nodeType === 9 ) {
doc = elem.documentElement;
// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height],
// whichever is greatest
return Math.max(
elem.body[ "scroll" + name ], doc[ "scroll" + name ],
elem.body[ "offset" + name ], doc[ "offset" + name ],
doc[ "client" + name ]
);
}
return value === undefined ?
// Get width or height on the element, requesting but not forcing parseFloat
jQuery.css( elem, type, extra ) :
// Set width or height on the element
jQuery.style( elem, type, value, extra );
}, type, chainable ? margin : undefined, chainable, null );
};
});
});
// The number of elements contained in the matched element set
jQuery.fn.size = function() {
return this.length;
};
jQuery.fn.andSelf = jQuery.fn.addBack;
// Register as a named AMD module, since jQuery can be concatenated with other
// files that may use define, but not via a proper concatenation script that
// understands anonymous AMD modules. A named AMD is safest and most robust
// way to register. Lowercase jquery is used because AMD module names are
// derived from file names, and jQuery is normally delivered in a lowercase
// file name. Do this after creating the global so that if an AMD module wants
// to call noConflict to hide this version of jQuery, it will work.
// Note that for maximum portability, libraries that are not jQuery should
// declare themselves as anonymous modules, and avoid setting a global if an
// AMD loader is present. jQuery is a special case. For more information, see
// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
if ( typeof define === "function" && define.amd ) {
define( "jquery", [], function() {
return jQuery;
});
}
var
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$;
jQuery.noConflict = function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
};
// Expose jQuery and $ identifiers, even in
// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
// and CommonJS for browser emulators (#13566)
if ( typeof noGlobal === strundefined ) {
window.jQuery = window.$ = jQuery;
}
return jQuery;
}));
| dhenson02/cdnjs | ajax/libs/jquery/2.1.1/jquery.js | JavaScript | mit | 247,351 |
(function(a){if(typeof exports=="object"&&typeof module=="object"){a(require("../../lib/codemirror"))}else{if(typeof define=="function"&&define.amd){define(["../../lib/codemirror"],a)}else{a(CodeMirror)}}})(function(f){var e={pairs:"()[]{}''\"\"",triples:"",explode:"[]{}"};var o=f.Pos;f.defineOption("autoCloseBrackets",false,function(i,s,r){if(r&&r!=f.Init){i.removeKeyMap(k);i.state.closeBrackets=null}if(s){i.state.closeBrackets=s;i.addKeyMap(k)}});function a(r,i){if(i=="pairs"&&typeof r=="string"){return r}if(typeof r=="object"&&r[i]!=null){return r[i]}return e[i]}var l=e.pairs+"`";var k={Backspace:d,Enter:b};for(var j=0;j<l.length;j++){k["'"+l.charAt(j)+"'"]=q(l.charAt(j))}function q(i){return function(r){return p(r,i)}}function n(i){var s=i.state.closeBrackets;if(!s){return null}var r=i.getModeAt(i.getCursor());return r.closeBrackets||s}function d(r){var t=n(r);if(!t||r.getOption("disableInput")){return f.Pass}var w=a(t,"pairs");var s=r.listSelections();for(var u=0;u<s.length;u++){if(!s[u].empty()){return f.Pass}var v=h(r,s[u].head);if(!v||w.indexOf(v)%2!=0){return f.Pass}}for(var u=s.length-1;u>=0;u--){var x=s[u].head;r.replaceRange("",o(x.line,x.ch-1),o(x.line,x.ch+1))}}function b(r){var t=n(r);var v=t&&a(t,"explode");if(!v||r.getOption("disableInput")){return f.Pass}var s=r.listSelections();for(var u=0;u<s.length;u++){if(!s[u].empty()){return f.Pass}var w=h(r,s[u].head);if(!w||v.indexOf(w)%2!=0){return f.Pass}}r.operation(function(){r.replaceSelection("\n\n",null);r.execCommand("goCharLeft");s=r.listSelections();for(var y=0;y<s.length;y++){var x=s[y].head.line;r.indentLine(x,null,true);r.indentLine(x+1,null,true)}})}function g(r){var i=f.cmpPos(r.anchor,r.head)>0;return{anchor:new o(r.anchor.line,r.anchor.ch+(i?-1:1)),head:new o(r.head.line,r.head.ch+(i?1:-1))}}function p(E,r){var z=n(E);if(!z||E.getOption("disableInput")){return f.Pass}var t=a(z,"pairs");var C=t.indexOf(r);if(C==-1){return f.Pass}var H=a(z,"triples");var D=t.charAt(C+1)==r;var s=E.listSelections();var u=C%2==0;var A,y;for(var w=0;w<s.length;w++){var x=s[w],G=x.head,B;var y=E.getRange(G,o(G.line,G.ch+1));if(u&&!x.empty()){B="surround"}else{if((D||!u)&&y==r){if(H.indexOf(r)>=0&&E.getRange(G,o(G.line,G.ch+3))==r+r+r){B="skipThree"}else{B="skip"}}else{if(D&&G.ch>1&&H.indexOf(r)>=0&&E.getRange(o(G.line,G.ch-2),G)==r+r&&(G.ch<=2||E.getRange(o(G.line,G.ch-3),o(G.line,G.ch-2))!=r)){B="addFour"}else{if(D){if(!f.isWordChar(y)&&m(E,G,r)){B="both"}else{return f.Pass}}else{if(u&&(E.getLine(G.line).length==G.ch||c(y,t)||/\s/.test(y))){B="both"}else{return f.Pass}}}}}if(!A){A=B}else{if(A!=B){return f.Pass}}}var v=C%2?t.charAt(C-1):r;var F=C%2?r:t.charAt(C+1);E.operation(function(){if(A=="skip"){E.execCommand("goCharRight")}else{if(A=="skipThree"){for(var J=0;J<3;J++){E.execCommand("goCharRight")}}else{if(A=="surround"){var I=E.getSelections();for(var J=0;J<I.length;J++){I[J]=v+I[J]+F}E.replaceSelections(I,"around");I=E.listSelections().slice();for(var J=0;J<I.length;J++){I[J]=g(I[J])}E.setSelections(I)}else{if(A=="both"){E.replaceSelection(v+F,null);E.triggerElectric(v+F);E.execCommand("goCharLeft")}else{if(A=="addFour"){E.replaceSelection(v+v+v+v,"before");E.execCommand("goCharRight")}}}}}})}function c(i,r){var s=r.lastIndexOf(i);return s>-1&&s%2==1}function h(i,s){var r=i.getRange(o(s.line,s.ch-1),o(s.line,s.ch+1));return r.length==2?r:null}function m(i,w,u){var r=i.getLine(w.line);var t=i.getTokenAt(w);if(/\bstring2?\b/.test(t.type)){return false}var v=new f.StringStream(r.slice(0,w.ch)+u+r.slice(w.ch),4);v.pos=v.start=t.start;for(;;){var s=i.getMode().token(v,t.state);if(v.pos>=w.ch+1){return/\bstring2?\b/.test(s)}v.start=v.pos}}}); | maruilian11/cdnjs | ajax/libs/codemirror/5.7.0/addon/edit/closebrackets.min.js | JavaScript | mit | 3,662 |
/*
* Opera (.oex) Extensions Compatibility Layer - operaextensions_background.js
* https://github.com/operasoftware/operaextensions.js (ver: 0.91)
* Copyright (c) 2013 Opera Software ASA
* License: The MIT License (https://github.com/operasoftware/operaextensions.js/blob/master/LICENSE)
*/
!(function( global ) {
var Opera = function() {};
Opera.prototype.REVISION = '1';
Opera.prototype.version = function() {
return this.REVISION;
};
Opera.prototype.buildNumber = function() {
return this.REVISION;
};
Opera.prototype.postError = function( str ) {
console.log( str );
};
var opr, isOEX = false;
try {
if(opera) {
opr = opera;
isOEX = true;
} else {
opr = new Opera();
}
} catch(e) {
opr = new Opera();
}
var manifest = null;
try {
manifest = chrome.app.getDetails(); // null in injected scripts / popups.
} catch(e) {} // Throws in Opera 12.15.
global.navigator.browserLanguage = global.navigator.language; //Opera defines both, some extensions use the former
var isReady = false;
var _delayedExecuteEvents = [
// Example:
// { 'target': opera.extension, 'methodName': 'message', 'args': event }
];
// Pick the right base URL for new tab generation
var newTab_BaseURL = 'data:text/html,<!DOCTYPE html><!--tab_%s--><title>Loading...</title><script>history.forward()</script>';
function addDelayedEvent(target, methodName, args) {
if(isReady) {
target[methodName].apply(target, args);
} else {
_delayedExecuteEvents.push({
"target": target,
"methodName": methodName,
"args": args
});
}
};
// Used to trigger opera.isReady() functions
var deferredComponentsLoadStatus = {
'WINTABS_LOADED': false,
'SPEEDDIAL_LOADED': false
// ...etc
};
/**
* rsvp.js
*
* Author: Tilde, Inc.
* URL: https://github.com/tildeio/rsvp.js
* Licensed under MIT License
*
* Customized for use in operaextensions.js
* By: Rich Tibbett
*/
var exports = {};
var browserGlobal = (typeof window !== 'undefined') ? window : {};
var MutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var async;
if (typeof process !== 'undefined' &&
{}.toString.call(process) === '[object process]') {
async = function(callback, binding) {
process.nextTick(function() {
callback.call(binding);
});
};
} else if (MutationObserver) {
var queue = [];
var observer = new MutationObserver(function() {
var toProcess = queue.slice();
queue = [];
toProcess.forEach(function(tuple) {
var callback = tuple[0], binding = tuple[1];
callback.call(binding);
});
});
var element = document.createElement('div');
observer.observe(element, { attributes: true });
async = function(callback, binding) {
queue.push([callback, binding]);
element.setAttribute('drainQueue', 'drainQueue');
};
} else {
async = function(callback, binding) {
setTimeout(function() {
callback.call(binding);
}, 1);
};
}
exports.async = async;
var Event = exports.Event = function(type, options) {
this.type = type;
for (var option in options) {
if (!options.hasOwnProperty(option)) { continue; }
this[option] = options[option];
}
};
var indexOf = function(callbacks, callback) {
for (var i=0, l=callbacks.length; i<l; i++) {
if (callbacks[i][0] === callback) { return i; }
}
return -1;
};
var callbacksFor = function(object) {
var callbacks = object._promiseCallbacks;
if (!callbacks) {
callbacks = object._promiseCallbacks = {};
}
return callbacks;
};
var EventTarget = exports.EventTarget = {
mixin: function(object) {
object.on = this.on;
object.off = this.off;
object.trigger = this.trigger;
return object;
},
on: function(eventNames, callback, binding) {
var allCallbacks = callbacksFor(this), callbacks, eventName;
eventNames = eventNames.split(/\s+/);
binding = binding || this;
while (eventName = eventNames.shift()) {
callbacks = allCallbacks[eventName];
if (!callbacks) {
callbacks = allCallbacks[eventName] = [];
}
if (indexOf(callbacks, callback) === -1) {
callbacks.push([callback, binding]);
}
}
},
off: function(eventNames, callback) {
var allCallbacks = callbacksFor(this), callbacks, eventName, index;
eventNames = eventNames.split(/\s+/);
while (eventName = eventNames.shift()) {
if (!callback) {
allCallbacks[eventName] = [];
continue;
}
callbacks = allCallbacks[eventName];
index = indexOf(callbacks, callback);
if (index !== -1) { callbacks.splice(index, 1); }
}
},
trigger: function(eventName, options) {
var allCallbacks = callbacksFor(this),
callbacks, callbackTuple, callback, binding, event;
if (callbacks = allCallbacks[eventName]) {
for (var i=0, l=callbacks.length; i<l; i++) {
callbackTuple = callbacks[i];
callback = callbackTuple[0];
binding = callbackTuple[1];
if (typeof options !== 'object') {
options = { detail: options };
}
event = new Event(eventName, options);
callback.call(binding, event);
}
}
}
};
var Promise = exports.Promise = function() {
this.on('promise:resolved', function(event) {
this.trigger('success', { detail: event.detail });
}, this);
this.on('promise:failed', function(event) {
this.trigger('error', { detail: event.detail });
}, this);
};
var noop = function() {};
var invokeCallback = function(type, promise, callback, event) {
var value, error;
if (callback) {
try {
value = callback(event.detail);
} catch(e) {
error = e;
}
} else {
value = event.detail;
}
if (value instanceof Promise) {
value.then(function(value) {
promise.resolve(value);
}, function(error) {
promise.reject(error);
});
} else if (callback && value) {
promise.resolve(value);
} else if (error) {
promise.reject(error);
} else {
promise[type](value);
}
};
Promise.prototype = {
then: function(done, fail) {
var thenPromise = new Promise();
this.on('promise:resolved', function(event) {
invokeCallback('resolve', thenPromise, done, event);
});
this.on('promise:failed', function(event) {
invokeCallback('reject', thenPromise, fail, event);
});
return thenPromise;
},
resolve: function(value) {
exports.async(function() {
this.trigger('promise:resolved', { detail: value });
this.isResolved = value;
}, this);
this.resolve = noop;
this.reject = noop;
},
reject: function(value) {
exports.async(function() {
this.trigger('promise:failed', { detail: value });
this.isRejected = value;
}, this);
this.resolve = noop;
this.reject = noop;
}
};
EventTarget.mixin(Promise.prototype);
function isObjectEmpty(obj) {
for(var prop in obj) {
if(obj.hasOwnProperty(prop)) {
return false;
}
}
return true;
}
/**
* GENERAL OEX SHIM UTILITY FUNCTIONS
*/
/**
* Chromium doesn't support complex colors in places so
* this function will convert colors from rgb, rgba, hsv,
* hsl and hsla in to hex colors.
*
* 'color' is the color string to convert.
* 'backgroundColorVal' is a background color number (0-255)
* with which to apply alpha blending (if any).
*/
function complexColorToHex(color, backgroundColorVal) {
if(color === undefined || color === null) {
return color;
}
// Convert an Array input to RGG(A)
if(Object.prototype.toString.call(color) === "[object Array]") {
if(color.length === 4) {
color = "rgba(" + color[0] + "," + color[1] + "," + color[2] + "," + color[3] + ")";
} else if(color.length === 3) {
color = "rgb(" + color[0] + "," + color[1] + "," + color[2] + ")";
} else {
color = "rgb(255,255,255)";
}
}
// Force covert color to String
color = color + "";
// X11/W3C Color Names List
var colorKeywords = { aliceblue: [240,248,255], antiquewhite: [250,235,215], aqua: [0,255,255], aquamarine: [127,255,212],
azure: [240,255,255], beige: [245,245,220], bisque: [255,228,196], black: [0,0,0], blanchedalmond: [255,235,205],
blue: [0,0,255], blueviolet: [138,43,226], brown: [165,42,42], burlywood: [222,184,135], cadetblue: [95,158,160],
chartreuse: [127,255,0], chocolate: [210,105,30], coral: [255,127,80], cornflowerblue: [100,149,237], cornsilk: [255,248,220],
crimson: [220,20,60], cyan: [0,255,255], darkblue: [0,0,139], darkcyan: [0,139,139], darkgoldenrod: [184,134,11],
darkgray: [169,169,169], darkgreen: [0,100,0], darkgrey: [169,169,169], darkkhaki: [189,183,107], darkmagenta: [139,0,139],
darkolivegreen: [85,107,47], darkorange: [255,140,0], darkorchid: [153,50,204], darkred: [139,0,0], darksalmon: [233,150,122],
darkseagreen: [143,188,143], darkslateblue: [72,61,139], darkslategray: [47,79,79], darkslategrey: [47,79,79],
darkturquoise: [0,206,209], darkviolet: [148,0,211], deeppink: [255,20,147], deepskyblue: [0,191,255], dimgray: [105,105,105],
dimgrey: [105,105,105], dodgerblue: [30,144,255], firebrick: [178,34,34], floralwhite: [255,250,240], forestgreen: [34,139,34],
fuchsia: [255,0,255], gainsboro: [220,220,220], ghostwhite: [248,248,255], gold: [255,215,0], goldenrod: [218,165,32],
gray: [128,128,128], green: [0,128,0], greenyellow: [173,255,47], grey: [128,128,128], honeydew: [240,255,240],
hotpink: [255,105,180], indianred: [205,92,92], indigo: [75,0,130], ivory: [255,255,240], khaki: [240,230,140],
lavender: [230,230,250], lavenderblush: [255,240,245], lawngreen: [124,252,0], lemonchiffon: [255,250,205],
lightblue: [173,216,230], lightcoral: [240,128,128], lightcyan: [224,255,255], lightgoldenrodyellow: [250,250,210],
lightgray: [211,211,211], lightgreen: [144,238,144], lightgrey: [211,211,211], lightpink: [255,182,193],
lightsalmon: [255,160,122], lightseagreen: [32,178,170], lightskyblue: [135,206,250], lightslategray: [119,136,153],
lightslategrey: [119,136,153], lightsteelblue: [176,196,222], lightyellow: [255,255,224], lime: [0,255,0],
limegreen: [50,205,50], linen: [250,240,230], magenta: [255,0,255], maroon: [128,0,0], mediumaquamarine: [102,205,170],
mediumblue: [0,0,205], mediumorchid: [186,85,211], mediumpurple: [147,112,219], mediumseagreen: [60,179,113],
mediumslateblue: [123,104,238], mediumspringgreen: [0,250,154], mediumturquoise: [72,209,204], mediumvioletred: [199,21,133],
midnightblue: [25,25,112], mintcream: [245,255,250], mistyrose: [255,228,225], moccasin: [255,228,181], navajowhite: [255,222,173],
navy: [0,0,128], oldlace: [253,245,230], olive: [128,128,0], olivedrab: [107,142,35], orange: [255,165,0], orangered: [255,69,0],
orchid: [218,112,214], palegoldenrod: [238,232,170], palegreen: [152,251,152], paleturquoise: [175,238,238],
palevioletred: [219,112,147], papayawhip: [255,239,213], peachpuff: [255,218,185], peru: [205,133,63], pink: [255,192,203],
plum: [221,160,221], powderblue: [176,224,230], purple: [128,0,128], red: [255,0,0], rosybrown: [188,143,143],
royalblue: [65,105,225], saddlebrown: [139,69,19], salmon: [250,128,114], sandybrown: [244,164,96], seagreen: [46,139,87],
seashell: [255,245,238], sienna: [160,82,45], silver: [192,192,192], skyblue: [135,206,235], slateblue: [106,90,205],
slategray: [112,128,144], slategrey: [112,128,144], snow: [255,250,250], springgreen: [0,255,127], steelblue: [70,130,180],
tan: [210,180,140], teal: [0,128,128], thistle: [216,191,216], tomato: [255,99,71], turquoise: [64,224,208], violet: [238,130,238],
wheat: [245,222,179], white: [255,255,255], whitesmoke: [245,245,245], yellow: [255,255,0], yellowgreen: [154,205,50] };
// X11/W3C Color Name check
var predefinedColor = colorKeywords[ color.toLowerCase() ];
if( predefinedColor ) {
return "#" + DectoHex(predefinedColor[0]) + DectoHex(predefinedColor[1]) + DectoHex(predefinedColor[2]);
}
// Hex color patterns
var hexColorTypes = {
"hexLong": /^#([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
"hexShort": /^#([0-9a-fA-F]{3})$/
};
for(var colorType in hexColorTypes) {
if(color.match(hexColorTypes[ colorType ])) {
return color;
}
}
// Other color patterns
var otherColorTypes = [
["rgb", /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/],
["rgb", /^rgba\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d+(?:\.\d+)?|\.\d+)\s*\)$/], // rgba
["hsl", /^hsl\((\d{1,3}),\s*(\d{1,3})%,\s*(\d{1,3})%\)$/],
["hsl", /^hsla\((\d{1,3}),\s*(\d{1,3})%,\s*(\d{1,3})%,\s*(\d+(?:\.\d+)?|\.\d+)\s*\)$/], // hsla
["hsv", /^hsv\((\d{1,3}),\s*(\d{1,3})%,\s*(\d{1,3})%\)$/]
];
function hueToRgb( p, q, t ) {
if ( t < 0 ) {
t += 1;
}
if ( t > 1 ) {
t -= 1;
}
if ( t < 1 / 6 ) {
return p + ( q - p ) * 6 * t;
}
if ( t < 1 / 2 ) {
return q;
}
if ( t < 2 / 3 ) {
return p + ( q - p ) * ( 2 / 3 - t ) * 6;
}
return p;
};
var toRGB = {
rgb: function( bits ) {
return [ bits[1], bits[2], bits[3], bits[4] || 1 ];
},
hsl: function( bits ) {
var hsl = {
h : parseInt( bits[ 1 ], 10 ) % 360 / 360,
s : parseInt( bits[ 2 ], 10 ) % 101 / 100,
l : parseInt( bits[ 3 ], 10 ) % 101 / 100,
a : bits[4] || 1
};
if ( hsl.s === 0 ) {
return [ hsl.l, hsl.l, hsl.l ];
}
var q = hsl.l < 0.5 ? hsl.l * ( 1 + hsl.s ) : hsl.l + hsl.s - hsl.l * hsl.s;
var p = 2 * hsl.l - q;
return [
( hueToRgb( p, q, hsl.h + 1 / 3 ) * 256 ).toFixed( 0 ),
( hueToRgb( p, q, hsl.h ) * 256 ).toFixed( 0 ),
( hueToRgb( p, q, hsl.h - 1 / 3 ) * 256 ).toFixed( 0 ),
hsl.a
];
},
hsv: function( bits ) {
var rgb = {},
hsv = {
h : parseInt( bits[ 1 ], 10 ) % 360 / 360,
s : parseInt( bits[ 2 ], 10 ) % 101 / 100,
v : parseInt( bits[ 3 ], 10 ) % 101 / 100
},
i = Math.floor( hsv.h * 6 ),
f = hsv.h * 6 - i,
p = hsv.v * ( 1 - hsv.s ),
q = hsv.v * ( 1 - f * hsv.s ),
t = hsv.v * ( 1 - ( 1 - f ) * hsv.s );
switch( i % 6 ) {
case 0:
rgb.r = hsv.v; rgb.g = t; rgb.b = p;
break;
case 1:
rgb.r = q; rgb.g = hsv.v; rgb.b = p;
break;
case 2:
rgb.r = p; rgb.g = hsv.v; rgb.b = t;
break;
case 3:
rgb.r = p; rgb.g = q; rgb.b = hsv.v;
break;
case 4:
rgb.r = t; rgb.g = p; rgb.b = hsv.v;
break;
case 5:
rgb.r = hsv.v; rgb.g = p; rgb.b = q;
break;
}
return [ rgb.r * 256, rgb.g * 256, rgb.b * 256 ];
}
};
function DectoHex( dec ) {
var hex = parseInt( dec, 10 );
hex = hex.toString(16);
return hex == 0 ? "00" : hex;
}
function applySaturation( rgb ) {
var alpha = parseFloat(rgb[3] || 1);
if(alpha + "" === "NaN" || alpha < 0 || alpha >= 1) {
return rgb;
}
if(alpha == 0) {
return [ 255, 255, 255 ];
}
return [
alpha * parseInt(rgb[0], 10) + (1 - alpha) * (backgroundColorVal || 255),
alpha * parseInt(rgb[1], 10) + (1 - alpha) * (backgroundColorVal || 255),
alpha * parseInt(rgb[2], 10) + (1 - alpha) * (backgroundColorVal || 255)
]; // assumes background is white (255)
}
for(var i = 0, l = otherColorTypes.length; i < l; i++) {
var bits = otherColorTypes[i][1].exec( color );
if(bits) {
var rgbVal = applySaturation( toRGB[ otherColorTypes[i][0] ]( bits ) );
return "#" + DectoHex(rgbVal[0] || 255) + DectoHex(rgbVal[1] || 255) + DectoHex(rgbVal[2] || 255);
}
}
return "#f00"; // default in case of error
};
function OError(name, msg, code) {
Error.call(this);
Error.captureStackTrace(this, arguments.callee);
this.name = name || "Error";
this.code = code || -1;
this.message = msg || "";
};
OError.prototype.__proto__ = Error.prototype;
var OEvent = function(eventType, eventProperties) {
var props = eventProperties || {};
var newEvt = new CustomEvent(eventType, true, true);
for(var i in props) {
newEvt[i] = props[i];
}
return newEvt;
};
var OEventTarget = function() {
EventTarget.mixin( this );
};
OEventTarget.prototype.constructor = OEventTarget;
OEventTarget.prototype.addEventListener = function(eventName, callback, useCapture) {
this.on(eventName, callback); // no useCapture
};
OEventTarget.prototype.removeEventListener = function(eventName, callback, useCapture) {
this.off(eventName, callback); // no useCapture
}
OEventTarget.prototype.dispatchEvent = function( eventObj ) {
var eventName = eventObj.type;
// Register an onX functions registered for this event, if any
if(typeof this[ 'on' + eventName.toLowerCase() ] === 'function') {
this.on( eventName, this[ 'on' + eventName.toLowerCase() ] );
}
this.trigger( eventName, eventObj );
};
var OPromise = function() {
Promise.call( this );
};
OPromise.prototype = Object.create( Promise.prototype );
// Add OEventTarget helper functions to OPromise prototype
for(var i in OEventTarget.prototype) {
OPromise.prototype[i] = OEventTarget.prototype[i];
}
/**
* Queue for running multi-object promise-rooted asynchronous
* functions serially
*/
var Queue = (function() {
var _q = [], _lock = false, _timeout = 1000;
function callNext() {
_lock = false;
dequeue(); // auto-execute next queue item
}
function dequeue() {
if (_lock) {
return;
}
_lock = true; // only allow one accessor at a time
var item = _q.shift(); // pop the next item from the queue
if (item === undefined) {
_lock = false;
return; // end dequeuing
}
if (item.obj.isResolved) {
// execute queue item immediately
item.fn.call(item.obj, callNext);
} else {
if(item.ignoreResolve) {
item.fn.call(item.obj, callNext);
} else {
// break deadlocks
var timer = global.setTimeout(function() {
console.warn('PromiseQueue deadlock broken with timeout.');
console.log(item.obj);
console.log(item.obj.isResolved);
item.obj.trigger('promise:resolved'); // manual trigger / resolve
}, _timeout);
// execute queue item when obj resolves
item.obj.on('promise:resolved', function() {
if(timer) global.clearTimeout(timer);
item.obj.isResolved = true; // set too late in rsvp.js
item.fn.call(item.obj, callNext);
});
}
}
};
return {
enqueue: function(obj, fn, ignoreResolve) {
_q.push({ "obj": obj, "fn": fn, "ignoreResolve": ignoreResolve });
dequeue(); // auto-execute next queue item
},
dequeue: function() {
dequeue();
}
}
})();
var OMessagePort = function( isBackground ) {
OEventTarget.call( this );
this._isBackground = isBackground || false;
this._localPort = null;
// Every process, except the background process needs to connect up ports
if( !this._isBackground ) {
this._localPort = chrome.extension.connect({ "name": ("" + Math.floor( Math.random() * 1e16)) });
this._localPort.onDisconnect.addListener(function() {
this.dispatchEvent( new OEvent( 'disconnect', { "source": this._localPort } ) );
this._localPort = null;
}.bind(this));
var onMessageHandler = function( _message, _sender, responseCallback ) {
var localPort = this._localPort;
if(_message && _message.action && _message.action.indexOf('___O_') === 0) {
// Fire controlmessage events *immediately*
this.dispatchEvent( new OEvent(
'controlmessage',
{
"data": _message,
"source": {
postMessage: function( data ) {
localPort.postMessage( data );
},
"tabId": _sender && _sender.tab ? _sender.tab.id : null
}
}
) );
} else {
// Fire 'message' event once we have all the initial listeners setup on the page
// so we don't miss any .onconnect call from the extension page.
// Or immediately if the shim isReady
addDelayedEvent(this, 'dispatchEvent', [ new OEvent(
'message',
{
"data": _message,
"source": {
postMessage: function( data ) {
localPort.postMessage( data );
},
"tabId": _sender && _sender.tab ? _sender.tab.id : null
}
}
) ]);
}
if(responseCallback)responseCallback({});
}.bind(this);
this._localPort.onMessage.addListener( onMessageHandler );
chrome.extension.onMessage.addListener( onMessageHandler );
// Fire 'connect' event once we have all the initial listeners setup on the page
// so we don't miss any .onconnect call from the extension page
addDelayedEvent(this, 'dispatchEvent', [ new OEvent('connect', { "source": this._localPort, "origin": "" }) ]);
}
};
OMessagePort.prototype = Object.create( OEventTarget.prototype );
OMessagePort.prototype.postMessage = function( data ) {
if( !this._isBackground ) {
if(this._localPort) {
this._localPort.postMessage( data );
}
} else {
this.broadcastMessage( data );
}
};
var OBackgroundMessagePort = function() {
OMessagePort.call( this, true );
this._allPorts = {};
chrome.extension.onConnect.addListener(function( _remotePort ) {
var portIndex = _remotePort['name'] || Math.floor(Math.random() * 1e16);
// When this port disconnects, remove _port from this._allPorts
_remotePort.onDisconnect.addListener(function() {
delete this._allPorts[ portIndex ];
this.dispatchEvent( new OEvent('disconnect', { "source": _remotePort }) );
}.bind(this));
this._allPorts[ portIndex ] = _remotePort;
_remotePort.onMessage.addListener( function( _message, _sender, responseCallback ) {
if(_message && _message.action && _message.action.indexOf('___O_') === 0) {
// Fire controlmessage events *immediately*
this.dispatchEvent( new OEvent(
'controlmessage',
{
"data": _message,
"source": {
postMessage: function( data ) {
_remotePort.postMessage( data );
},
"tabId": _remotePort.sender && _remotePort.sender.tab ? _remotePort.sender.tab.id : null
}
}
) );
} else {
// Fire 'message' event once we have all the initial listeners setup on the page
// so we don't miss any .onconnect call from the extension page.
// Or immediately if the shim isReady
addDelayedEvent(this, 'dispatchEvent', [ new OEvent(
'message',
{
"data": _message,
"source": {
postMessage: function( data ) {
_remotePort.postMessage( data );
},
"tabId": _remotePort.sender && _remotePort.sender.tab ? _remotePort.sender.tab.id : null
}
}
) ]);
}
}.bind(this) );
this.dispatchEvent( new OEvent('connect', { "source": _remotePort, "origin": "" }) );
}.bind(this));
};
OBackgroundMessagePort.prototype = Object.create( OMessagePort.prototype );
OBackgroundMessagePort.prototype.broadcastMessage = function( data ) {
for(var activePort in this._allPorts) {
this._allPorts[ activePort ].postMessage( data );
}
};
var OperaExtension = function() {
OBackgroundMessagePort.call( this );
};
OperaExtension.prototype = Object.create( OBackgroundMessagePort.prototype );
// Generate API stubs
var OEX = opr.extension = opr.extension || new OperaExtension();
var OEC = opr.contexts = opr.contexts || {};
OperaExtension.prototype.getFile = function(path) {
var response = null;
if(typeof path != "string")return response;
try{
var host = chrome.extension.getURL('');
if(path.indexOf('widget:')==0)path = path.replace('widget:','chrome-extension:');
if(path.indexOf('/')==0)path = path.substring(1);
path = (path.indexOf(host)==-1?host:'')+path;
var xhr = new XMLHttpRequest();
xhr.onloadend = function(){
if (xhr.readyState==xhr.DONE && xhr.status==200){
result = xhr.response;
result.name = path.substring(path.lastIndexOf('/')+1);
result.lastModifiedDate = null;
result.toString = function(){
return "[object File]";
};
response = result;
};
};
xhr.open('GET',path,false);
xhr.responseType = 'blob';
xhr.send(null);
} catch(e){
return response;
};
return response;
};
var OStorage = function () {
// All attributes and methods defined in this class must be non-enumerable,
// hence the structure of this class and use of Object.defineProperty.
Object.defineProperty(this, "_storage", { value : localStorage });
Object.defineProperty(this, "length", { value : 0, writable:true });
// Copy all key/value pairs from localStorage on startup
for(var i in localStorage) {
this[i] = localStorage[i];
this.length++;
}
Object.defineProperty(OStorage.prototype, "getItem", {
value: function( key ) {
return this._storage.getItem(key);
}.bind(this)
});
Object.defineProperty(OStorage.prototype, "key", {
value: function( i ) {
return this._storage.key(i);
}.bind(this)
});
Object.defineProperty(OStorage.prototype, "removeItem", {
value: function( key, proxiedChange ) {
this._storage.removeItem(key);
if( this.hasOwnProperty( key ) ) {
delete this[key];
this.length--;
}
if( !proxiedChange ) {
OEX.postMessage({
"action": "___O_widgetPreferences_removeItem_RESPONSE",
"data": {
"key": key
}
});
}
}.bind(this)
});
Object.defineProperty(OStorage.prototype, "setItem", {
value: function( key, value, proxiedChange ) {
var oldVal = this._storage.getItem(key);
this._storage.setItem(key, value);
if( !this[key] ) {
this.length++;
}
this[key] = value;
if( !proxiedChange ) {
OEX.postMessage({
"action": "___O_widgetPreferences_setItem_RESPONSE",
"data": {
"key": key,
"val": value
}
});
}
// Create and fire 'storage' event on window object
var storageEvt = new OEvent('storage', {
"key": key,
"oldValue": oldVal,
"newValue": this._storage.getItem(key),
"url": chrome.extension.getURL(""),
"storageArea": this._storage
});
global.dispatchEvent( storageEvt );
}.bind(this)
});
Object.defineProperty(OStorage.prototype, "clear", {
value: function( proxiedChange ) {
this._storage.clear();
for(var i in this) {
if( this.hasOwnProperty( i ) ) {
delete this[ i ];
}
}
this.length = 0;
if( !proxiedChange ) {
OEX.postMessage({
"action": "___O_widgetPreferences_clearItem_RESPONSE"
});
}
}.bind(this)
});
};
// Inherit the standard Storage prototype
OStorage.prototype = Object.create( global.Storage.prototype );
var OWidgetObj = function() {
OEventTarget.call(this);
this.properties = manifest;
// LocalStorage shim
this._preferences = new OStorage();
// Setup widget object proxy listener
// for injected scripts and popups to connect to
OEX.addEventListener('controlmessage', function( msg ) {
if( !msg.data || !msg.data.action ) {
return;
}
switch( msg.data.action ) {
// Set up all storage properties
case '___O_widget_setup_REQUEST':
var dataObj = {};
for(var i in this.properties) {
dataObj[ i ] = this.properties[ i ];
}
msg.source.postMessage({
"action": "___O_widget_setup_RESPONSE",
"attrs": dataObj,
// Add a copy of the preferences object
"_prefs": this._preferences
});
break;
// Update a storage item
case '___O_widgetPreferences_setItem_REQUEST':
this._preferences.setItem( msg.data.data.key, msg.data.data.val, true );
break;
// Remove a storage item
case '___O_widgetPreferences_removeItem_REQUEST':
this._preferences.removeItem( msg.data.data.key, true );
break;
// Clear all storage items
case '___O_widgetPreferences_clear_REQUEST':
this._preferences.clear( true );
break;
case '___O_widgetPreferences_updateAll':
for(var prefKey in msg.data.data) {
this._preferences.setItem( prefKey, msg.data.data[ prefKey ], false );
}
break;
default:
break;
}
}.bind(this), false);
};
OWidgetObj.prototype = Object.create( OEventTarget.prototype );
OWidgetObj.prototype.__defineGetter__('name', function() {
return this.properties.name || "";
});
OWidgetObj.prototype.__defineGetter__('shortName', function() {
return this.properties.name ? this.properties.name.short || "" : "";
});
OWidgetObj.prototype.__defineGetter__('id', function() {
return this.properties.id || "";
});
OWidgetObj.prototype.__defineGetter__('description', function() {
return this.properties.description || "";
});
OWidgetObj.prototype.__defineGetter__('author', function() {
return this.properties.author ? this.properties.author.name || "" : "";
});
OWidgetObj.prototype.__defineGetter__('authorHref', function() {
return this.properties.author ? this.properties.author.href || "" : "";
});
OWidgetObj.prototype.__defineGetter__('authorEmail', function() {
return this.properties.author ? this.properties.author.email || "" : "";
});
OWidgetObj.prototype.__defineGetter__('version', function() {
return this.properties.version || "";
});
OWidgetObj.prototype.__defineGetter__('preferences', function() {
return this._preferences;
});
// Add Widget API directly to global window
try {
global.widget = widget || new OWidgetObj();
} catch(e) {
global.widget = new OWidgetObj();
}
var BrowserWindowManager = function() {
OPromise.call(this);
this.length = 0;
// Set up the real BrowserWindow (& BrowserTab) objects available at start up time
chrome.windows.getAll({
populate: true
}, function(_windows) {
var _allTabs = [];
for (var i = 0, l = _windows.length; i < l; i++) {
var newWindow = new BrowserWindow(_windows[i]);
// Set properties not available in BrowserWindow constructor
newWindow.properties.id = _windows[i].id;
newWindow.properties.incognito = _windows[i].incognito;
this[i] = newWindow;
this.length = i + 1;
// Replace tab properties belonging to this window with real properties
var _tabs = [];
for (var j = 0, k = _windows[i].tabs.length; j < k; j++) {
_tabs[j] = new BrowserTab(_windows[i].tabs[j], this[i], true);
// Set properties not available in BrowserTab constructor
_tabs[j].properties.id = _windows[i].tabs[j].id;
_tabs[j].properties.active = _windows[i].tabs[j].active;
_tabs[j].properties.pinned = _windows[i].tabs[j].pinned;
_tabs[j].properties.status = _windows[i].tabs[j].status;
_tabs[j].properties.title = _windows[i].tabs[j].title;
_tabs[j].properties.favIconUrl = _windows[i].tabs[j].favIconUrl;
_tabs[j].properties.url = _windows[i].tabs[j].url;
_tabs[j].properties.index = _windows[i].tabs[j].index;
_tabs[j].properties.incognito = _windows[i].tabs[j].incognito;
}
this[i].tabs.replaceTabs(_tabs);
_allTabs = _allTabs.concat(_tabs);
}
// Replace tabs in root tab manager object
OEX.tabs.replaceTabs(_allTabs);
// Resolve root window manager
this.resolve(true);
// Resolve root tabs manager
OEX.tabs.resolve(true);
// Resolve objects.
//
// Resolution of each object in order:
// 1. Window
// 2. Window's Tab Manager
// 3. Window's Tab Manager's Tabs
for (var i = 0, l = this.length; i < l; i++) {
this[i].resolve(true);
this[i].tabs.resolve(true);
for (var j = 0, k = this[i].tabs.length; j < k; j++) {
this[i].tabs[j].resolve(true);
}
}
// Set WinTabs feature to LOADED
deferredComponentsLoadStatus['WINTABS_LOADED'] = true;
}.bind(this));
this.addWindow = function(windowId, windowObj) {
windowObj.properties.id = windowId;
this[this.length] = windowObj;
this.length += 1;
// Resolve object
windowObj.resolve(true);
windowObj.tabs.resolve(true);
// Fire a new 'create' event on this manager object
this.dispatchEvent(new OEvent('create', {
browserWindow: windowObj
}));
};
// Monitor ongoing window events
chrome.windows.onFocusChanged.addListener(function(windowId) {
var _prevFocusedWindow = this.getLastFocused();
// If no new window is focused, abort here
if( windowId !== chrome.windows.WINDOW_ID_NONE ) {
// Find and fire focus event on newly focused window
for (var i = 0, l = this.length; i < l; i++) {
if (this[i].properties.id == windowId && _prevFocusedWindow !== this[i] ) {
this[i].properties.focused = true;
} else {
this[i].properties.focused = false;
}
}
}
// Find and fire blur event on currently focused window
for (var i = 0, l = this.length; i < l; i++) {
if (this[i].properties.id !== windowId && this[i] == _prevFocusedWindow) {
this[i].properties.focused = false;
var _newFocusedWindow = this.getLastFocused();
// Fire a new 'blur' event on the window object
this[i].dispatchEvent(new OEvent('blur', {
browserWindow: _newFocusedWindow
}));
// Fire a new 'blur' event on this manager object
this.dispatchEvent(new OEvent('blur', {
browserWindow: _newFocusedWindow
}));
// If something is blurring then we should also fire the
// corresponding 'focus' events
// Fire a new 'focus' event on the window object
_newFocusedWindow.dispatchEvent(new OEvent('focus', {
browserWindow: _prevFocusedWindow
}));
// Fire a new 'focus' event on this manager object
this.dispatchEvent(new OEvent('focus', {
browserWindow: _prevFocusedWindow
}));
break;
}
}
// Queue.dequeue();
}.bind(this));
chrome.windows.onRemoved.addListener(function(windowId) {
// Remove window from current collection
var deleteIndex = -1;
for (var i = 0, l = this.length; i < l; i++) {
if (this[i].properties.id == windowId) {
deleteIndex = i;
break;
}
}
if (deleteIndex > -1) {
var removedWindow = this[deleteIndex];
removedWindow.properties.closed = true;
// Set window tabs collection to empty
removedWindow.tabs.replaceTabs([]);
// Manually splice the deleteIndex_th_ item from the current windows collection
for (var i = deleteIndex, l = this.length; i < l; i++) {
if (this[i + 1]) {
this[i] = this[i + 1];
} else {
delete this[i]; // remove last item
}
}
this.length -= 1;
// Fire a new 'close' event on the closed BrowserWindow object
removedWindow.dispatchEvent(new OEvent('close', {}));
// Fire a new 'close' event on this manager object
this.dispatchEvent(new OEvent('close', {
'browserWindow': removedWindow
}));
}
// Queue.dequeue();
}.bind(this));
};
BrowserWindowManager.prototype = Object.create(OPromise.prototype);
BrowserWindowManager.prototype.create = function(tabsToInject, browserWindowProperties) {
/*
// Support tc-BrowserWindowManager-015 test
var isEmpty_TabsToInject = true;
if(tabsToInject && Object.prototype.toString.call(tabsToInject) === "[object Array]") {
for(var i = 0, l = tabsToInject.length; i < l; i++) {
if( !isObjectEmpty(tabsToInject[i]) ) {
isEmpty_TabsToInject = false;
break;
}
}
}
var isEmpty_BrowserWindowProperties = isObjectEmpty(browserWindowProperties || {});
// undefined/null tabsToInject w/ non-empty window properties is ok
if( !isEmpty_BrowserWindowProperties && (tabsToInject === undefined || tabsToInject === null)) {
noTabsToInject = false;
}
if(isEmpty_TabsToInject && isEmpty_BrowserWindowProperties) {
throw new OError(
"NotSupportedError",
"Cannot create a new window without providing at least one method parameter.",
DOMException.NOT_SUPPORTED_ERR
);
}
if(!isEmpty_TabsToInject && isEmpty_BrowserWindowProperties) {
throw new OError(
"NotSupportedError",
"Cannot create a new window without providing at least one window property parameter.",
DOMException.NOT_SUPPORTED_ERR
);
}
if(isEmpty_TabsToInject && !isEmpty_BrowserWindowProperties) {
throw new OError(
"NotSupportedError",
"Cannot create a new window without providing at least one object (or 'null')",
DOMException.NOT_SUPPORTED_ERR
);
}*/
// Create new BrowserWindow object (+ sanitize browserWindowProperties values)
var shadowBrowserWindow = new BrowserWindow(browserWindowProperties);
var createProperties = {
'focused': shadowBrowserWindow.properties.focused,
'incognito': shadowBrowserWindow.properties.incognito,
'width': shadowBrowserWindow.properties.width,
'height': shadowBrowserWindow.properties.height,
'top': shadowBrowserWindow.properties.top,
'left': shadowBrowserWindow.properties.left
};
// Add tabs included in the create() call to the newly created
// window, if any, based on type
var hasTabsToInject = false;
var tabsToMove = [];
var tabsToCreate = [];
if (tabsToInject &&
Object.prototype.toString.call(tabsToInject) === "[object Array]" &&
tabsToInject.length > 0) {
hasTabsToInject = true;
for (var i = 0, l = tabsToInject.length; i < l; i++) {
if (tabsToInject[i] instanceof BrowserTab) {
(function(existingBrowserTab, index) {
// Remove tab from previous window parent and then
// add it to its new window parent
if(existingBrowserTab._windowParent) {
existingBrowserTab._windowParent.tabs.removeTab(existingBrowserTab);
}
// Rewrite tab's BrowserWindow parent
existingBrowserTab._windowParent = shadowBrowserWindow;
// Rewrite tab's index position in collection
existingBrowserTab.properties.index = shadowBrowserWindow.tabs.length;
shadowBrowserWindow.tabs.addTab( existingBrowserTab, existingBrowserTab.properties.index);
// Don't create the first tab as this will be resolved differently
if(index == 0) {
// Implicitly add the first BrowserTab to the new window
createProperties.tabId = existingBrowserTab.properties.id;
shadowBrowserWindow.rewriteUrl = newTab_BaseURL.replace('%s', existingBrowserTab.properties.id);
} else {
// handled in window.create callback function
// because we need the window's id property to move
// items to this window object
tabsToMove.push(existingBrowserTab);
}
// move events etc will fire in onMoved listener of RootBrowserTabManager
})(tabsToInject[i], i);
} else { // Treat as a BrowserTabProperties object by default
(function(browserTabProperties, index) {
browserTabProperties = browserTabProperties || {};
var newBrowserTab = new BrowserTab(browserTabProperties, shadowBrowserWindow);
newBrowserTab.properties.index = i;
// Register BrowserTab object with the current BrowserWindow object
shadowBrowserWindow.tabs.addTab( newBrowserTab, newBrowserTab.properties.index);
// Add object to root store
OEX.tabs.addTab( newBrowserTab );
// set BrowserWindow object's rewriteUrl to first tab's opera id
if( index == 0 ) {
createProperties.url = shadowBrowserWindow.rewriteUrl = newTab_BaseURL.replace('%s', newBrowserTab._operaId);
} else {
tabsToCreate.push(newBrowserTab);
}
})(tabsToInject[i], i);
}
}
} else { // we only have one default chrome://newtab or opera://startpage tab to set up
// setup single new tab and tell onCreated to ignore this item
var defaultBrowserTab = new BrowserTab({ active: true }, shadowBrowserWindow);
// Register BrowserTab object with the current BrowserWindow object
shadowBrowserWindow.tabs.addTab( defaultBrowserTab, defaultBrowserTab.properties.index );
// Add object to root store
OEX.tabs.addTab( defaultBrowserTab );
// set rewriteUrl to windowId
shadowBrowserWindow.rewriteUrl = newTab_BaseURL.replace('%s', shadowBrowserWindow._operaId);
createProperties.url = shadowBrowserWindow.rewriteUrl;
}
// Add this object to the current collection
this[this.length] = shadowBrowserWindow;
this.length += 1;
// unfocus all other windows in collection if this window is focused
if(shadowBrowserWindow.properties.focused == true ) {
for(var i = 0, l = this.length; i < l; i++) {
if(this[i] !== shadowBrowserWindow) {
this[i].properties.focused = false;
}
}
}
// Queue platform action or fire immediately if this object is resolved
Queue.enqueue(this, function(done) {
chrome.windows.create(
createProperties,
function(_window) {
// Update BrowserWindow properties
for (var i in _window) {
if(i == 'tabs') continue; // don't overwrite tabs!
shadowBrowserWindow.properties[i] = _window[i];
}
// Move any remaining existing tabs to new window
// now that we have the window.id property assigned
// above in properties copy
if( tabsToMove.length > 0 ) {
for(var i = 0, l = tabsToMove.length; i < l; i++) {
(function(existingBrowserTab) {
// Explicitly move anything after the first BrowserTab to the new window
Queue.enqueue(existingBrowserTab, function(done) {
chrome.tabs.move(
this.properties.id,
{
index: this._windowParent.tabs.length,
windowId: this._windowParent.properties.id
},
function(_tab) {
for (var i in _tab) {
if(i == 'url') continue;
this.properties[i] = _tab[i];
}
done();
}.bind(this)
);
}.bind(existingBrowserTab));
})(tabsToMove[i]);
}
}
if( tabsToCreate.length > 0 ) {
for(var i = 0, l = tabsToCreate.length; i < l; i++) {
(function(newBrowserTab) {
var tabCreateProps = {
'windowId': shadowBrowserWindow.properties.id,
'url': newBrowserTab.properties.url || 'about:blank',
'active': newBrowserTab.properties.active,
'pinned': newBrowserTab.properties.pinned,
'index': newBrowserTab.properties.index
};
Queue.enqueue(this, function(done) {
chrome.tabs.create(
tabCreateProps,
function(_tab) {
for (var i in _tab) {
newBrowserTab.properties[i] = _tab[i];
}
newBrowserTab.resolve(true);
done();
}.bind(shadowBrowserWindow.tabs)
);
}.bind(this), true);
newBrowserTab._windowParent.tabs.dispatchEvent(new OEvent('create', {
"tab": newBrowserTab,
"prevWindow": newBrowserTab._windowParent,
"prevTabGroup": null,
"prevPosition": NaN
}));
// Fire a create event at RootTabsManager
OEX.tabs.dispatchEvent(new OEvent('create', {
"tab": newBrowserTab,
"prevWindow": newBrowserTab._windowParent,
"prevTabGroup": null,
"prevPosition": NaN
}));
})(tabsToCreate[i]);
}
}
done();
}.bind(this)
);
}.bind(this), true);
// return shadowBrowserWindow from this function before firing these events!
global.setTimeout(function() {
// Fire a new 'create' event on this manager object
this.dispatchEvent(new OEvent('create', {
browserWindow: shadowBrowserWindow
}));
}.bind(this), 50);
return shadowBrowserWindow;
};
BrowserWindowManager.prototype.getAll = function() {
var allWindows = [];
for (var i = 0, l = this.length; i < l; i++) {
allWindows[i] = this[i];
}
return allWindows;
};
BrowserWindowManager.prototype.getLastFocused = function() {
for(var i = 0, l = this.length; i < l; i++) {
if(this[i].focused == true) {
return this[i];
}
}
// default
if(this[0]) {
this[0].properties.focused = true;
}
return this[0] || undefined;
};
BrowserWindowManager.prototype.close = function(browserWindow) {
if(!browserWindow || !(browserWindow instanceof BrowserWindow)) {
return;
}
browserWindow.close();
};
var BrowserWindow = function(browserWindowProperties) {
OPromise.call(this);
browserWindowProperties = browserWindowProperties || {};
this.properties = {
'id': undefined, // not settable on create
'closed': false, // not settable on create
'focused': browserWindowProperties.focused ? !!browserWindowProperties.focused : undefined,
// private:
'incognito': browserWindowProperties.private ? !!browserWindowProperties.private : undefined,
'parent': null,
'width': browserWindowProperties.width ? parseInt(browserWindowProperties.width, 10) : undefined,
'height': browserWindowProperties.height ? parseInt(browserWindowProperties.height, 10) : undefined,
'top': browserWindowProperties.top ? parseInt(browserWindowProperties.top, 10) : undefined,
'left': browserWindowProperties.left ? parseInt(browserWindowProperties.left, 10) : undefined
// 'tabGroups' not part of settable properties
// 'tabs' not part of settable properties
};
this._parent = null;
// Create a unique browserWindow id
this._operaId = Math.floor(Math.random() * 1e16);
this.tabs = new BrowserTabManager(this);
this.tabGroups = new BrowserTabGroupManager(this);
if(this.properties.private !== undefined) {
this.properties.incognito = !!this.properties.private;
delete this.properties.private;
}
// Not allowed when creating a new window object
if(this.properties.closed !== undefined) {
delete this.properties.closed;
}
};
BrowserWindow.prototype = Object.create(OPromise.prototype);
// API
BrowserWindow.prototype.__defineGetter__("id", function() {
return this._operaId;
});
BrowserWindow.prototype.__defineGetter__("closed", function() {
return this.properties.closed !== undefined ? !!this.properties.closed : false;
});
BrowserWindow.prototype.__defineGetter__("focused", function() {
return this.properties.focused !== undefined ? !!this.properties.focused : false;
});
BrowserWindow.prototype.__defineGetter__("private", function() {
return this.properties.incognito !== undefined ? !!this.properties.incognito : false;
});
BrowserWindow.prototype.__defineGetter__("top", function() {
return this.properties.top !== undefined ? this.properties.top : -1;
}); // read-only
BrowserWindow.prototype.__defineGetter__("left", function() {
return this.properties.left !== undefined ? this.properties.left : -1;
}); // read-only
BrowserWindow.prototype.__defineGetter__("height", function() {
return this.properties.height !== undefined ? this.properties.height : -1;
}); // read-only
BrowserWindow.prototype.__defineGetter__("width", function() {
return this.properties.width !== undefined ? this.properties.width : -1;
}); // read-only
BrowserWindow.prototype.__defineGetter__("parent", function() {
return this._parent;
});
BrowserWindow.prototype.insert = function(browserTab, child) {
if (!browserTab || !(browserTab instanceof BrowserTab)) {
return;
}
if (this.properties.closed === true) {
throw new OError(
"InvalidStateError",
"Current window is in the closed state and therefore is invalid",
DOMException.INVALID_STATE_ERR
);
}
var moveProperties = {
windowId: this.properties.id,
index: OEX.windows.length // by default, add to the end of the current window
};
// Set insert position for the new tab from 'before' attribute, if any
if (child && (child instanceof BrowserTab)) {
if (child.closed === true) {
throw new OError(
"InvalidStateError",
"'child' parameter is in the closed state and therefore is invalid",
DOMException.INVALID_STATE_ERR
);
}
if (child._windowParent && child._windowParent.closed === true) {
throw new OError(
"InvalidStateError",
"Parent window of 'child' parameter is in the closed state and therefore is invalid",
DOMException.INVALID_STATE_ERR
);
}
moveProperties.windowId = child._windowParent ?
child._windowParent.properties.id : moveProperties.windowId;
moveProperties.index = child.position;
} else {
// IF we're moving within the same window then index will be length - 1
moveProperties.index = moveProperties.index > 0 ? moveProperties.index - 1 : moveProperties.index;
}
// Detach tab from existing BrowserWindow parent (if any)
if (browserTab._windowParent) {
browserTab._oldWindowParent = browserTab._windowParent;
browserTab._oldIndex = browserTab.properties.index;
if(browserTab._oldWindowParent !== this) {
browserTab._windowParent.tabs.removeTab( browserTab );
}
}
// Attach tab to new BrowserWindow parent
browserTab._windowParent = this;
// Update index within new parent
browserTab.properties.index = moveProperties.index;
if(this !== browserTab._oldWindowParent) {
// Attach tab to new parent
this.tabs.addTab( browserTab, browserTab.properties.index );
}
// Queue platform action or fire immediately if this object is resolved
Queue.enqueue(browserTab, function(done) {
chrome.tabs.move(
browserTab.properties.id,
{
windowId: moveProperties.windowId || this.properties.id,
index: moveProperties.index
},
function(_tab) {
done();
}.bind(this)
);
}.bind(this));
};
BrowserWindow.prototype.focus = function() {
if(this.properties.focused == true || this.properties.closed == true) {
return; // already focused or invalid because window is closed
}
// Set BrowserWindow object to focused state
this.properties.focused = true;
// unset all other window object's focused state
for(var i = 0, l = OEX.windows.length; i < l; i++) {
if(OEX.windows[i] !== this) {
OEX.windows[i].properties.focused = false;
}
}
// Queue platform action or fire immediately if this object is resolved
Queue.enqueue(this, function(done) {
chrome.windows.update(
this.properties.id,
{ focused: true },
function() {
done();
}.bind(this)
);
}.bind(this));
};
BrowserWindow.prototype.update = function(browserWindowProperties) {
var updateProperties = {};
if(browserWindowProperties.focused !== undefined && browserWindowProperties.focused == true) {
this.properties.focused = updateProperties.focused = !!browserWindowProperties.focused;
}
if(browserWindowProperties.top !== undefined && browserWindowProperties.top !== null) {
this.properties.top = updateProperties.top = parseInt(browserWindowProperties.top, 10);
}
if(browserWindowProperties.left !== undefined && browserWindowProperties.left !== null) {
this.properties.left = updateProperties.left = parseInt(browserWindowProperties.left, 10);
}
if(browserWindowProperties.height !== undefined && browserWindowProperties.height !== null) {
this.properties.height = updateProperties.height = parseInt(browserWindowProperties.height, 10);
}
if(browserWindowProperties.width !== undefined && browserWindowProperties.width !== null) {
this.properties.width = updateProperties.width = parseInt(browserWindowProperties.width, 10);
}
if( !isObjectEmpty(updateProperties) ) {
// Queue platform action or fire immediately if this object is resolved
Queue.enqueue(this, function(done) {
chrome.windows.update(
this.properties.id,
updateProperties,
function() {
done();
}.bind(this)
);
}.bind(this));
}
}
BrowserWindow.prototype.close = function() {
if( this.properties.closed == true) {
/*throw new OError(
"InvalidStateError",
"The current BrowserWindow object is already closed. Cannot call close on this object.",
DOMException.INVALID_STATE_ERR
);*/
return;
}
// Set BrowserWindow object to closed state
this.properties.closed = true;
// Queue platform action or fire immediately if this object is resolved
Queue.enqueue(this, function(done) {
if(!this.properties.id) return;
chrome.windows.remove(
this.properties.id,
function() {
done();
}.bind(this)
);
}.bind(this));
};
var BrowserTabManager = function( parentObj ) {
OPromise.call( this );
// Set up 0 mock BrowserTab objects at startup
this.length = 0;
this._parent = parentObj;
// Remove all collection items and replace with browserTabs
this.replaceTabs = function( browserTabs ) {
for( var i = 0, l = this.length; i < l; i++ ) {
delete this[ i ];
}
this.length = 0;
if(browserTabs.length <= 0) {
return;
}
for( var i = 0, l = browserTabs.length; i < l; i++ ) {
if(this !== OEX.tabs) {
browserTabs[ i ].properties.index = i;
}
this[ i ] = browserTabs[ i ];
}
this.length = browserTabs.length;
// Set focused on first tab object, unless some other tab object has focused=='true'
var focusFound = false;
for(var i = 0, l = browserTabs.length; i < l; i++) {
if(browserTabs[i].properties.active == true) {
focusFound = true;
break;
}
}
if(!focusFound) {
browserTabs[0].focus();
}
};
// Add an array of browserTabs to the current collection
this.addTab = function( browserTab, startPosition ) {
// Extract current set of tabs in collection
var allTabs = [];
for(var i = 0, l = this.length; i < l; i++) {
allTabs[ i ] = this[ i ];
if(allTabs[ i ].properties.active == true) {
focusFound = true;
}
}
if(browserTab.properties.active == true) {
browserTab.focus();
}
var position = startPosition !== undefined ? startPosition : allTabs.length;
// Add new browserTab to allTabs array
allTabs.splice(this !== OEX.tabs ? position : this.length, 0, browserTab);
// Rewrite the current tabs collection in order
for( var i = 0, l = allTabs.length; i < l; i++ ) {
if(this !== OEX.tabs) {
// Update all tab indexes to the current tabs collection order
allTabs[ i ].properties.index = i;
}
this[ i ] = allTabs[ i ];
}
this.length = allTabs.length;
};
// Remove a browserTab from the current collection
this.removeTab = function( browserTab ) {
var oldCollectionLength = this.length;
// Extract current set of tabs in collection
var allTabs = [];
var removeTabIndex = -1;
for(var i = 0, l = this.length; i < l; i++) {
allTabs[ i ] = this[ i ];
if( allTabs[ i ].id == browserTab.id ) {
removeTabIndex = i;
}
}
// Remove browser tab
if(removeTabIndex > -1) {
allTabs.splice(removeTabIndex, 1);
}
// Rewrite the current tabs collection
for( var i = 0, l = allTabs.length; i < l; i++ ) {
if(this !== OEX.tabs) {
allTabs[ i ].properties.index = i;
}
this[ i ] = allTabs[ i ];
}
this.length = allTabs.length;
// Remove any ghost items, if any
if(oldCollectionLength > this.length) {
for(var i = this.length, l = oldCollectionLength; i < l; i++) {
delete this[ i ];
}
}
};
};
BrowserTabManager.prototype = Object.create( OPromise.prototype );
BrowserTabManager.prototype.create = function( browserTabProperties, before ) {
if(before && !(before instanceof BrowserTab)) {
throw new OError(
"TypeMismatchError",
"Could not create BrowserTab object. 'before' attribute provided is invalid.",
DOMException.TYPE_MISMATCH_ERR
);
} else if(before) {
if( before.closed === true ) {
throw new OError(
"InvalidStateError",
"'before' BrowserTab object is in the closed state and therefore is invalid.",
DOMException.INVALID_STATE_ERR
);
}
if(before._windowParent && before._windowParent.closed === true ) {
throw new OError(
"InvalidStateError",
"Parent window of 'before' BrowserTab object is in the closed state and therefore is invalid.",
DOMException.INVALID_STATE_ERR
);
}
// If we're adding this BrowserTab before an existing object then set its insert position correctly
browserTabProperties.position = before.properties.index;
}
// Set parent window to create the tab in
var windowParent = before && before._windowParent ? before._windowParent : this._parent || OEX.windows.getLastFocused();
if(windowParent && windowParent.closed === true ) {
throw new OError(
"InvalidStateError",
"Parent window of the current BrowserTab object is in the closed state and therefore is invalid.",
DOMException.INVALID_STATE_ERR
);
}
var shadowBrowserTab = new BrowserTab( browserTabProperties, windowParent );
// Sanitized tab properties
var createTabProperties = {
'url': shadowBrowserTab.properties.url,
'active': shadowBrowserTab.properties.active,
'pinned': shadowBrowserTab.properties.pinned,
'index': shadowBrowserTab.properties.index
};
// Set insert position for the new tab from 'before' attribute, if any
if( before ) {
createTabProperties.windowId = before._windowParent ?
before._windowParent.properties.id : createTabProperties.windowId;
}
// Add this object to the end of the current tabs collection
shadowBrowserTab._windowParent.tabs.addTab(shadowBrowserTab, shadowBrowserTab.properties.index);
// unfocus all other tabs in tab's window parent collection if this tab is set to focused
if(shadowBrowserTab.properties.active == true ) {
for(var i = 0, l = shadowBrowserTab._windowParent.tabs.length; i < l; i++) {
if(shadowBrowserTab._windowParent.tabs[i] !== shadowBrowserTab) {
shadowBrowserTab._windowParent.tabs[i].properties.active = false;
}
}
}
// Add this object to the root tab manager
OEX.tabs.addTab( shadowBrowserTab );
// Queue platform action or fire immediately if this object is resolved
Queue.enqueue(this, function(done) {
chrome.tabs.create(
createTabProperties,
function( _tab ) {
// Update BrowserTab properties
for(var i in _tab) {
if(i == 'url') continue;
shadowBrowserTab.properties[i] = _tab[i];
}
// Resolve new tab, if it hasn't been resolved already
shadowBrowserTab.resolve(true);
done();
}.bind(this)
);
}.bind(this), true);
// return shadowBrowserTab from this function before firing these events!
global.setTimeout(function() {
shadowBrowserTab._windowParent.tabs.dispatchEvent(new OEvent('create', {
"tab": shadowBrowserTab,
"prevWindow": null,
"prevTabGroup": null,
"prevPosition": 0
}));
// Fire a create event at RootTabsManager
OEX.tabs.dispatchEvent(new OEvent('create', {
"tab": shadowBrowserTab,
"prevWindow": null,
"prevTabGroup": null,
"prevPosition": 0
}));
}, 50);
return shadowBrowserTab;
};
BrowserTabManager.prototype.getAll = function() {
var allTabs = [];
for(var i = 0, l = this.length; i < l; i++) {
allTabs[ i ] = this[ i ];
}
return allTabs;
};
BrowserTabManager.prototype.getSelected = function() {
for(var i = 0, l = this.length; i < l; i++) {
if(this[i].focused == true) {
return this[i];
}
}
// default
if(this[0]) {
this[0].properties.active = true;
}
return this[0] || undefined;
};
// Alias of .getSelected()
BrowserTabManager.prototype.getFocused = BrowserTabManager.prototype.getSelected;
BrowserTabManager.prototype.close = function( browserTab ) {
if( !browserTab || !(browserTab instanceof BrowserTab)) {
throw new OError(
"TypeMismatchError",
"Expected browserTab argument to be of type BrowserTab.",
DOMException.TYPE_MISMATCH_ERR
);
}
browserTab.close();
};
var RootBrowserTabManager = function() {
BrowserTabManager.call(this);
// list of tab objects we should ignore
this._blackList = {};
// global permanaent tabs collection manager
this._allTabs = [];
// Event Listener implementations
chrome.tabs.onCreated.addListener(function(_tab) {
var tabFoundIndex = -1;
for (var i = 0, l = this._allTabs.length; i < l; i++) {
// opera.extension.windows.create rewrite hack
if (this._allTabs[i].rewriteUrl && this._allTabs[i].properties.url == _tab.url) {
if(this._allTabs[i]._windowParent) {
// If the window ids don't match then silently move the tab to the correct parent
// e.g. this happens if we create a new tab from the background page's console.
if(this._allTabs[i]._windowParent.properties.id !== _tab.windowId) {
for(var j = 0, k = OEX.windows.length; j < k; j++) {
if(OEX.windows[j].properties.id == _tab.windowId) {
this._allTabs[i]._windowParent.tabs.removeTab(this._allTabs[i]);
this._allTabs[i]._windowParent = OEX.windows[j];
//this._allTabs[i].properties.index = this._allTabs[i]._windowParent.tabs.length;
this._allTabs[i].properties.windowId = _tab.windowId;
// Force change tab's index position in platform
Queue.enqueue(this._allTabs[i], function(done) {
chrome.tabs.move(
this.properties.id,
{ index: this._windowParent.tabs.length },
function(_tab) {
done();
}.bind(this)
);
}.bind(this._allTabs[i]));
OEX.windows[j].tabs.addTab( this._allTabs[i], this._allTabs[i].properties.index);
}
}
}
// Resolve the parent window object, if it's not already resolved
this._allTabs[i]._windowParent.properties.id = _tab.windowId;
this._allTabs[i]._windowParent.resolve(true);
// Also resolve window object's root tab manager
this._allTabs[i]._windowParent.tabs.resolve(true);
} else {
throw new OError('NoParent', 'BrowserTab object must have a parent window.');
}
// Rewrite tab properties (importantly, the id gets added here)
/*for(var j in _tab) {
if(j == 'url') continue;
this._allTabs[i].properties[j] = _tab[j];
}*/
// update oncreate tab properties
this._allTabs[i].properties.id = _tab.id;
this._allTabs[i].properties.index = _tab.index;
/*this._allTabs[i].properties.status = _tab.readyState;
this._allTabs[i].properties.title = _tab.title;
this._allTabs[i].properties.favIconUrl = _tab.favIconUrl;
this._allTabs[i].properties.incognito = _tab.incognito;
this._allTabs[i].properties.pinned = _tab.pinned;*/
// 'index' should be handled in shim
// now rewrite tab to the correct url
// (which will be automatically trigger navigation to the rewrite url)
// Resolve the tab object
this._allTabs[i].resolve(true);
// remove windowparent rewrite url
if(this._allTabs[i]._windowParent.rewriteUrl !== undefined) {
delete this._allTabs[i]._windowParent.rewriteUrl;
}
return;
}
// Standard tab search
if (this._allTabs[i].properties.id == _tab.id) {
tabFoundIndex = i;
break;
}
}
var newTab;
if (tabFoundIndex < 0) {
var parentWindow;
// find tab's parent window object via the window.rewriteURL property
var _windows = OEX.windows;
for (var i = 0, l = _windows.length; i < l; i++) {
// Bind the window object with its window id and resolve
if( _windows[i].rewriteUrl && _windows[i].rewriteUrl == _tab.url ) {
_windows[i].properties.id = _tab.windowId;
_windows[i].resolve(true);
// Also resolve window object's root tab manager
_windows[i].tabs.resolve(true);
}
if (_windows[i].properties.id !== undefined && _windows[i].properties.id == _tab.windowId) {
parentWindow = _windows[i];
break;
}
}
if (!parentWindow) {
// Create new BrowserWindow object
parentWindow = new BrowserWindow();
// write properties not available in BrowserWindow constructor
parentWindow.properties.id = _tab.windowId;
// Attach to windows collection
OEX.windows.addWindow(_tab.windowId, parentWindow);
parentWindow.resolve(true);
parentWindow.tabs.resolve(true);
// we really need to learn more about the newly create BrowserWindow object
chrome.windows.get(parentWindow.properties.id, { 'populate': false }, function(_window) {
// update window properties
for(var prop in _window) {
if(prop == 'tabs') continue;
parentWindow.properties[prop] = _window[prop];
}
}.bind(this));
}
// Replace first tab object with newTab
if(parentWindow.rewriteUrl && parentWindow.tabs.length > 0) {
newTab = parentWindow.tabs[0];
// rewrite the tab's properties
for(var j in _tab) {
newTab.properties[j] = _tab[j];
}
} else {
// Create the new BrowserTab object using the provided properties
newTab = new BrowserTab(_tab, parentWindow, true);
// write properties not available in BrowserTab constructor
newTab.properties.id = _tab.id;
newTab.properties.url = _tab.url;
newTab.properties.title = _tab.title;
newTab.properties.favIconUrl = _tab.favIconUrl;
newTab.properties.pinned = _tab.pinned;
newTab.properties.incognito = _tab.incognito;
newTab.properties.status = _tab.status;
newTab.properties.index = _tab.index;
if(_tab.active == true && newTab.properties.active == false) {
newTab.focus();
}
// Register the new BrowserTab object with a BrowserWindow's tabs collection
newTab._windowParent.tabs.addTab( newTab, newTab.properties.index );
// Add object to root store
this.addTab( newTab );
}
// Fire create events for a newly created BrowserTab object
newTab._windowParent.tabs.dispatchEvent(new OEvent('create', {
"tab": newTab,
"prevWindow": null,
"prevTabGroup": null,
"prevPosition": 0
}));
// Fire a create event at RootTabsManager
OEX.tabs.dispatchEvent(new OEvent('create', {
"tab": newTab,
"prevWindow": null,
"prevTabGroup": null,
"prevPosition": 0
}));
} else {
newTab = this[tabFoundIndex];
// Update existing tab properties
for(var i in _tab) {
if(i == 'url') continue;
newTab.properties[i] = _tab[i];
}
// update individual properties
//newTab.properties.id = _tab.id;
}
// remove window rewriteUrl since the bootstrap has now been used
if(newTab._windowParent.rewriteUrl !== undefined) {
delete newTab._windowParent.rewriteUrl;
}
// Resolve new tab, if it hasn't been resolved already
newTab.resolve(true);
// Queue.dequeue();
}.bind(this));
chrome.tabs.onRemoved.addListener(function(tabId, removeInfo) {
if( this._blackList[ tabId ] ) {
return;
}
// Remove tab from current collection
var deleteIndex = -1;
for (var i = 0, l = this._allTabs.length; i < l; i++) {
if (this._allTabs[i].properties.id == tabId) {
deleteIndex = i;
break;
}
}
if (deleteIndex < 0) {
return;
}
var oldTab = this._allTabs[deleteIndex];
var oldTabWindowParent = oldTab._oldWindowParent;
var oldTabPosition = oldTab._oldIndex || oldTab.properties.index;
// Detach from current parent BrowserWindow (if close happened outside of our framework)
if (!oldTabWindowParent && oldTab._windowParent !== undefined && oldTab._windowParent !== null) {
oldTab.properties.closed = true;
oldTab._windowParent.tabs.removeTab( oldTab );
// Remove tab from root tab manager
this.removeTab( oldTab );
// Focus new tab within the removed tab's window
for(var i = 0, l = oldTab._windowParent.tabs.length; i < l; i++) {
if(oldTab._windowParent.tabs[i].properties.active == true) {
oldTab._windowParent.tabs[i].focus();
} else {
oldTab._windowParent.tabs[i].properties.active = false;
}
}
oldTab.properties.index = NaN;
oldTabWindowParent = oldTab._windowParent;
oldTab._windowParent = null;
}
// Fire a new 'close' event on the closed BrowserTab object
oldTab.dispatchEvent(new OEvent('close', {
"tab": oldTab,
"prevWindow": oldTabWindowParent,
"prevTabGroup": null,
"prevPosition": oldTabPosition
}));
// Fire a new 'close' event on the closed BrowserTab's previous
// BrowserWindow parent object
if(oldTabWindowParent) {
oldTabWindowParent.tabs.dispatchEvent(new OEvent('close', {
"tab": oldTab,
"prevWindow": oldTabWindowParent,
"prevTabGroup": null,
"prevPosition": oldTabPosition
}));
}
// Fire a new 'close' event on this root tab manager object
this.dispatchEvent(new OEvent('close', {
"tab": oldTab,
"prevWindow": oldTabWindowParent,
"prevTabGroup": null,
"prevPosition": oldTabPosition
}));
// Queue.dequeue();
}.bind(this));
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
var updateIndex = -1;
for (var i = 0, l = this._allTabs.length; i < l; i++) {
if (this._allTabs[i].properties.id == tabId) {
updateIndex = i;
break;
}
}
if (updateIndex < 0) {
return; // nothing to update
}
var updateTab = this._allTabs[updateIndex];
if (tab.status == 'complete' && updateTab.rewriteUrl && updateTab.properties.url == tab.url) {
updateTab.properties.url = updateTab.rewriteUrl;
updateTab.properties.title = '';
updateTab.properties.favIconUrl = '';
updateTab.properties.status = 'loading';
delete updateTab.rewriteUrl;
Queue.enqueue(this, function(done) {
chrome.tabs.update(
updateTab.properties.id,
{ 'url': updateTab.properties.url },
function() {
done();
}.bind(this)
);
}.bind(this));
} else {
// Update individual tab properties
updateTab.properties.url = tab.url;
updateTab.properties.title = tab.title;
updateTab.properties.favIconUrl = tab.favIconUrl;
updateTab.properties.status = tab.status;
updateTab.properties.pinned = tab.pinned;
updateTab.properties.incognito = tab.incognito;
updateTab.properties.index = tab.index;
if(tab.active == true && updateTab.properties.active == false) {
updateTab.focus();
}
}
// Queue.dequeue();
}.bind(this));
function moveHandler(tabId, moveInfo) {
if( this._blackList[ tabId ] ) {
return;
}
// find tab's parent window object via the window.rewriteURL property
// and rewrite it's id value
var _windows = OEX.windows;
for (var i = 0, l = _windows.length; i < l; i++) {
// Bind the window object with its window id and resolve
if( _windows[i].rewriteUrl && _windows[i].rewriteUrl == newTab_BaseURL.replace('%s', tabId) ) {
_windows[i].properties.id = moveInfo.windowId;
_windows[i].resolve(true);
// Also resolve window object's root tab manager
_windows[i].tabs.resolve(true);
delete _windows[i].rewriteUrl;
}
}
// Find tab object
var moveIndex = -1;
for (var i = 0, l = this._allTabs.length; i < l; i++) {
if (this._allTabs[i].properties.id == tabId) {
moveIndex = i;
break;
}
}
if (moveIndex < 0) {
return; // nothing to update
}
var moveTab = this._allTabs[moveIndex];
if(moveTab) {
// Remove and re-add to BrowserTabManager parent in the correct position
if(moveTab._oldWindowParent) {
moveTab._oldWindowParent.tabs.removeTab( moveTab );
} else {
moveTab._windowParent.tabs.removeTab( moveTab );
}
// Update index
moveTab.properties.index = moveInfo.toIndex;
moveTab._windowParent.tabs.addTab( moveTab, moveInfo.toIndex );
moveTab.dispatchEvent(new OEvent('move', {
"tab": moveTab,
"prevWindow": moveTab._oldWindowParent,
"prevTabGroup": null,
"prevPosition": moveTab._oldIndex
}));
this.dispatchEvent(new OEvent('move', {
"tab": moveTab,
"prevWindow": moveTab._oldWindowParent,
"prevTabGroup": null,
"prevPosition": moveTab._oldIndex
}));
// Clean up temporary attributes
if(moveTab._oldWindowParent !== undefined) {
delete moveTab._oldWindowParent;
}
if(moveTab._oldIndex !== undefined) {
delete moveTab._oldIndex;
}
}
// Queue.dequeue();
}
function attachHandler(tabId, attachInfo) {
// Find tab object
var attachIndex = -1;
for (var i = 0, l = this._allTabs.length; i < l; i++) {
if (this._allTabs[i].properties.id == tabId) {
attachIndex = i;
break;
}
}
if (attachIndex < 0) {
return; // nothing to update
}
var attachedTab = this._allTabs[attachIndex];
// Detach tab from existing BrowserWindow parent (if any)
if (attachedTab._oldWindowParent) {
attachedTab._oldWindowParent.tabs.removeTab( attachedTab );
}
// Wait for new window to be created and attached!
//global.setTimeout(function() {
// Attach tab to new BrowserWindow parent
for (var i = 0, l = OEX.windows.length; i < l; i++) {
if (OEX.windows[i].properties.id == attachInfo.newWindowId) {
// Reassign attachedTab's _windowParent
attachedTab._windowParent = OEX.windows[i];
// Tab will be added in the moveHandler function
break;
}
}
var moveInfo = {
windowId: attachInfo.newWindowId,
//fromIndex: null,
toIndex: attachInfo.newPosition
};
// Execute normal move handler
moveHandler.bind(this).call(this, tabId, moveInfo);
//}.bind(this), 200);
}
function detachHandler(tabId, detachInfo) {
// Find tab object
var detachIndex = -1;
for (var i = 0, l = this._allTabs.length; i < l; i++) {
if (this._allTabs[i].properties.id == tabId) {
detachIndex = i;
break;
}
}
if (detachIndex < 0) {
return; // nothing to update
}
var detachedTab = this._allTabs[detachIndex];
if(detachedTab) {
detachedTab._oldWindowParent = detachedTab._windowParent;
detachedTab._oldIndex = detachedTab.position;
}
// Queue.dequeue();
}
// Fired when a tab is moved within a window
chrome.tabs.onMoved.addListener(moveHandler.bind(this));
// Fired when a tab is moved between windows
chrome.tabs.onAttached.addListener(attachHandler.bind(this));
// Fired when a tab is removed from an existing window
chrome.tabs.onDetached.addListener(detachHandler.bind(this));
chrome.tabs.onActivated.addListener(function(activeInfo) {
if( this._blackList[ activeInfo.tabId ] ) {
return;
}
if(!activeInfo.tabId) return;
var blurTarget, focusTarget;
for(var i = 0, l = this._allTabs.length; i < l; i++) {
if(this._allTabs[i].properties.id == activeInfo.tabId) {
// Set BrowserTab object to active state
this._allTabs[i].properties.active = true;
// Fire focus event on tab's manager
focusTarget = this._allTabs[i];
if(this._allTabs[i]._windowParent) {
// unset active state of all other tabs in this collection
for(var j = 0, k = this._allTabs[i]._windowParent.tabs.length; j < k; j++) {
if(this._allTabs[i]._windowParent.tabs[j] !== this._allTabs[i]) {
if(this._allTabs[i]._windowParent.tabs[j].properties.active == true) {
blurTarget = this._allTabs[i]._windowParent.tabs[j];
}
this._allTabs[i]._windowParent.tabs[j].properties.active = false;
}
}
}
}
}
// Fire blur event
if(focusTarget) {
OEX.tabs.dispatchEvent( new OEvent('blur', {
"tab": focusTarget,
"prevWindow": focusTarget._windowParent, // same as current window
"prevTabGroup": null,
"prevPosition": focusTarget.properties.index
}) );
}
// Fire focus event
if(blurTarget) {
OEX.tabs.dispatchEvent( new OEvent('focus', {
"tab": blurTarget,
"prevWindow": blurTarget._windowParent, // same as current window
"prevTabGroup": null,
"prevPosition": blurTarget.properties.index
}) );
}
// Queue.dequeue();
}.bind(this));
// Listen for getScreenshot requests from Injected Scripts
OEX.addEventListener('controlmessage', function( msg ) {
if( !msg.data || !msg.data.action || msg.data.action !== '___O_getScreenshot_REQUEST' || !msg.source.tabId ) {
return;
}
// Resolve tabId to BrowserTab object
var sourceBrowserTab = null
for(var i = 0, l = this._allTabs.length; i < l; i++) {
if( this._allTabs[ i ].properties.id == msg.source.tabId ) {
sourceBrowserTab = this._allTabs[ i ];
break;
}
}
if( sourceBrowserTab !== null &&
sourceBrowserTab._windowParent &&
sourceBrowserTab._windowParent.properties.closed != true ) {
try {
// Get screenshot of requested window belonging to current tab
chrome.tabs.captureVisibleTab(
sourceBrowserTab._windowParent.properties.id,
{},
function( nativeCallback ) {
// Return the result to the callee
msg.source.postMessage({
"action": "___O_getScreenshot_RESPONSE",
"dataUrl": nativeCallback || null
});
}.bind(this)
);
} catch(e) {}
} else {
msg.source.postMessage({
"action": "___O_getScreenshot_RESPONSE",
"dataUrl": undefined
});
}
}.bind(this));
};
RootBrowserTabManager.prototype = Object.create( BrowserTabManager.prototype );
// Make sure .__proto__ object gets setup correctly
for(var i in BrowserTabManager.prototype) {
if(BrowserTabManager.prototype.hasOwnProperty(i)) {
RootBrowserTabManager.prototype[i] = BrowserTabManager.prototype[i];
}
}
var BrowserTab = function(browserTabProperties, windowParent, bypassRewriteUrl) {
if(!windowParent) {
throw new OError('Parent missing', 'BrowserTab objects can only be created with a window parent provided');
}
OPromise.call(this);
this._windowParent = windowParent;
browserTabProperties = browserTabProperties || {};
// Set the correct tab index
var tabIndex = 0;
if(browserTabProperties.position !== undefined &&
browserTabProperties.position !== null &&
parseInt(browserTabProperties.position, 10) >= 0) {
tabIndex = parseInt(browserTabProperties.position, 10);
} else if(windowParent && windowParent.tabs) {
tabIndex = windowParent.tabs.length;
}
this.properties = {
'id': undefined, // not settable on create
'closed': false, // not settable on create
// locked:
'pinned': browserTabProperties.locked ? !!browserTabProperties.locked : false,
// private:
'incognito': false, // TODO handle private tab creation in Chromium model
// selected:
'active': browserTabProperties.focused ? !!browserTabProperties.focused : false,
// readyState:
'status': 'loading', // not settable on create
// faviconUrl:
'favIconUrl': '', // not settable on create
'title': '', // not settable on create
'url': browserTabProperties.url ? (browserTabProperties.url + "") : 'about:blank',
// position:
'index': tabIndex
// 'browserWindow' not part of settable properties
// 'tabGroup' not part of settable properties
}
// Create a unique browserTab id
this._operaId = Math.floor(Math.random() * 1e16);
// Pass the identity of this tab through the Chromium Tabs API via the URL field
if(!bypassRewriteUrl) {
this.rewriteUrl = this.properties.url;
this.properties.url = newTab_BaseURL.replace('%s', this._operaId)
}
// Set tab focused if active
if(this.properties.active == true) {
this.focus();
}
// Add this object to the permanent management collection
OEX.tabs._allTabs.push( this );
};
BrowserTab.prototype = Object.create(OPromise.prototype);
// API
BrowserTab.prototype.__defineGetter__("id", function() {
return this._operaId;
}); // read-only
BrowserTab.prototype.__defineGetter__("closed", function() {
return this.properties.closed !== undefined ? !!this.properties.closed : false;
}); // read-only
BrowserTab.prototype.__defineGetter__("locked", function() {
return this.properties.pinned !== undefined ? !!this.properties.pinned : false;
}); // read-only
BrowserTab.prototype.__defineGetter__("focused", function() {
return this.properties.active !== undefined ? !!this.properties.active : false;
}); // read
BrowserTab.prototype.__defineSetter__("focused", function(val) {
this.properties.active = !!val;
if(this.properties.active == true) {
this.focus();
}
}); // write
BrowserTab.prototype.__defineGetter__("selected", function() {
return this.properties.active !== undefined ? !!this.properties.active : false;
}); // read
BrowserTab.prototype.__defineSetter__("selected", function(val) {
this.properties.active = !!val;
if(this.properties.active == true) {
this.focus();
}
}); // write
BrowserTab.prototype.__defineGetter__("private", function() {
return this.properties.incognito !== undefined ? !!this.properties.incognito : false;
}); // read-only
BrowserTab.prototype.__defineGetter__("faviconUrl", function() {
if (this.properties.closed) {
return "";
}
return this.properties.favIconUrl || "";
}); // read-only
BrowserTab.prototype.__defineGetter__("title", function() {
if (this.properties.closed) {
return "";
}
return this.properties.title || "";
}); // read-only
BrowserTab.prototype.__defineGetter__("url", function() {
if (this.properties.closed) {
return "";
}
// URL rewrite hack
if (this.rewriteUrl) {
return this.rewriteUrl;
}
return this.properties.url || "";
}); // read-only
BrowserTab.prototype.__defineSetter__("url", function(val) {
this.properties.url = val + "";
Queue.enqueue(this, function(done) {
chrome.tabs.update(
this.properties.id,
{ 'url': this.properties.url },
function(_tab) {
done();
}.bind(this)
);
}.bind(this));
});
BrowserTab.prototype.__defineGetter__("readyState", function() {
return this.properties.status !== undefined ? this.properties.status : "loading";
});
BrowserTab.prototype.__defineGetter__("browserWindow", function() {
return this._windowParent;
});
BrowserTab.prototype.__defineGetter__("tabGroup", function() {
// not implemented
return null;
});
BrowserTab.prototype.__defineGetter__("position", function() {
return this.properties.index !== undefined ? this.properties.index : NaN;
});
// Methods
BrowserTab.prototype.focus = function() {
if(this.properties.active == true || this.properties.closed == true) {
return; // already focused or invalid because tab is closed
}
// Set BrowserTab object to active state
this.properties.active = true;
if(this._windowParent) {
// unset active state of all other tabs in this collection
for(var i = 0, l = this._windowParent.tabs.length; i < l; i++) {
if(this._windowParent.tabs[i] !== this) {
this._windowParent.tabs[i].properties.active = false;
}
}
}
// Queue platform action or fire immediately if this object is resolved
Queue.enqueue(this, function(done) {
chrome.tabs.update(
this.properties.id,
{ active: true },
function() {
done();
}.bind(this)
);
}.bind(this));
};
BrowserTab.prototype.update = function(browserTabProperties) {
if( this.properties.closed == true ) {
throw new OError(
"InvalidStateError",
"The current BrowserTab object is closed. Cannot call 'update' on this object.",
DOMException.INVALID_STATE_ERR
);
}
if( isObjectEmpty(browserTabProperties || {}) ) {
throw new OError(
'TypeMismatchError',
'You must provide some valid properties to update a BrowserTab object',
DOMException.TYPE_MISMATCH_ERR
);
}
var updateProperties = {};
// Cannot set focused = false in update
if(browserTabProperties.focused !== undefined && browserTabProperties.focused == true) {
this.properties.active = updateProperties.active = !!browserTabProperties.focused;
// unset active parameter of all other objects
if(this._windowParent) {
for(var i = 0, l = this._windowParent.tabs.length; i < l; i++) {
if(this._windowParent.tabs[i] != this) {
this._windowParent.tabs[i].properties.active = false;
}
}
}
}
if(browserTabProperties.locked !== undefined && browserTabProperties.locked !== null) {
this.properties.pinned = updateProperties.pinned = !!browserTabProperties.locked;
}
if(browserTabProperties.url !== undefined && browserTabProperties.url !== null) {
if(this.rewriteUrl) {
this.rewriteUrl = updateProperties.url = browserTabProperties.url;
} else {
this.properties.url = updateProperties.url = browserTabProperties.url;
}
}
if( !isObjectEmpty(updateProperties) ) {
// Queue platform action or fire immediately if this object is resolved
Queue.enqueue(this, function(done) {
chrome.tabs.update(
this.properties.id,
updateProperties,
function(_tab) {
done();
}.bind(this)
);
}.bind(this));
}
};
BrowserTab.prototype.refresh = function() {
// Cannot refresh if the tab is in the closed state
if(this.properties.closed === true) {
return;
}
// reload by resetting the URL
//this.properties.status = "loading";
//this.properties.title = undefined;
Queue.enqueue(this, function(done) {
// reset the readyState + title
this.properties.status = "loading";
this.properties.title = undefined;
chrome.tabs.reload(
this.properties.id,
{ bypassCache: true },
function() {
done();
}.bind(this)
);
}.bind(this));
};
// Web Messaging support for BrowserTab objects
BrowserTab.prototype.postMessage = function( postData ) {
// Cannot send messages if tab is in the closed state
if(this.properties.closed === true) {
throw new OError(
"InvalidStateError",
"The current BrowserTab object is in the closed state and therefore is invalid.",
DOMException.INVALID_STATE_ERR
);
}
// Queue platform action or fire immediately if this object is resolved
Queue.enqueue(this, function(done) {
chrome.tabs.sendMessage(
this.properties.id,
postData,
function() {
done();
}.bind(this)
);
}.bind(this));
};
// Screenshot API support for BrowserTab objects
BrowserTab.prototype.getScreenshot = function( callback ) {
// Cannot get a screenshot if tab is in the closed state
if(this.properties.closed === true) {
throw new OError(
"InvalidStateError",
"The current BrowserTab object is in the closed state and therefore is invalid.",
DOMException.INVALID_STATE_ERR
);
}
if( !this._windowParent || this._windowParent.properties.closed === true) {
callback.call( this, undefined );
return;
}
try {
// Queue platform action or fire immediately if this object is resolved
Queue.enqueue(this, function(done) {
chrome.tabs.captureVisibleTab(
this._windowParent.properties.id,
{},
function( nativeCallback ) {
if( nativeCallback ) {
// Convert the returned dataURL in to an ImageData object and
// return via the main callback function argument
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
ctx.drawImage(img,0,0);
var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
// Return the ImageData object to the callee
callback.call( this, imageData );
}.bind(this);
img.src = nativeCallback;
} else {
callback.call( this, undefined );
}
done();
}.bind(this)
);
}.bind(this));
} catch(e) {}
};
BrowserTab.prototype.close = function() {
if(this.properties.closed == true) {
/*throw new OError(
"InvalidStateError",
"The current BrowserTab object is already closed. Cannot call 'close' on this object.",
DOMException.INVALID_STATE_ERR
);*/
return;
}
// Cannot close pinned tab
if(this.properties.pinned == true) {
return;
}
// Set BrowserTab object to closed state
this.properties.closed = true;
this.properties.active = false;
// Detach from parent window
this._oldWindowParent = this._windowParent;
//this._windowParent = null;
// Remove index
this._oldIndex = this.properties.index;
this.properties.index = undefined;
// Remove tab from current collection
if(this._oldWindowParent) {
this._oldWindowParent.tabs.removeTab( this );
}
// Remove tab from global collection
OEX.tabs.removeTab( this );
// Queue platform action or fire immediately if this object is resolved
Queue.enqueue(this, function(done) {
if(!this.properties.id) return;
chrome.tabs.remove(
this.properties.id,
function() {
done();
}.bind(this)
);
}.bind(this));
};
var BrowserTabGroupManager = function( parentObj ) {
OEventTarget.call(this);
this._parent = parentObj;
// Set up 0 mock BrowserTabGroup objects at startup
this.length = 0;
};
BrowserTabGroupManager.prototype = Object.create( OEventTarget.prototype );
BrowserTabGroupManager.prototype.create = function() {
// When this feature is not supported in the current user agent then we must
// throw a NOT_SUPPORTED_ERR as per the full Opera WinTabs API specification.
throw new OError(
"NotSupportedError",
"The current user agent does not support the Tab Groups feature.",
DOMException.NOT_SUPPORTED_ERR
);
};
BrowserTabGroupManager.prototype.getAll = function() {
return []; // always empty
};
if(manifest && manifest.permissions && manifest.permissions.indexOf('tabs') != -1) {
OEX.windows = OEX.windows || new BrowserWindowManager();
} else {
// Set WinTabs feature to LOADED
deferredComponentsLoadStatus['WINTABS_LOADED'] = true;
}
if(manifest && manifest.permissions && manifest.permissions.indexOf('tabs') != -1) {
OEX.tabs = OEX.tabs || new RootBrowserTabManager();
} else {
// Set WinTabs feature to LOADED
deferredComponentsLoadStatus['WINTABS_LOADED'] = true;
}
if(manifest && manifest.permissions && manifest.permissions.indexOf('tabs') != -1) {
OEX.tabGroups = OEX.tabGroups || new BrowserTabGroupManager();
}
var ToolbarContext = function() {
OEventTarget.call( this );
this.length = 0;
// Unfortunately, click events only fire if a popup is not supplied
// to a registered browser action in Chromium :(
// http://stackoverflow.com/questions/1938356/chrome-browser-action-click-not-working
//
// TODO also invoke clickEventHandler function when a popup page loads
function clickEventHandler(_tab) {
if( this[ 0 ] ) {
this[ 0 ].dispatchEvent( new OEvent('click', {}) );
}
// Fire event also on ToolbarContext API stub
this.dispatchEvent( new OEvent('click', {}) );
}
chrome.browserAction.onClicked.addListener(clickEventHandler.bind(this));
};
ToolbarContext.prototype = Object.create( OEventTarget.prototype );
ToolbarContext.prototype.createItem = function( toolbarUIItemProperties ) {
return new ToolbarUIItem( toolbarUIItemProperties );
};
ToolbarContext.prototype.addItem = function( toolbarUIItem ) {
if( !toolbarUIItem || !toolbarUIItem instanceof ToolbarUIItem ) {
return;
}
this[ 0 ] = toolbarUIItem;
this.length = 1;
toolbarUIItem.resolve(true);
toolbarUIItem.apply();
toolbarUIItem.badge.resolve(true);
toolbarUIItem.badge.apply();
toolbarUIItem.popup.resolve(true);
toolbarUIItem.popup.apply();
};
ToolbarContext.prototype.removeItem = function( toolbarUIItem ) {
if( !toolbarUIItem || !toolbarUIItem instanceof ToolbarUIItem ) {
return;
}
if( this[ 0 ] && this[ 0 ] === toolbarUIItem ) {
delete this[ 0 ];
this.length = 0;
// Disable the toolbar button
chrome.browserAction.disable();
toolbarUIItem.dispatchEvent( new OEvent('remove', {}) );
// Fire event on self
this.dispatchEvent( new OEvent('remove', {}) );
}
};
var ToolbarBadge = function( properties ) {
OPromise.call( this );
this.properties = {};
// Set provided properties through object prototype setter functions
this.properties.textContent = properties.textContent ? "" + properties.textContent : properties.textContent;
this.properties.backgroundColor = complexColorToHex(properties.backgroundColor);
this.properties.color = complexColorToHex(properties.color);
this.properties.display = String(properties.display).toLowerCase() === 'none' ? 'none' : 'block';
};
ToolbarBadge.prototype = Object.create( OPromise.prototype );
ToolbarBadge.prototype.apply = function() {
chrome.browserAction.setBadgeBackgroundColor({ "color": (this.backgroundColor || "#f00") });
if( this.display === "block" ) {
chrome.browserAction.setBadgeText({ "text": this.textContent || "" });
} else {
chrome.browserAction.setBadgeText({ "text": "" });
}
};
// API
ToolbarBadge.prototype.__defineGetter__("textContent", function() {
return this.properties.textContent;
});
ToolbarBadge.prototype.__defineSetter__("textContent", function( val ) {
this.properties.textContent = "" + val;
if( this.properties.display === "block" ) {
Queue.enqueue(this, function(done) {
chrome.browserAction.setBadgeText({ "text": ("" + val) });
done();
}.bind(this));
}
});
ToolbarBadge.prototype.__defineGetter__("backgroundColor", function() {
return this.properties.backgroundColor;
});
ToolbarBadge.prototype.__defineSetter__("backgroundColor", function( val ) {
this.properties.backgroundColor = complexColorToHex(val);
Queue.enqueue(this, function(done) {
chrome.browserAction.setBadgeBackgroundColor({ "color": this.properties.backgroundColor });
done();
}.bind(this));
});
ToolbarBadge.prototype.__defineGetter__("color", function() {
return this.properties.color;
});
ToolbarBadge.prototype.__defineSetter__("color", function( val ) {
this.properties.color = complexColorToHex(val);
// not implemented in chromium
});
ToolbarBadge.prototype.__defineGetter__("display", function() {
return this.properties.display;
});
ToolbarBadge.prototype.__defineSetter__("display", function( val ) {
if(("" + val).toLowerCase() === "none") {
this.properties.display = "none";
Queue.enqueue(this, function(done) {
chrome.browserAction.setBadgeText({ "text": "" });
done();
}.bind(this));
}
else {
this.properties.display = "block";
Queue.enqueue(this, function(done) {
chrome.browserAction.setBadgeText({ "text": this.properties.textContent });
done();
}.bind(this));
}
});
var ToolbarPopup = function( properties ) {
OPromise.call( this );
this.properties = {
href: "",
width: 300,
height: 300
};
// internal properties
this.isExternalHref = false;
this.href = properties.href;
this.width = properties.width;
this.height = properties.height;
this.applyHrefVal = function() {
// If href points to a http or https resource we need to load it via an iframe
if(this.isExternalHref === true) {
return "/oex_shim/popup_resourceloader.html?href=" + global.btoa(this.properties.href) +
"&w=" + this.properties.width + "&h=" + this.properties.height;
}
return this.properties.href + (this.properties.href.indexOf('?') > 0 ? '&' : '?' ) +
"w=" + this.properties.width + "&h=" + this.properties.height;
};
};
ToolbarPopup.prototype = Object.create( OPromise.prototype );
ToolbarPopup.prototype.apply = function() {
if(this.properties.href && this.properties.href !== "undefined" && this.properties.href !== "null" && this.properties.href !== "") {
chrome.browserAction.setPopup({ "popup": this.applyHrefVal() });
} else {
chrome.browserAction.setPopup({ "popup": "" });
}
};
// API
ToolbarPopup.prototype.__defineGetter__("href", function() {
return this.properties.href;
});
ToolbarPopup.prototype.__defineSetter__("href", function( val ) {
val = val + ""; // force to type string
// Check if we have an external href path
if(val.match(/^(https?:\/\/|data:)/)) {
this.isExternalHref = true;
} else {
this.isExternalHref = false;
}
this.properties.href = val;
if(this.properties.href && this.properties.href !== "undefined" && this.properties.href !== "null" && this.properties.href !== "") {
Queue.enqueue(this, function(done) {
chrome.browserAction.setPopup({ "popup": this.applyHrefVal() });
done();
}.bind(this));
} else {
chrome.browserAction.setPopup({ "popup": "" });
}
});
ToolbarPopup.prototype.__defineGetter__("width", function() {
return this.properties.width;
});
ToolbarPopup.prototype.__defineSetter__("width", function( val ) {
val = (val + "").replace(/\D/g, '');
if(val == '') {
this.properties.width = 300; // default width
} else {
this.properties.width = val < 800 ? val : 800; // enforce max width
}
if(this.properties.href && this.properties.href !== "undefined" && this.properties.href !== "null" && this.properties.href !== "") {
Queue.enqueue(this, function(done) {
chrome.browserAction.setPopup({ "popup": this.applyHrefVal() });
done();
}.bind(this));
} else {
chrome.browserAction.setPopup({ "popup": "" });
}
});
ToolbarPopup.prototype.__defineGetter__("height", function() {
return this.properties.height;
});
ToolbarPopup.prototype.__defineSetter__("height", function( val ) {
val = (val + "").replace(/\D/g, '');
if(val == '') {
this.properties.height = 300; // default height
} else {
this.properties.height = val < 600 ? val : 600; // enforce max height
}
if(this.properties.href && this.properties.href !== "undefined" && this.properties.href !== "null" && this.properties.href !== "") {
Queue.enqueue(this, function(done) {
chrome.browserAction.setPopup({ "popup": this.applyHrefVal() });
done();
}.bind(this));
} else {
chrome.browserAction.setPopup({ "popup": "" });
}
});
var ToolbarUIItem = function( properties ) {
OPromise.call( this );
this.properties = {};
this.properties.disabled = properties.disabled || false;
this.properties.title = properties.title || "";
this.properties.icon = properties.icon || "";
this.properties.popup = new ToolbarPopup( properties.popup || {} );
this.properties.badge = new ToolbarBadge( properties.badge || {} );
if(properties.onclick){this.onclick = properties.onclick;}
if(properties.onremove){this.onremove = properties.onremove;}
};
ToolbarUIItem.prototype = Object.create( OPromise.prototype );
ToolbarUIItem.prototype.apply = function() {
// Apply title property
chrome.browserAction.setTitle({ "title": this.title });
// Apply icon property
if(this.icon) {
chrome.browserAction.setIcon({ "path": this.icon });
}
// Apply disabled property
if( this.disabled === true ) {
chrome.browserAction.disable();
} else {
chrome.browserAction.enable();
}
};
// API
ToolbarUIItem.prototype.__defineGetter__("disabled", function() {
return this.properties.disabled;
});
ToolbarUIItem.prototype.__defineSetter__("disabled", function( val ) {
if( this.properties.disabled !== val ) {
if( val === true || val === "true" || val === 1 || val === "1" ) {
this.properties.disabled = true;
Queue.enqueue(this, function(done) {
chrome.browserAction.disable();
done();
}.bind(this));
} else {
this.properties.disabled = false;
Queue.enqueue(this, function(done) {
chrome.browserAction.enable();
done();
}.bind(this));
}
}
});
ToolbarUIItem.prototype.__defineGetter__("title", function() {
return this.properties.title;
});
ToolbarUIItem.prototype.__defineSetter__("title", function( val ) {
this.properties.title = "" + val;
Queue.enqueue(this, function(done) {
chrome.browserAction.setTitle({ "title": this.title });
done();
}.bind(this));
});
ToolbarUIItem.prototype.__defineGetter__("icon", function() {
return this.properties.icon;
});
ToolbarUIItem.prototype.__defineSetter__("icon", function( val ) {
this.properties.icon = "" + val;
Queue.enqueue(this, function(done) {
chrome.browserAction.setIcon({ "path": this.icon });
done();
}.bind(this));
});
ToolbarUIItem.prototype.__defineGetter__("popup", function() {
return this.properties.popup;
});
ToolbarUIItem.prototype.__defineGetter__("badge", function() {
return this.properties.badge;
});
if(manifest && manifest.browser_action !== undefined && manifest.browser_action !== null ) {
OEC.toolbar = OEC.toolbar || new ToolbarContext();
}
var MenuEvent = function(type, args, target) {
var event;
if (type == 'click') {
var tab = null;
var tabs = OEX.tabs.getAll();
for (var i = 0; i < tabs.length; i++) {
if (tabs[i].properties.id == args.tab.id &&
tabs[i].browserWindow.properties.id == args.tab.windowId) tab = tabs[i];
};
event = OEvent(type, {
documentURL: args.info.pageUrl,
pageURL: args.info.pageUrl,
isEditable: args.info.editable,
linkURL: args.info.linkUrl || null,
mediaType: args.info.mediaType || null,
selectionText: args.info.selectionText || null,
source: tab,
//tab.port should be implemented
srcURL: args.info.srcUrl || null
});
} else event = OEvent(type, args);
Object.defineProperty(event, 'target', {
enumerable: true,
get: function() {
return target || null;
},
set: function(value) {}
});
return event;
};
MenuEvent.prototype = Object.create(Event.prototype);
var MenuEventTarget = function() {
var that = this;
var target = {};
EventTarget.mixin(target);
var onclick = null;
Object.defineProperty(this, 'onclick', {
enumerable: true,
configurable: false,
get: function() {
return onclick;
},
set: function(value) {
if (onclick != null) this.removeEventListener('click', onclick, false);
onclick = value;
if (onclick != null && onclick instanceof Function) this.addEventListener('click', onclick, false);
else onclick = null;
}
});
Object.defineProperty(this, 'dispatchEvent', {
enumerable: false,
configurable: false,
writable: false,
value: function(event) {
var currentTarget = this;
var stoppedImmediatePropagation = false;
Object.defineProperty(event, 'currentTarget', {
enumerable: true,
configurable: false,
get: function() {
return currentTarget;
},
set: function(value) {}
});
Object.defineProperty(event, 'stopImmediatePropagation', {
enumerable: true,
configurable: false,
writable: false,
value: function() {
stoppedImmediatePropagation = true;
}
});
var allCallbacks = callbacksFor(target),
callbacks = allCallbacks[event.type],
callbackTuple, callback, binding;
if (callbacks) for (var i = 0, l = callbacks.length; i < l; i++) {
callbackTuple = callbacks[i];
callback = callbackTuple[0];
binding = callbackTuple[1];
if (!stoppedImmediatePropagation) callback.call(binding, event);
};
}
});
Object.defineProperty(this, 'addEventListener', {
enumerable: true,
configurable: false,
writable: false,
value: function(eventName, callback, useCapture) {
target.on(eventName, callback, this); // no useCapture
}
});
Object.defineProperty(this, 'removeEventListener', {
enumerable: true,
configurable: false,
writable: false,
value: function(eventName, callback, useCapture) {
target.off(eventName, callback, this); // no useCapture
}
});
};
var OMenuContext = function(internal) {
if (internal !== Opera) { //only internal creations
throw new OError("NotSupportedError", "NOT_SUPPORTED_ERR", DOMException.NOT_SUPPORTED_ERR);
return;
};
MenuEventTarget.call(this);
var length = 0;
Object.defineProperty(this, 'length', {
enumerable: true,
get: function() {
return length;
},
set: function(value) {}
});
function toUint32(value) {
value = Number(value);
value = value < 0 ? Math.ceil(value) : Math.floor(value);
return value - Math.floor(value / Math.pow(2, 32)) * Math.pow(2, 32);
};
Object.defineProperty(this, 'addItem', {
enumerable: true,
value: function(menuItem, before) {
//too many items
if (this instanceof MenuContext && this.length > 0) {
throw new OError("NotSupportedError", "NOT_SUPPORTED_ERR", DOMException.NOT_SUPPORTED_ERR);
return;
};
//no item to add
if (!menuItem || !(menuItem instanceof MenuItem)) {
throw new OError("TypeMismatchError", "TYPE_MISMATCH_ERR", DOMException.TYPE_MISMATCH_ERR);
return;
}
//adding only for folders
if (this instanceof MenuItem && this.type != 'folder') {
throw new OError("TypeMismatchError", "TYPE_MISMATCH_ERR", DOMException.TYPE_MISMATCH_ERR);
return;
};
if (Array.prototype.indexOf.apply(this, [menuItem]) != -1) return; //already exist
//same parent check
if (before === undefined || this instanceof MenuContext) before = this.length;
else if (before instanceof MenuItem) {
var index = Array.prototype.indexOf.apply(this, [before]);
if (before.parent != this || index == -1) {
throw new OError("HierarchyRequestError", "HIERARCHY_REQUEST_ERR", DOMException.HIERARCHY_REQUEST_ERR);
return;
} else before = index;
} else if (before === null) before = this.length;
else before = toUint32(before);
if (isNaN(before)) before = 0;
//loop check
var parent = this;
var noLoop = false;
while (!noLoop) {
if (parent instanceof MenuContext || parent == null) noLoop = true;
else if (parent === menuItem) {
throw new OError("HierarchyRequestError", "HIERARCHY_REQUEST_ERR", DOMException.HIERARCHY_REQUEST_ERR);
return;
} else parent = parent.parent;
};
Array.prototype.splice.apply(this, [before, 0, menuItem]);
length = length + 1;
if (this instanceof MenuContext) menuItem.dispatchEvent(new MenuEvent('change', {
properties: {
parent: this
}
}, menuItem));
else this.dispatchEvent(new MenuEvent('change', {
properties: {
parent: this
}
}, menuItem));
}
});
Object.defineProperty(this, 'removeItem', {
enumerable: true,
value: function(index) {
if (index === undefined) {
throw new OError("TypeMismatchError", "TYPE_MISMATCH_ERR", DOMException.TYPE_MISMATCH_ERR);
return;
};
if (index < 0 || index >= length || this[index] == undefined) return;
this[index].dispatchEvent(new MenuEvent('change', {
properties: {
parent: null
}
}, this[index]));
Array.prototype.splice.apply(this, [index, 1]);
length = length - 1;
}
});
Object.defineProperty(this, 'item', {
enumerable: true,
value: function(index) {
return this[index] || null;
}
});
};
OMenuContext.prototype = Object.create(MenuEventTarget.prototype);
var MenuItemProperties = function(obj, initial) {
var lock = false;
var menuItemId = null;
var properties = {
id: "",
type: "entry",
contexts: ["page"],
disabled: false,
title: "",
icon: "",
documentURLPatterns: null,
targetURLPatterns: null,
parent: null
};
var allowedContexts = ["all", "page", "frame", "selection", "link", "editable", "image", "video", "audio"];
var changed = function() {
if (!lock) obj.dispatchEvent(new MenuEvent('change', {}, obj));
}
var update = function(props) {
if (lock) return;
lock = true;
if (props != undefined) for (var name in props) if (properties[name] !== undefined) {
if (name === "type") {
if (["entry", "folder", "line"].indexOf(String(props.type).toLowerCase()) != -1) properties.type = String(props.type);
} else if (name === "parent") {
if (props.parent === null || props.parent instanceof OMenuContext) properties.parent = props.parent;
else throw new TypeError();
} else if (name === "id") properties.id = String(props.id);
else obj[name] = props[name];
};
lock = false;
//update
if (properties.parent == null || (properties.parent instanceof MenuItem && properties.parent.menuItemId == null)) {
if (menuItemId != null) {
chrome.contextMenus.remove(menuItemId);
menuItemId = null;
};
} else if (properties.disabled == true) {
if (menuItemId != null) {
chrome.contextMenus.remove(menuItemId);
menuItemId = null;
};
} else {
var updateProperties = {
title: properties.title.length == 0 ? chrome.app.getDetails().name : properties.title,
type: properties.type.toLowerCase() == "line" ? "separator" : "normal" //"normal", "checkbox", "radio", "separator"
};
var contexts = properties.contexts.join(',').toLowerCase().split(',').filter(function(element) {
return allowedContexts.indexOf(element.toLowerCase()) != -1;
});
if (contexts.length == 0) updateProperties.contexts = ["page"];
else updateProperties.contexts = contexts;
if (properties.parent instanceof MenuItem && properties.parent.menuItemId != null) {
updateProperties.parentId = properties.parent.menuItemId;
};
if (menuItemId == null) {
if (properties.id != "") updateProperties.id = properties.id; //set id
menuItemId = chrome.contextMenus.create(updateProperties);
} else chrome.contextMenus.update(menuItemId, updateProperties);
/* unsafe code
if(
this.properties.parent instanceof MenuContext && this.properties.icon.length>0 //has icon
&& !(chrome.app.getDetails().icons && chrome.app.getDetails().icons[16]) // no global 16x16 icon
){//set custom root icon
chrome.browserAction.setIcon({path: this.properties.icon });
};
*/
};
};
var nosetter = function(value) {};
Object.defineProperty(obj, 'id', {
enumerable: true,
get: function() {
return properties.id;
},
set: nosetter
});
Object.defineProperty(obj, 'type', {
enumerable: true,
get: function() {
return properties.type;
},
set: nosetter
});
Object.defineProperty(obj, 'contexts', {
enumerable: true,
get: function() {
return properties.contexts;
},
set: function(value) {
if (!Array.isArray(value)) {
throw new TypeError();
return;
};
properties.contexts = value.length == 0 ? value : value.join(',').split(',');
changed();
}
});
Object.defineProperty(obj, 'disabled', {
enumerable: true,
get: function() {
return properties.disabled;
},
set: function(value) {
properties.disabled = Boolean(value);
changed();
}
});
Object.defineProperty(obj, 'title', {
enumerable: true,
get: function() {
return properties.title;
},
set: function(value) {
properties.title = String(value);
changed();
}
});
Object.defineProperty(obj, 'icon', {
enumerable: true,
get: function() {
return properties.icon;
},
set: function(value) {
if (typeof value === "string") {
properties.icon = value;
if (properties.icon.indexOf(':') == -1 && properties.icon.indexOf('/') == -1 && properties.icon.length > 0) properties.icon = '/' + properties.icon;
};
changed();
}
});
Object.defineProperty(obj, 'documentURLPatterns', {
enumerable: true,
get: function() {
return properties.documentURLPatterns;
},
set: function(value) {
if (Array.isArray(value)) {
properties.documentURLPatterns = [];
for (var i = 0; i < value.length; i++) properties.documentURLPatterns.push(String(value[i]).toLowerCase());
};
changed();
}
});
Object.defineProperty(obj, 'targetURLPatterns', {
enumerable: true,
get: function() {
return properties.targetURLPatterns;
},
set: function(value) {
if (Array.isArray(value)) {
properties.targetURLPatterns = [];
for (var i = 0; i < value.length; i++) properties.targetURLPatterns.push(String(value[i]).toLowerCase());
};
changed();
}
});
Object.defineProperty(obj, 'menuItemId', {
enumerable: false,
get: function() {
return menuItemId;
},
set: nosetter
});
Object.defineProperty(obj, 'parent', {
enumerable: true,
get: function() {
return properties.parent;
},
set: nosetter
});
if (initial != undefined) update(initial);
return update;
};
var MenuItem = function(internal, properties) {
OMenuContext.apply(this, [internal]);
var _apply = MenuItemProperties(this, properties);
//click event
if (properties.onclick != undefined) this.onclick = properties.onclick; //set initial click handler
if (this.type.toLowerCase() === 'entry') chrome.contextMenus.onClicked.addListener(function(_info, _tab) {
if (this.menuItemId == null || !(this.menuItemId === _info.menuItemId || this.id === _info.menuItemId)) return;
this.dispatchEvent(new MenuEvent('click', {
info: _info,
tab: _tab
}, this));
var event = new MenuEvent('click', {
info: _info,
tab: _tab
}, this);
OEC.menu.dispatchEvent(event);
event.source.postMessage({
"action": "___O_MenuItem_Click",
"info": _info,
"menuItemId": this.id
});
}.bind(this));
this.addEventListener('change', function(e) {
if (e.target === this) _apply(e.properties);
else _apply();
for (var i = 0; i < this.length; i++) this[i].dispatchEvent(new MenuEvent('change', {
properties: e.properties
}, e.target));
}, false);
Object.defineProperty(this, 'toString', {
value: function(event) {
return "[object MenuItem]";
}
});
};
MenuItem.prototype = Object.create(OMenuContext.prototype);
var MenuContext = function(internal) {
chrome.contextMenus.removeAll(); //clear all items
OMenuContext.apply(this, [internal]);
Object.defineProperty(this, 'toString', {
value: function(event) {
return "[object MenuContext]";
}
});
};
MenuContext.prototype = Object.create(OMenuContext.prototype);
MenuContext.prototype.createItem = function(menuItemProperties) {
return new MenuItem(Opera, menuItemProperties);
};
if(manifest && manifest.permissions && manifest.permissions.indexOf('contextMenus')!=-1){
global.MenuItem = MenuItem;
global.MenuContext = MenuContext;
OEC.menu = OEC.menu || new MenuContext(Opera);
}
var SpeeddialContext = function() {
this.properties = {};
global.opr.speeddial.get(function(speeddialProperties) {
this.properties.url = speeddialProperties.url;
this.properties.title = speeddialProperties.title;
// Set WinTabs feature to LOADED
deferredComponentsLoadStatus['SPEEDDIAL_LOADED'] = true;
}.bind(this));
};
SpeeddialContext.prototype.constructor = SpeeddialContext;
SpeeddialContext.prototype.__defineGetter__('url', function() {
return this.properties.url || "";
}); // read
SpeeddialContext.prototype.__defineSetter__('url', function(val) {
this.properties.url = val;
global.opr.speeddial.update({ 'url': val }, function() {});
}); // write
SpeeddialContext.prototype.__defineGetter__('title', function() {
return this.properties.title || "";
}); // read
SpeeddialContext.prototype.__defineSetter__('title', function(val) {
this.properties.title = val;
global.opr.speeddial.update({ 'title': val }, function() {});
}); // write
if(manifest && manifest.speeddial && global.opr && global.opr.speeddial){
OEC.speeddial = OEC.speeddial || new SpeeddialContext();
} else {
// Set WinTabs feature to LOADED
deferredComponentsLoadStatus['SPEEDDIAL_LOADED'] = true;
}
/*
* This file is part of the Adblock Plus extension,
* Copyright (C) 2006-2012 Eyeo GmbH
*
* Adblock Plus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* Adblock Plus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
*/
//
// Module framework stuff
//
function require(module)
{
return require.scopes[module];
}
require.scopes = {__proto__: null};
function importAll(module, globalObj)
{
var exports = require(module);
for (var key in exports)
globalObj[key] = exports[key];
}
onShutdown = {
done: false,
add: function() {},
remove: function() {}
};
//
// XPCOM emulation
//
var Components =
{
interfaces:
{
nsIFile: {DIRECTORY_TYPE: 0},
nsIFileURL: function() {},
nsIHttpChannel: function() {},
nsITimer: {TYPE_REPEATING_SLACK: 0},
nsIInterfaceRequestor: null,
nsIChannelEventSink: null
},
classes:
{
"@mozilla.org/timer;1":
{
createInstance: function()
{
return new FakeTimer();
}
},
"@mozilla.org/xmlextras/xmlhttprequest;1":
{
createInstance: function()
{
return new XMLHttpRequest();
}
}
},
results: {},
utils: {
reportError: function(e)
{
console.error(e);
console.trace();
}
},
manager: null,
ID: function()
{
return null;
}
};
var Cc = Components.classes;
var Ci = Components.interfaces;
var Cr = Components.results;
var Cu = Components.utils;
var XPCOMUtils =
{
generateQI: function() {}
};
//
// Info pseudo-module
//
require.scopes.info =
{
get addonID()
{
return chrome.i18n.getMessage("@@extension_id");
},
addonVersion: "2.1", // Hardcoded for now
addonRoot: "",
get addonName()
{
return chrome.i18n.getMessage("name");
},
application: "chrome"
};
//
// IO module: no direct file system access, using FileSystem API
//
require.scopes.io =
{
IO: {
_getFileEntry: function(file, create, successCallback, errorCallback)
{
if (file instanceof FakeFile)
file = file.path;
else if ("spec" in file)
file = file.spec;
// Remove directory path - we operate on a single directory in Chrome
file = file.replace(/^.*[\/\\]/, "");
// We request a gigabyte of space, just in case
rFS = window.requestFileSystem || window.webkitRequestFileSystem;
if(rFS) {
rFS(window.PERSISTENT, 1024*1024*1024, function(fs)
{
fs.root.getFile(file, {create: create}, function(fileEntry)
{
successCallback(fs, fileEntry);
}, errorCallback);
}, errorCallback);
}
},
lineBreak: "\n",
resolveFilePath: function(path)
{
return new FakeFile(path);
},
readFromFile: function(file, decode, listener, callback, timeLineID)
{
if ("spec" in file && /^defaults\b/.test(file.spec))
{
// Code attempts to read the default patterns.ini, we don't have that.
// Make sure to execute first-run actions instead.
callback(null);
if (localStorage.currentVersion)
seenDataCorruption = true;
delete localStorage.currentVersion;
return;
}
this._getFileEntry(file, false, function(fs, fileEntry)
{
fileEntry.file(function(file)
{
var reader = new FileReader();
reader.onloadend = function()
{
if (reader.error)
callback(reader.error);
else
{
var lines = reader.result.split(/[\r\n]+/);
for (var i = 0; i < lines.length; i++)
listener.process(lines[i]);
listener.process(null);
callback(null);
}
};
reader.readAsText(file);
}, callback);
}, callback);
},
writeToFile: function(file, encode, data, callback, timeLineID)
{
this._getFileEntry(file, true, function(fs, fileEntry)
{
fileEntry.createWriter(function(writer)
{
var executeWriteOperation = function(op, nextOperation)
{
writer.onwriteend = function()
{
if (writer.error)
callback(writer.error);
else
nextOperation();
}.bind(this);
op();
}.bind(this);
executeWriteOperation(writer.truncate.bind(writer, 0), function()
{
var blob;
try
{
blob = new Blob([data.join(this.lineBreak) + this.lineBreak], {type: "text/plain"});
}
catch (e)
{
if (!(e instanceof TypeError))
throw e;
// Blob wasn't a constructor before Chrome 20
var builder = new (window.BlobBuilder || window.WebKitBlobBuilder);
builder.append(data.join(this.lineBreak) + this.lineBreak);
blob = builder.getBlob("text/plain");
}
executeWriteOperation(writer.write.bind(writer, blob), callback.bind(null, null));
}.bind(this));
}.bind(this), callback);
}.bind(this), callback);
},
copyFile: function(fromFile, toFile, callback)
{
// Simply combine read and write operations
var data = [];
this.readFromFile(fromFile, false, {
process: function(line)
{
if (line !== null)
data.push(line);
}
}, function(e)
{
if (e)
callback(e);
else
this.writeToFile(toFile, false, data, callback);
}.bind(this));
},
renameFile: function(fromFile, newName, callback)
{
this._getFileEntry(fromFile, false, function(fs, fileEntry)
{
fileEntry.moveTo(fs.root, newName, function()
{
callback(null);
}, callback);
}, callback);
},
removeFile: function(file, callback)
{
this._getFileEntry(file, false, function(fs, fileEntry)
{
fileEntry.remove(function()
{
callback(null);
}, callback);
}, callback);
},
statFile: function(file, callback)
{
this._getFileEntry(file, false, function(fs, fileEntry)
{
fileEntry.getMetadata(function(metadata)
{
callback(null, {
exists: true,
isDirectory: fileEntry.isDirectory,
isFile: fileEntry.isFile,
lastModified: metadata.modificationTime.getTime()
});
}, callback);
}, callback);
}
}
};
//
// Fake nsIFile implementation for our I/O
//
function FakeFile(path)
{
this.path = path;
}
FakeFile.prototype =
{
get leafName()
{
return this.path;
},
set leafName(value)
{
this.path = value;
},
append: function(path)
{
this.path += path;
},
clone: function()
{
return new FakeFile(this.path);
},
get parent()
{
return {create: function() {}};
},
normalize: function() {}
};
//
// Prefs module: the values are hardcoded for now.
//
require.scopes.prefs = {
Prefs: {
enabled: true,
patternsfile: "patterns.ini",
patternsbackups: 5,
patternsbackupinterval: 24,
data_directory: "",
savestats: false,
privateBrowsing: false,
subscriptions_fallbackerrors: 5,
subscriptions_fallbackurl: "https://adblockplus.org/getSubscription?version=%VERSION%&url=%SUBSCRIPTION%&downloadURL=%URL%&error=%ERROR%&channelStatus=%CHANNELSTATUS%&responseStatus=%RESPONSESTATUS%",
subscriptions_autoupdate: true,
subscriptions_exceptionsurl: "https://easylist-downloads.adblockplus.org/exceptionrules.txt",
documentation_link: "https://adblockplus.org/redirect?link=%LINK%&lang=%LANG%",
addListener: function() {}
}
};
//
// Utils module
//
require.scopes.utils =
{
Utils: {
systemPrincipal: null,
getString: function(id)
{
return id;
},
runAsync: function(callback, thisPtr)
{
var params = Array.prototype.slice.call(arguments, 2);
window.setTimeout(function()
{
callback.apply(thisPtr, params);
}, 0);
},
get appLocale()
{
var locale = chrome.i18n.getMessage("@@ui_locale").replace(/_/g, "-");
this.__defineGetter__("appLocale", function() {return locale});
return this.appLocale;
},
generateChecksum: function(lines)
{
// We cannot calculate MD5 checksums yet :-(
return null;
},
makeURI: function(url)
{
return Services.io.newURI(url);
},
checkLocalePrefixMatch: function(prefixes)
{
if (!prefixes)
return null;
var list = prefixes.split(",");
for (var i = 0; i < list.length; i++)
if (new RegExp("^" + list[i] + "\\b").test(this.appLocale))
return list[i];
return null;
},
chooseFilterSubscription: function(subscriptions)
{
var selectedItem = null;
var selectedPrefix = null;
var matchCount = 0;
for (var i = 0; i < subscriptions.length; i++)
{
var subscription = subscriptions[i];
if (!selectedItem)
selectedItem = subscription;
var prefix = require("utils").Utils.checkLocalePrefixMatch(subscription.getAttribute("prefixes"));
if (prefix)
{
if (!selectedPrefix || selectedPrefix.length < prefix.length)
{
selectedItem = subscription;
selectedPrefix = prefix;
matchCount = 1;
}
else if (selectedPrefix && selectedPrefix.length == prefix.length)
{
matchCount++;
// If multiple items have a matching prefix of the same length:
// Select one of the items randomly, probability should be the same
// for all items. So we replace the previous match here with
// probability 1/N (N being the number of matches).
if (Math.random() * matchCount < 1)
{
selectedItem = subscription;
selectedPrefix = prefix;
}
}
}
}
return selectedItem;
}
}
};
//
// ElemHideHitRegistration dummy implementation
//
require.scopes.elemHideHitRegistration =
{
AboutHandler: {}
};
//
// Services.jsm module emulation
//
var Services =
{
io: {
newURI: function(uri)
{
if (!uri.length || uri[0] == "~")
throw new Error("Invalid URI");
/^([^:\/]*)/.test(uri);
var scheme = RegExp.$1.toLowerCase();
return {
scheme: scheme,
spec: uri,
QueryInterface: function()
{
return this;
}
};
},
newFileURI: function(file)
{
var result = this.newURI("file:///" + file.path);
result.file = file;
return result;
}
},
obs: {
addObserver: function() {},
removeObserver: function() {}
},
vc: {
compare: function(v1, v2)
{
function parsePart(s)
{
if (!s)
return parsePart("0");
var part = {
numA: 0,
strB: "",
numC: 0,
extraD: ""
};
if (s === "*")
{
part.numA = Number.MAX_VALUE;
return part;
}
var matches = s.match(/(\d*)(\D*)(\d*)(.*)/);
part.numA = parseInt(matches[1], 10) || part.numA;
part.strB = matches[2] || part.strB;
part.numC = parseInt(matches[3], 10) || part.numC;
part.extraD = matches[4] || part.extraD;
if (part.strB == "+")
{
part.numA++;
part.strB = "pre";
}
return part;
}
function comparePartElement(s1, s2)
{
if (s1 === "" && s2 !== "")
return 1;
if (s1 !== "" && s2 === "")
return -1;
return s1 === s2 ? 0 : (s1 > s2 ? 1 : -1);
}
function compareParts(p1, p2)
{
var result = 0;
var elements = ["numA", "strB", "numC", "extraD"];
elements.some(function(element)
{
result = comparePartElement(p1[element], p2[element]);
return result;
});
return result;
}
var parts1 = v1.split(".");
var parts2 = v2.split(".");
for (var i = 0; i < Math.max(parts1.length, parts2.length); i++)
{
var result = compareParts(parsePart(parts1[i]), parsePart(parts2[i]));
if (result)
return result;
}
return 0;
}
}
}
//
// FileUtils.jsm module emulation
//
var FileUtils =
{
PERMS_DIRECTORY: 0
};
function FakeTimer()
{
}
FakeTimer.prototype =
{
delay: 0,
callback: null,
initWithCallback: function(callback, delay)
{
this.callback = callback;
this.delay = delay;
this.scheduleTimeout();
},
scheduleTimeout: function()
{
var me = this;
window.setTimeout(function()
{
try
{
me.callback();
}
catch(e)
{
Cu.reportError(e);
}
me.scheduleTimeout();
}, this.delay);
}
};
//
// Add a channel property to XMLHttpRequest, Synchronizer needs it
//
XMLHttpRequest.prototype.channel =
{
status: -1,
notificationCallbacks: {},
loadFlags: 0,
INHIBIT_CACHING: 0,
VALIDATE_ALWAYS: 0,
QueryInterface: function()
{
return this;
}
};
/*
* This file is part of the Adblock Plus extension,
* Copyright (C) 2006-2012 Eyeo GmbH
*
* Adblock Plus is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* Adblock Plus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Adblock Plus. If not, see <http://www.gnu.org/licenses/>.
*/
//
// This file has been generated automatically from Adblock Plus for Firefox
// source code. DO NOT MODIFY, change the original source code instead.
//
// Relevant repositories:
// * https://hg.adblockplus.org/adblockplus/
// * https://hg.adblockplus.org/jshydra/
//
/**
* Minor modifications for compatibility with operaextensions.js
*
* You can view changes by diffing this file with:
* https://github.com/adblockplus/adblockpluschrome/blob/0f158ee8c97390b831bac12016241613b4276729/lib/adblockplus.js
*
*/
require.scopes["filterNotifier"] = (function()
{
var exports = {};
var listeners = [];
var FilterNotifier = exports.FilterNotifier =
{
addListener: function(listener)
{
if (listeners.indexOf(listener) >= 0)
{
return;
}
listeners.push(listener);
},
removeListener: function(listener)
{
var index = listeners.indexOf(listener);
if (index >= 0)
{
listeners.splice(index, 1);
}
},
triggerListeners: function(action, item, param1, param2, param3)
{
for (var _loopIndex0 = 0; _loopIndex0 < listeners.length; ++_loopIndex0)
{
var listener = listeners[_loopIndex0];
listener(action, item, param1, param2, param3);
}
}
};
return exports;
})();
require.scopes["filterClasses"] = (function()
{
var exports = {};
var FilterNotifier = require("filterNotifier").FilterNotifier;
function Filter(text)
{
this.text = text;
this.subscriptions = [];
}
exports.Filter = Filter;
Filter.prototype =
{
text: null,
subscriptions: null,
serialize: function(buffer)
{
buffer.push("[Filter]");
buffer.push("text=" + this.text);
},
toString: function()
{
return this.text;
}
};
Filter.knownFilters =
{
__proto__: null
};
Filter.elemhideRegExp = /^([^\/\*\|\@"!]*?)#(\@)?(?:([\w\-]+|\*)((?:\([\w\-]+(?:[$^*]?=[^\(\)"]*)?\))*)|#([^{}]+))$/;
Filter.regexpRegExp = /^(@@)?\/.*\/(?:\$~?[\w\-]+(?:=[^,\s]+)?(?:,~?[\w\-]+(?:=[^,\s]+)?)*)?$/;
Filter.optionsRegExp = /\$(~?[\w\-]+(?:=[^,\s]+)?(?:,~?[\w\-]+(?:=[^,\s]+)?)*)$/;
Filter.fromText = function(text)
{
if (text in Filter.knownFilters)
{
return Filter.knownFilters[text];
}
var ret;
// element hiding is not supported in Opera's URL Filter API
// TODO: remove all elemhide related code
var match = null;
if (match)
{
ret = ElemHideBase.fromText(text, match[1], match[2], match[3], match[4], match[5]);
}
else if (text[0] == "!")
{
ret = new CommentFilter(text);
}
else
{
ret = RegExpFilter.fromText(text);
}
Filter.knownFilters[ret.text] = ret;
return ret;
};
Filter.fromObject = function(obj)
{
var ret = Filter.fromText(obj.text);
if (ret instanceof ActiveFilter)
{
if ("disabled" in obj)
{
ret._disabled = obj.disabled == "true";
}
if ("hitCount" in obj)
{
ret._hitCount = parseInt(obj.hitCount) || 0;
}
if ("lastHit" in obj)
{
ret._lastHit = parseInt(obj.lastHit) || 0;
}
}
return ret;
};
Filter.normalize = function(text)
{
if (!text)
{
return text;
}
text = text.replace(/[^\S ]/g, "");
if (/^\s*!/.test(text))
{
return text.replace(/^\s+/, "").replace(/\s+$/, "");
}
else if (Filter.elemhideRegExp.test(text))
{
var _tempVar1 = /^(.*?)(#\@?#?)(.*)$/.exec(text);
var domain = _tempVar1[1];
var separator = _tempVar1[2];
var selector = _tempVar1[3];
return domain.replace(/\s/g, "") + separator + selector.replace(/^\s+/, "").replace(/\s+$/, "");
}
else
{
return text.replace(/\s/g, "");
}
};
function InvalidFilter(text, reason)
{
Filter.call(this, text);
this.reason = reason;
}
exports.InvalidFilter = InvalidFilter;
InvalidFilter.prototype =
{
__proto__: Filter.prototype,
reason: null,
serialize: function(buffer){}
};
function CommentFilter(text)
{
Filter.call(this, text);
}
exports.CommentFilter = CommentFilter;
CommentFilter.prototype =
{
__proto__: Filter.prototype,
serialize: function(buffer){}
};
function ActiveFilter(text, domains)
{
Filter.call(this, text);
this.domainSource = domains;
}
exports.ActiveFilter = ActiveFilter;
ActiveFilter.prototype =
{
__proto__: Filter.prototype,
_disabled: false,
_hitCount: 0,
_lastHit: 0,
get disabled()
{
return this._disabled;
},
set disabled(value)
{
if (value != this._disabled)
{
var oldValue = this._disabled;
this._disabled = value;
FilterNotifier.triggerListeners("filter.disabled", this, value, oldValue);
}
return this._disabled;
},
get hitCount()
{
return this._hitCount;
},
set hitCount(value)
{
if (value != this._hitCount)
{
var oldValue = this._hitCount;
this._hitCount = value;
FilterNotifier.triggerListeners("filter.hitCount", this, value, oldValue);
}
return this._hitCount;
},
get lastHit()
{
return this._lastHit;
},
set lastHit(value)
{
if (value != this._lastHit)
{
var oldValue = this._lastHit;
this._lastHit = value;
FilterNotifier.triggerListeners("filter.lastHit", this, value, oldValue);
}
return this._lastHit;
},
domainSource: null,
domainSeparator: null,
ignoreTrailingDot: true,
get domains()
{
var domains = null;
if (this.domainSource)
{
var list = this.domainSource.split(this.domainSeparator);
if (list.length == 1 && list[0][0] != "~")
{
domains =
{
__proto__: null,
"": false
};
if (this.ignoreTrailingDot)
{
list[0] = list[0].replace(/\.+$/, "");
}
domains[list[0]] = true;
}
else
{
var hasIncludes = false;
for (var i = 0; i < list.length; i++)
{
var domain = list[i];
if (this.ignoreTrailingDot)
{
domain = domain.replace(/\.+$/, "");
}
if (domain == "")
{
continue;
}
var include;
if (domain[0] == "~")
{
include = false;
domain = domain.substr(1);
}
else
{
include = true;
hasIncludes = true;
}
if (!domains)
{
domains =
{
__proto__: null
};
}
domains[domain] = include;
}
domains[""] = !hasIncludes;
}
delete this.domainSource;
}
this.__defineGetter__("domains", function()
{
return domains;
});
return this.domains;
},
isActiveOnDomain: function(docDomain)
{
if (!this.domains)
{
return true;
}
if (!docDomain)
{
return this.domains[""];
}
if (this.ignoreTrailingDot)
{
docDomain = docDomain.replace(/\.+$/, "");
}
docDomain = docDomain.toUpperCase();
while (true)
{
if (docDomain in this.domains)
{
return this.domains[docDomain];
}
var nextDot = docDomain.indexOf(".");
if (nextDot < 0)
{
break;
}
docDomain = docDomain.substr(nextDot + 1);
}
return this.domains[""];
},
isActiveOnlyOnDomain: function(docDomain)
{
if (!docDomain || !this.domains || this.domains[""])
{
return false;
}
if (this.ignoreTrailingDot)
{
docDomain = docDomain.replace(/\.+$/, "");
}
docDomain = docDomain.toUpperCase();
for (var domain in this.domains)
{
if (this.domains[domain] && domain != docDomain && (domain.length <= docDomain.length || domain.indexOf("." + docDomain) != domain.length - docDomain.length - 1))
{
return false;
}
}
return true;
},
serialize: function(buffer)
{
if (this._disabled || this._hitCount || this._lastHit)
{
Filter.prototype.serialize.call(this, buffer);
if (this._disabled)
{
buffer.push("disabled=true");
}
if (this._hitCount)
{
buffer.push("hitCount=" + this._hitCount);
}
if (this._lastHit)
{
buffer.push("lastHit=" + this._lastHit);
}
}
}
};
function RegExpFilter(text, regexpSource, contentType, matchCase, domains, thirdParty)
{
ActiveFilter.call(this, text, domains);
if (contentType != null)
{
this.contentType = contentType;
}
if (matchCase)
{
this.matchCase = matchCase;
}
if (thirdParty != null)
{
this.thirdParty = thirdParty;
}
if (regexpSource.length >= 2 && regexpSource[0] == "/" && regexpSource[regexpSource.length - 1] == "/")
{
var regexp = new RegExp(regexpSource.substr(1, regexpSource.length - 2), this.matchCase ? "" : "i");
this.__defineGetter__("regexp", function()
{
return regexp;
});
}
else
{
this.regexpSource = regexpSource;
}
}
exports.RegExpFilter = RegExpFilter;
RegExpFilter.prototype =
{
__proto__: ActiveFilter.prototype,
length: 1,
domainSeparator: "|",
regexpSource: null,
get regexp()
{
var source = this.regexpSource.replace(/\*+/g, "*");
if (source[0] == "*")
{
source = source.substr(1);
}
var pos = source.length - 1;
if (pos >= 0 && source[pos] == "*")
{
source = source.substr(0, pos);
}
source = source.replace(/\^\|$/, "^").replace(/\W/g, "\\$&").replace(/\\\*/g, ".*").replace(/\\\^/g, "(?:[\\x00-\\x24\\x26-\\x2C\\x2F\\x3A-\\x40\\x5B-\\x5E\\x60\\x7B-\\x80]|$)").replace(/^\\\|\\\|/, "^[\\w\\-]+:\\/+(?!\\/)(?:[^.\\/]+\\.)*?").replace(/^\\\|/, "^").replace(/\\\|$/, "$");
var regexp = new RegExp(source, this.matchCase ? "" : "i");
delete this.regexpSource;
this.__defineGetter__("regexp", function()
{
return regexp;
});
return this.regexp;
},
contentType: 2147483647,
matchCase: false,
thirdParty: null,
matches: function(location, contentType, docDomain, thirdParty)
{
if (this.regexp.test(location) && (RegExpFilter.typeMap[contentType] & this.contentType) != 0 && (this.thirdParty == null || this.thirdParty == thirdParty) && this.isActiveOnDomain(docDomain))
{
return true;
}
return false;
}
};
RegExpFilter.prototype.__defineGetter__("0", function()
{
return this;
});
RegExpFilter.fromText = function(text)
{
var blocking = true;
var origText = text;
if (text.indexOf("@@") == 0)
{
blocking = false;
text = text.substr(2);
}
var contentType = null;
var matchCase = null;
var domains = null;
var siteKeys = null;
var thirdParty = null;
var collapse = null;
var options;
var match = text.indexOf("$") >= 0 ? Filter.optionsRegExp.exec(text) : null;
if (match)
{
options = match[1].toUpperCase().split(",");
text = match.input.substr(0, match.index);
for (var _loopIndex2 = 0; _loopIndex2 < options.length; ++_loopIndex2)
{
var option = options[_loopIndex2];
var value = null;
var separatorIndex = option.indexOf("=");
if (separatorIndex >= 0)
{
value = option.substr(separatorIndex + 1);
option = option.substr(0, separatorIndex);
}
option = option.replace(/-/, "_");
if (option in RegExpFilter.typeMap)
{
if (contentType == null)
{
contentType = 0;
}
contentType |= RegExpFilter.typeMap[option];
}
else if (option[0] == "~" && option.substr(1) in RegExpFilter.typeMap)
{
if (contentType == null)
{
contentType = RegExpFilter.prototype.contentType;
}
contentType &= ~RegExpFilter.typeMap[option.substr(1)];
}
else if (option == "MATCH_CASE")
{
matchCase = true;
}
else if (option == "DOMAIN" && typeof value != "undefined")
{
domains = value;
}
else if (option == "THIRD_PARTY")
{
thirdParty = true;
}
else if (option == "~THIRD_PARTY")
{
thirdParty = false;
}
else if (option == "COLLAPSE")
{
collapse = true;
}
else if (option == "~COLLAPSE")
{
collapse = false;
}
else if (option == "SITEKEY" && typeof value != "undefined")
{
siteKeys = value.split(/\|/);
}
}
}
if (!blocking && (contentType == null || contentType & RegExpFilter.typeMap.DOCUMENT) && (!options || options.indexOf("DOCUMENT") < 0) && !/^\|?[\w\-]+:/.test(text))
{
if (contentType == null)
{
contentType = RegExpFilter.prototype.contentType;
}
contentType &= ~RegExpFilter.typeMap.DOCUMENT;
}
if (!blocking && siteKeys)
{
contentType = RegExpFilter.typeMap.DOCUMENT;
}
try
{
if (blocking)
{
return new BlockingFilter(origText, text, contentType, matchCase, domains, thirdParty, collapse);
}
else
{
return new WhitelistFilter(origText, text, contentType, matchCase, domains, thirdParty, siteKeys);
}
}
catch (e)
{
return new InvalidFilter(text, e);
}
};
RegExpFilter.typeMap =
{
OTHER: 1,
SCRIPT: 2,
IMAGE: 4,
STYLESHEET: 8,
OBJECT: 16,
SUBDOCUMENT: 32,
DOCUMENT: 64,
XBL: 1,
PING: 1,
XMLHTTPREQUEST: 2048,
OBJECT_SUBREQUEST: 4096,
DTD: 1,
MEDIA: 16384,
FONT: 32768,
BACKGROUND: 4,
POPUP: 268435456,
DONOTTRACK: 536870912,
ELEMHIDE: 1073741824
};
RegExpFilter.prototype.contentType &= ~ (RegExpFilter.typeMap.ELEMHIDE | RegExpFilter.typeMap.DONOTTRACK | RegExpFilter.typeMap.POPUP);
function BlockingFilter(text, regexpSource, contentType, matchCase, domains, thirdParty, collapse)
{
RegExpFilter.call(this, text, regexpSource, contentType, matchCase, domains, thirdParty);
this.collapse = collapse;
}
exports.BlockingFilter = BlockingFilter;
BlockingFilter.prototype =
{
__proto__: RegExpFilter.prototype,
collapse: null
};
function WhitelistFilter(text, regexpSource, contentType, matchCase, domains, thirdParty, siteKeys)
{
RegExpFilter.call(this, text, regexpSource, contentType, matchCase, domains, thirdParty);
if (siteKeys != null)
{
this.siteKeys = siteKeys;
}
}
exports.WhitelistFilter = WhitelistFilter;
WhitelistFilter.prototype =
{
__proto__: RegExpFilter.prototype,
siteKeys: null
};
function ElemHideBase(text, domains, selector)
{
ActiveFilter.call(this, text, domains ? domains.toUpperCase() : null);
if (domains)
{
this.selectorDomain = domains.replace(/,~[^,]+/g, "").replace(/^~[^,]+,?/, "").toLowerCase();
}
this.selector = selector;
}
exports.ElemHideBase = ElemHideBase;
ElemHideBase.prototype =
{
__proto__: ActiveFilter.prototype,
domainSeparator: ",",
ignoreTrailingDot: false,
selectorDomain: null,
selector: null
};
ElemHideBase.fromText = function(text, domain, isException, tagName, attrRules, selector)
{
if (!selector)
{
if (tagName == "*")
{
tagName = "";
}
var id = null;
var additional = "";
if (attrRules)
{
attrRules = attrRules.match(/\([\w\-]+(?:[$^*]?=[^\(\)"]*)?\)/g);
for (var _loopIndex3 = 0; _loopIndex3 < attrRules.length; ++_loopIndex3)
{
var rule = attrRules[_loopIndex3];
rule = rule.substr(1, rule.length - 2);
var separatorPos = rule.indexOf("=");
if (separatorPos > 0)
{
rule = rule.replace(/=/, "=\"") + "\"";
additional += "[" + rule + "]";
}
else
{
if (id)
{
var Utils = require("utils").Utils;
return new InvalidFilter(text, Utils.getString("filter_elemhide_duplicate_id"));
}
else
{
id = rule;
}
}
}
}
if (id)
{
selector = tagName + "." + id + additional + "," + tagName + "#" + id + additional;
}
else if (tagName || additional)
{
selector = tagName + additional;
}
else
{
var Utils = require("utils").Utils;
return new InvalidFilter(text, Utils.getString("filter_elemhide_nocriteria"));
}
}
if (isException)
{
return new ElemHideException(text, domain, selector);
}
else
{
return new ElemHideFilter(text, domain, selector);
}
};
function ElemHideFilter(text, domains, selector)
{
ElemHideBase.call(this, text, domains, selector);
}
exports.ElemHideFilter = ElemHideFilter;
ElemHideFilter.prototype =
{
__proto__: ElemHideBase.prototype
};
function ElemHideException(text, domains, selector)
{
ElemHideBase.call(this, text, domains, selector);
}
exports.ElemHideException = ElemHideException;
ElemHideException.prototype =
{
__proto__: ElemHideBase.prototype
};
return exports;
})();
require.scopes["subscriptionClasses"] = (function()
{
var exports = {};
var _tempVar4 = require("filterClasses");
var ActiveFilter = _tempVar4.ActiveFilter;
var BlockingFilter = _tempVar4.BlockingFilter;
var WhitelistFilter = _tempVar4.WhitelistFilter;
var ElemHideBase = _tempVar4.ElemHideBase;
var FilterNotifier = require("filterNotifier").FilterNotifier;
function Subscription(url, title)
{
this.url = url;
this.filters = [];
if (title)
{
this._title = title;
}
else
{
var Utils = require("utils").Utils;
this._title = Utils.getString("newGroup_title");
}
Subscription.knownSubscriptions[url] = this;
}
exports.Subscription = Subscription;
Subscription.prototype =
{
url: null,
filters: null,
_title: null,
_fixedTitle: false,
_disabled: false,
get title()
{
return this._title;
},
set title(value)
{
if (value != this._title)
{
var oldValue = this._title;
this._title = value;
FilterNotifier.triggerListeners("subscription.title", this, value, oldValue);
}
return this._title;
},
get fixedTitle()
{
return this._fixedTitle;
},
set fixedTitle(value)
{
if (value != this._fixedTitle)
{
var oldValue = this._fixedTitle;
this._fixedTitle = value;
FilterNotifier.triggerListeners("subscription.fixedTitle", this, value, oldValue);
}
return this._fixedTitle;
},
get disabled()
{
return this._disabled;
},
set disabled(value)
{
if (value != this._disabled)
{
var oldValue = this._disabled;
this._disabled = value;
FilterNotifier.triggerListeners("subscription.disabled", this, value, oldValue);
}
return this._disabled;
},
serialize: function(buffer)
{
buffer.push("[Subscription]");
buffer.push("url=" + this.url);
buffer.push("title=" + this._title);
if (this._fixedTitle)
{
buffer.push("fixedTitle=true");
}
if (this._disabled)
{
buffer.push("disabled=true");
}
},
serializeFilters: function(buffer)
{
for (var _loopIndex5 = 0; _loopIndex5 < this.filters.length; ++_loopIndex5)
{
var filter = this.filters[_loopIndex5];
buffer.push(filter.text.replace(/\[/g, "\\["));
}
},
toString: function()
{
var buffer = [];
this.serialize(buffer);
return buffer.join("\n");
}
};
Subscription.knownSubscriptions =
{
__proto__: null
};
Subscription.fromURL = function(url)
{
if (url in Subscription.knownSubscriptions)
{
return Subscription.knownSubscriptions[url];
}
try
{
url = Services.io.newURI(url, null, null).spec;
return new DownloadableSubscription(url, null);
}
catch (e)
{
return new SpecialSubscription(url);
}
};
Subscription.fromObject = function(obj)
{
var result;
try
{
obj.url = Services.io.newURI(obj.url, null, null).spec;
result = new DownloadableSubscription(obj.url, obj.title);
if ("nextURL" in obj)
{
result.nextURL = obj.nextURL;
}
if ("downloadStatus" in obj)
{
result._downloadStatus = obj.downloadStatus;
}
if ("lastModified" in obj)
{
result.lastModified = obj.lastModified;
}
if ("lastSuccess" in obj)
{
result.lastSuccess = parseInt(obj.lastSuccess) || 0;
}
if ("lastCheck" in obj)
{
result._lastCheck = parseInt(obj.lastCheck) || 0;
}
if ("expires" in obj)
{
result.expires = parseInt(obj.expires) || 0;
}
if ("softExpiration" in obj)
{
result.softExpiration = parseInt(obj.softExpiration) || 0;
}
if ("errors" in obj)
{
result._errors = parseInt(obj.errors) || 0;
}
if ("requiredVersion" in obj)
{
var addonVersion = require("info").addonVersion;
result.requiredVersion = obj.requiredVersion;
if (Services.vc.compare(result.requiredVersion, addonVersion) > 0)
{
result.upgradeRequired = true;
}
}
if ("alternativeLocations" in obj)
{
result.alternativeLocations = obj.alternativeLocations;
}
if ("homepage" in obj)
{
result._homepage = obj.homepage;
}
if ("lastDownload" in obj)
{
result._lastDownload = parseInt(obj.lastDownload) || 0;
}
}
catch (e)
{
if (!("title" in obj))
{
if (obj.url == "~wl~")
{
obj.defaults = "whitelist";
}
else if (obj.url == "~fl~")
{
obj.defaults = "blocking";
}
else if (obj.url == "~eh~")
{
obj.defaults = "elemhide";
}
if ("defaults" in obj)
{
var Utils = require("utils").Utils;
obj.title = Utils.getString(obj.defaults + "Group_title");
}
}
result = new SpecialSubscription(obj.url, obj.title);
if ("defaults" in obj)
{
result.defaults = obj.defaults.split(" ");
}
}
if ("fixedTitle" in obj)
{
result._fixedTitle = obj.fixedTitle == "true";
}
if ("disabled" in obj)
{
result._disabled = obj.disabled == "true";
}
return result;
};
function SpecialSubscription(url, title)
{
Subscription.call(this, url, title);
}
exports.SpecialSubscription = SpecialSubscription;
SpecialSubscription.prototype =
{
__proto__: Subscription.prototype,
defaults: null,
isDefaultFor: function(filter)
{
if (this.defaults && this.defaults.length)
{
for (var _loopIndex6 = 0; _loopIndex6 < this.defaults.length; ++_loopIndex6)
{
var type = this.defaults[_loopIndex6];
if (filter instanceof SpecialSubscription.defaultsMap[type])
{
return true;
}
if (!(filter instanceof ActiveFilter) && type == "blacklist")
{
return true;
}
}
}
return false;
},
serialize: function(buffer)
{
Subscription.prototype.serialize.call(this, buffer);
if (this.defaults && this.defaults.length)
{
buffer.push("defaults=" + this.defaults.filter(function(type)
{
return type in SpecialSubscription.defaultsMap;
}).join(" "));
}
if (this._lastDownload)
{
buffer.push("lastDownload=" + this._lastDownload);
}
}
};
SpecialSubscription.defaultsMap =
{
__proto__: null,
"whitelist": WhitelistFilter,
"blocking": BlockingFilter,
"elemhide": ElemHideBase
};
SpecialSubscription.create = function(title)
{
var url;
do
{
url = "~user~" + Math.round(Math.random() * 1000000);
}
while (url in Subscription.knownSubscriptions);
return new SpecialSubscription(url, title);
};
SpecialSubscription.createForFilter = function(filter)
{
var subscription = SpecialSubscription.create();
subscription.filters.push(filter);
for (var type in SpecialSubscription.defaultsMap)
{
if (filter instanceof SpecialSubscription.defaultsMap[type])
{
subscription.defaults = [type];
}
}
if (!subscription.defaults)
{
subscription.defaults = ["blocking"];
}
var Utils = require("utils").Utils;
subscription.title = Utils.getString(subscription.defaults[0] + "Group_title");
return subscription;
};
function RegularSubscription(url, title)
{
Subscription.call(this, url, title || url);
}
exports.RegularSubscription = RegularSubscription;
RegularSubscription.prototype =
{
__proto__: Subscription.prototype,
_homepage: null,
_lastDownload: 0,
get homepage()
{
return this._homepage;
},
set homepage(value)
{
if (value != this._homepage)
{
var oldValue = this._homepage;
this._homepage = value;
FilterNotifier.triggerListeners("subscription.homepage", this, value, oldValue);
}
return this._homepage;
},
get lastDownload()
{
return this._lastDownload;
},
set lastDownload(value)
{
if (value != this._lastDownload)
{
var oldValue = this._lastDownload;
this._lastDownload = value;
FilterNotifier.triggerListeners("subscription.lastDownload", this, value, oldValue);
}
return this._lastDownload;
},
serialize: function(buffer)
{
Subscription.prototype.serialize.call(this, buffer);
if (this._homepage)
{
buffer.push("homepage=" + this._homepage);
}
if (this._lastDownload)
{
buffer.push("lastDownload=" + this._lastDownload);
}
}
};
function ExternalSubscription(url, title)
{
RegularSubscription.call(this, url, title);
}
exports.ExternalSubscription = ExternalSubscription;
ExternalSubscription.prototype =
{
__proto__: RegularSubscription.prototype,
serialize: function(buffer)
{
throw new Error("Unexpected call, external subscriptions should not be serialized");
}
};
function DownloadableSubscription(url, title)
{
RegularSubscription.call(this, url, title);
}
exports.DownloadableSubscription = DownloadableSubscription;
DownloadableSubscription.prototype =
{
__proto__: RegularSubscription.prototype,
_downloadStatus: null,
_lastCheck: 0,
_errors: 0,
nextURL: null,
get downloadStatus()
{
return this._downloadStatus;
},
set downloadStatus(value)
{
var oldValue = this._downloadStatus;
this._downloadStatus = value;
FilterNotifier.triggerListeners("subscription.downloadStatus", this, value, oldValue);
return this._downloadStatus;
},
lastModified: null,
lastSuccess: 0,
get lastCheck()
{
return this._lastCheck;
},
set lastCheck(value)
{
if (value != this._lastCheck)
{
var oldValue = this._lastCheck;
this._lastCheck = value;
FilterNotifier.triggerListeners("subscription.lastCheck", this, value, oldValue);
}
return this._lastCheck;
},
expires: 0,
softExpiration: 0,
get errors()
{
return this._errors;
},
set errors(value)
{
if (value != this._errors)
{
var oldValue = this._errors;
this._errors = value;
FilterNotifier.triggerListeners("subscription.errors", this, value, oldValue);
}
return this._errors;
},
requiredVersion: null,
upgradeRequired: false,
alternativeLocations: null,
serialize: function(buffer)
{
RegularSubscription.prototype.serialize.call(this, buffer);
if (this.nextURL)
{
buffer.push("nextURL=" + this.nextURL);
}
if (this.downloadStatus)
{
buffer.push("downloadStatus=" + this.downloadStatus);
}
if (this.lastModified)
{
buffer.push("lastModified=" + this.lastModified);
}
if (this.lastSuccess)
{
buffer.push("lastSuccess=" + this.lastSuccess);
}
if (this.lastCheck)
{
buffer.push("lastCheck=" + this.lastCheck);
}
if (this.expires)
{
buffer.push("expires=" + this.expires);
}
if (this.softExpiration)
{
buffer.push("softExpiration=" + this.softExpiration);
}
if (this.errors)
{
buffer.push("errors=" + this.errors);
}
if (this.requiredVersion)
{
buffer.push("requiredVersion=" + this.requiredVersion);
}
if (this.alternativeLocations)
{
buffer.push("alternativeLocations=" + this.alternativeLocations);
}
}
};
return exports;
})();
require.scopes["filterStorage"] = (function()
{
var exports = {};
var IO = require("io").IO;
var Prefs = require("prefs").Prefs;
var _tempVar7 = require("filterClasses");
var Filter = _tempVar7.Filter;
var ActiveFilter = _tempVar7.ActiveFilter;
var _tempVar8 = require("subscriptionClasses");
var Subscription = _tempVar8.Subscription;
var SpecialSubscription = _tempVar8.SpecialSubscription;
var ExternalSubscription = _tempVar8.ExternalSubscription;
var FilterNotifier = require("filterNotifier").FilterNotifier;
var formatVersion = 4;
var FilterStorage = exports.FilterStorage =
{
get formatVersion()
{
return formatVersion;
},
get sourceFile()
{
var file = null;
if (Prefs.patternsfile)
{
file = IO.resolveFilePath(Prefs.patternsfile);
}
if (!file)
{
file = IO.resolveFilePath(Prefs.data_directory);
if (file)
{
file.append("patterns.ini");
}
}
if (!file)
{
try
{
file = IO.resolveFilePath(Services.prefs.getDefaultBranch("extensions.adblockplus.").getCharPref("data_directory"));
if (file)
{
file.append("patterns.ini");
}
}
catch (e){}
}
if (!file)
{
Cu.reportError("Adblock Plus: Failed to resolve filter file location from extensions.adblockplus.patternsfile preference");
}
this.__defineGetter__("sourceFile", function()
{
return file;
});
return this.sourceFile;
},
fileProperties:
{
__proto__: null
},
subscriptions: [],
knownSubscriptions:
{
__proto__: null
},
getGroupForFilter: function(filter)
{
var generalSubscription = null;
for (var _loopIndex9 = 0; _loopIndex9 < FilterStorage.subscriptions.length; ++_loopIndex9)
{
var subscription = FilterStorage.subscriptions[_loopIndex9];
if (subscription instanceof SpecialSubscription && !subscription.disabled)
{
if (subscription.isDefaultFor(filter))
{
return subscription;
}
if (!generalSubscription && (!subscription.defaults || !subscription.defaults.length))
{
generalSubscription = subscription;
}
}
}
return generalSubscription;
},
addSubscription: function(subscription, silent)
{
if (subscription.url in FilterStorage.knownSubscriptions)
{
return;
}
FilterStorage.subscriptions.push(subscription);
FilterStorage.knownSubscriptions[subscription.url] = subscription;
addSubscriptionFilters(subscription);
if (!silent)
{
FilterNotifier.triggerListeners("subscription.added", subscription);
}
},
removeSubscription: function(subscription, silent)
{
for (var i = 0; i < FilterStorage.subscriptions.length; i++)
{
if (FilterStorage.subscriptions[i].url == subscription.url)
{
removeSubscriptionFilters(subscription);
FilterStorage.subscriptions.splice(i--, 1);
delete FilterStorage.knownSubscriptions[subscription.url];
if (!silent)
{
FilterNotifier.triggerListeners("subscription.removed", subscription);
}
return;
}
}
},
moveSubscription: function(subscription, insertBefore)
{
var currentPos = FilterStorage.subscriptions.indexOf(subscription);
if (currentPos < 0)
{
return;
}
var newPos = insertBefore ? FilterStorage.subscriptions.indexOf(insertBefore) : -1;
if (newPos < 0)
{
newPos = FilterStorage.subscriptions.length;
}
if (currentPos < newPos)
{
newPos--;
}
if (currentPos == newPos)
{
return;
}
FilterStorage.subscriptions.splice(currentPos, 1);
FilterStorage.subscriptions.splice(newPos, 0, subscription);
FilterNotifier.triggerListeners("subscription.moved", subscription);
},
updateSubscriptionFilters: function(subscription, filters)
{
removeSubscriptionFilters(subscription);
subscription.oldFilters = subscription.filters;
subscription.filters = filters;
addSubscriptionFilters(subscription);
FilterNotifier.triggerListeners("subscription.updated", subscription);
delete subscription.oldFilters;
},
addFilter: function(filter, subscription, position, silent)
{
if (!subscription)
{
if (filter.subscriptions.some(function(s)
{
return s instanceof SpecialSubscription && !s.disabled;
}))
{
return;
}
subscription = FilterStorage.getGroupForFilter(filter);
}
if (!subscription)
{
subscription = SpecialSubscription.createForFilter(filter);
this.addSubscription(subscription);
return;
}
if (typeof position == "undefined")
{
position = subscription.filters.length;
}
if (filter.subscriptions.indexOf(subscription) < 0)
{
filter.subscriptions.push(subscription);
}
subscription.filters.splice(position, 0, filter);
if (!silent)
{
FilterNotifier.triggerListeners("filter.added", filter, subscription, position);
}
},
removeFilter: function(filter, subscription, position)
{
var subscriptions = subscription ? [subscription] : filter.subscriptions.slice();
for (var i = 0; i < subscriptions.length; i++)
{
var subscription = subscriptions[i];
if (subscription instanceof SpecialSubscription)
{
var positions = [];
if (typeof position == "undefined")
{
var index = -1;
do
{
index = subscription.filters.indexOf(filter, index + 1);
if (index >= 0)
{
positions.push(index);
}
}
while (index >= 0);
}
else
{
positions.push(position);
}
for (var j = positions.length - 1; j >= 0; j--)
{
var position = positions[j];
if (subscription.filters[position] == filter)
{
subscription.filters.splice(position, 1);
if (subscription.filters.indexOf(filter) < 0)
{
var index = filter.subscriptions.indexOf(subscription);
if (index >= 0)
{
filter.subscriptions.splice(index, 1);
}
}
FilterNotifier.triggerListeners("filter.removed", filter, subscription, position);
}
}
}
}
},
moveFilter: function(filter, subscription, oldPosition, newPosition)
{
if (!(subscription instanceof SpecialSubscription) || subscription.filters[oldPosition] != filter)
{
return;
}
newPosition = Math.min(Math.max(newPosition, 0), subscription.filters.length - 1);
if (oldPosition == newPosition)
{
return;
}
subscription.filters.splice(oldPosition, 1);
subscription.filters.splice(newPosition, 0, filter);
FilterNotifier.triggerListeners("filter.moved", filter, subscription, oldPosition, newPosition);
},
increaseHitCount: function(filter)
{
if (!Prefs.savestats || PrivateBrowsing.enabled || !(filter instanceof ActiveFilter))
{
return;
}
filter.hitCount++;
filter.lastHit = Date.now();
},
resetHitCounts: function(filters)
{
if (!filters)
{
filters = [];
for (var text in Filter.knownFilters)
{
filters.push(Filter.knownFilters[text]);
}
}
for (var _loopIndex10 = 0; _loopIndex10 < filters.length; ++_loopIndex10)
{
var filter = filters[_loopIndex10];
filter.hitCount = 0;
filter.lastHit = 0;
}
},
_loading: false,
loadFromDisk: function(sourceFile)
{
if (this._loading)
{
return;
}
var readFile = function(sourceFile, backupIndex)
{
var parser = new INIParser();
doneReading(parser);
return;
IO.readFromFile(sourceFile, true, parser, function(e)
{
if (!e && parser.subscriptions.length == 0)
{
e = new Error("No data in the file");
}
if (e)
{
Cu.reportError(e);
}
if (e && !explicitFile)
{
sourceFile = this.sourceFile;
if (sourceFile)
{
var _tempVar11 = /^(.*)(\.\w+)$/.exec(sourceFile.leafName) || [null, sourceFile.leafName, ""];
var part1 = _tempVar11[1];
var part2 = _tempVar11[2];
sourceFile = sourceFile.clone();
sourceFile.leafName = part1 + "-backup" + ++backupIndex + part2;
IO.statFile(sourceFile, function(e, statData)
{
if (!e && statData.exists)
{
readFile(sourceFile, backupIndex);
}
else
{
doneReading(parser);
}
});
return;
}
}
doneReading(parser);
}.bind(this), "FilterStorageRead");
}.bind(this);
var doneReading = function(parser)
{
var specialMap =
{
"~il~": true,
"~wl~": true,
"~fl~": true,
"~eh~": true
};
var knownSubscriptions =
{
__proto__: null
};
for (var i = 0; i < parser.subscriptions.length; i++)
{
var subscription = parser.subscriptions[i];
if (subscription instanceof SpecialSubscription && subscription.filters.length == 0 && subscription.url in specialMap)
{
parser.subscriptions.splice(i--, 1);
}
else
{
knownSubscriptions[subscription.url] = subscription;
}
}
this.fileProperties = parser.fileProperties;
this.subscriptions = parser.subscriptions;
this.knownSubscriptions = knownSubscriptions;
Filter.knownFilters = parser.knownFilters;
Subscription.knownSubscriptions = parser.knownSubscriptions;
if (parser.userFilters)
{
for (var i = 0; i < parser.userFilters.length; i++)
{
var filter = Filter.fromText(parser.userFilters[i]);
this.addFilter(filter, null, undefined, true);
}
}
this._loading = false;
FilterNotifier.triggerListeners("load");
if (sourceFile != this.sourceFile)
{
this.saveToDisk();
}
}.bind(this);
var startRead = function(file)
{
this._loading = true;
readFile(file, 0);
}.bind(this);
var explicitFile;
if (sourceFile)
{
explicitFile = true;
startRead(sourceFile);
}
else
{
explicitFile = false;
sourceFile = FilterStorage.sourceFile;
var callback = function(e, statData)
{
if (e || !statData.exists)
{
var addonRoot = require("info").addonRoot;
sourceFile = Services.io.newURI(addonRoot + "defaults/patterns.ini", null, null);
}
startRead(sourceFile);
};
if (sourceFile)
{
IO.statFile(sourceFile, callback);
}
else
{
callback(true);
}
}
},
_generateFilterData: function(subscriptions)
{
var _generatorResult12 = [];
_generatorResult12.push("# Adblock Plus preferences");
_generatorResult12.push("version=" + formatVersion);
var saved =
{
__proto__: null
};
var buf = [];
for (var i = 0; i < subscriptions.length; i++)
{
var subscription = subscriptions[i];
for (var j = 0; j < subscription.filters.length; j++)
{
var filter = subscription.filters[j];
if (!(filter.text in saved))
{
filter.serialize(buf);
saved[filter.text] = filter;
for (var k = 0; k < buf.length; k++)
{
_generatorResult12.push(buf[k]);
}
buf.splice(0);
}
}
}
for (var i = 0; i < subscriptions.length; i++)
{
var subscription = subscriptions[i];
_generatorResult12.push("");
subscription.serialize(buf);
if (subscription.filters.length)
{
buf.push("", "[Subscription filters]");
subscription.serializeFilters(buf);
}
for (var k = 0; k < buf.length; k++)
{
_generatorResult12.push(buf[k]);
}
buf.splice(0);
}
return _generatorResult12;
},
_saving: false,
_needsSave: false,
saveToDisk: function(targetFile)
{
var explicitFile = true;
if (!targetFile)
{
targetFile = FilterStorage.sourceFile;
explicitFile = false;
}
if (!targetFile)
{
return;
}
if (!explicitFile && this._saving)
{
this._needsSave = true;
return;
}
try
{
targetFile.parent.create(Ci.nsIFile.DIRECTORY_TYPE, FileUtils.PERMS_DIRECTORY);
}
catch (e){}
var writeFilters = function()
{
IO.writeToFile(targetFile, true, this._generateFilterData(subscriptions), function(e)
{
/*if (!explicitFile)
{
this._saving = false;
}
if (e)
{
Cu.reportError(e);
}
if (!explicitFile && this._needsSave)
{
this._needsSave = false;
this.saveToDisk();
}
else
{
FilterNotifier.triggerListeners("save");
}*/
}.bind(this), "FilterStorageWrite");
}.bind(this);
var checkBackupRequired = function(callbackNotRequired, callbackRequired)
{
if (explicitFile || Prefs.patternsbackups <= 0)
{
callbackNotRequired();
}
else
{
IO.statFile(targetFile, function(e, statData)
{
if (e || !statData.exists)
{
callbackNotRequired();
}
else
{
var _tempVar13 = /^(.*)(\.\w+)$/.exec(targetFile.leafName) || [null, targetFile.leafName, ""];
var part1 = _tempVar13[1];
var part2 = _tempVar13[2];
var newestBackup = targetFile.clone();
newestBackup.leafName = part1 + "-backup1" + part2;
IO.statFile(newestBackup, function(e, statData)
{
if (!e && (!statData.exists || (Date.now() - statData.lastModified) / 3600000 >= Prefs.patternsbackupinterval))
{
callbackRequired(part1, part2);
}
else
{
callbackNotRequired();
}
});
}
});
}
}.bind(this);
var removeLastBackup = function(part1, part2)
{
var file = targetFile.clone();
file.leafName = part1 + "-backup" + Prefs.patternsbackups + part2;
IO.removeFile(file, function(e)
{
return renameBackup(part1, part2, Prefs.patternsbackups - 1);
});
}.bind(this);
var renameBackup = function(part1, part2, index)
{
if (index > 0)
{
var fromFile = targetFile.clone();
fromFile.leafName = part1 + "-backup" + index + part2;
var toName = part1 + "-backup" + (index + 1) + part2;
IO.renameFile(fromFile, toName, function(e)
{
return renameBackup(part1, part2, index - 1);
});
}
else
{
var toFile = targetFile.clone();
toFile.leafName = part1 + "-backup" + (index + 1) + part2;
IO.copyFile(targetFile, toFile, writeFilters);
}
}.bind(this);
var subscriptions = this.subscriptions.filter(function(s)
{
return !(s instanceof ExternalSubscription);
});
if (!explicitFile)
{
this._saving = true;
}
checkBackupRequired(writeFilters, removeLastBackup);
},
getBackupFiles: function()
{
var result = [];
var _tempVar14 = /^(.*)(\.\w+)$/.exec(FilterStorage.sourceFile.leafName) || [null, FilterStorage.sourceFile.leafName, ""];
var part1 = _tempVar14[1];
var part2 = _tempVar14[2];
for (var i = 1;; i++)
{
var file = FilterStorage.sourceFile.clone();
file.leafName = part1 + "-backup" + i + part2;
if (file.exists())
{
result.push(file);
}
else
{
break;
}
}
return result;
}
};
function addSubscriptionFilters(subscription)
{
if (!(subscription.url in FilterStorage.knownSubscriptions))
{
return;
}
for (var _loopIndex15 = 0; _loopIndex15 < subscription.filters.length; ++_loopIndex15)
{
var filter = subscription.filters[_loopIndex15];
filter.subscriptions.push(subscription);
}
}
function removeSubscriptionFilters(subscription)
{
if (!(subscription.url in FilterStorage.knownSubscriptions))
{
return;
}
for (var _loopIndex16 = 0; _loopIndex16 < subscription.filters.length; ++_loopIndex16)
{
var filter = subscription.filters[_loopIndex16];
var i = filter.subscriptions.indexOf(subscription);
if (i >= 0)
{
filter.subscriptions.splice(i, 1);
}
}
}
var PrivateBrowsing = exports.PrivateBrowsing =
{
enabled: false,
init: function()
{
if ("@mozilla.org/privatebrowsing;1" in Cc)
{
try
{
this.enabled = Cc["@mozilla.org/privatebrowsing;1"].getService(Ci.nsIPrivateBrowsingService).privateBrowsingEnabled;
Services.obs.addObserver(this, "private-browsing", true);
onShutdown.add(function()
{
Services.obs.removeObserver(this, "private-browsing");
}.bind(this));
}
catch (e)
{
Cu.reportError(e);
}
}
},
observe: function(subject, topic, data)
{
if (topic == "private-browsing")
{
if (data == "enter")
{
this.enabled = true;
}
else if (data == "exit")
{
this.enabled = false;
}
}
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsISupportsWeakReference, Ci.nsIObserver])
};
PrivateBrowsing.init();
function INIParser()
{
this.fileProperties = this.curObj = {};
this.subscriptions = [];
this.knownFilters =
{
__proto__: null
};
this.knownSubscriptions =
{
__proto__: null
};
}
INIParser.prototype =
{
subscriptions: null,
knownFilters: null,
knownSubscrptions: null,
wantObj: true,
fileProperties: null,
curObj: null,
curSection: null,
userFilters: null,
process: function(val)
{
var origKnownFilters = Filter.knownFilters;
Filter.knownFilters = this.knownFilters;
var origKnownSubscriptions = Subscription.knownSubscriptions;
Subscription.knownSubscriptions = this.knownSubscriptions;
var match;
try
{
if (this.wantObj === true && (match = /^(\w+)=(.*)$/.exec(val)))
{
this.curObj[match[1]] = match[2];
}
else if (val === null || (match = /^\s*\[(.+)\]\s*$/.exec(val)))
{
if (this.curObj)
{
switch (this.curSection)
{
case "filter":
case "pattern":
if ("text" in this.curObj)
{
Filter.fromObject(this.curObj);
}
break;
case "subscription":
var subscription = Subscription.fromObject(this.curObj);
if (subscription)
{
this.subscriptions.push(subscription);
}
break;
case "subscription filters":
case "subscription patterns":
if (this.subscriptions.length)
{
var subscription = this.subscriptions[this.subscriptions.length - 1];
for (var _loopIndex17 = 0; _loopIndex17 < this.curObj.length; ++_loopIndex17)
{
var text = this.curObj[_loopIndex17];
var filter = Filter.fromText(text);
subscription.filters.push(filter);
filter.subscriptions.push(subscription);
}
}
break;
case "user patterns":
this.userFilters = this.curObj;
break;
}
}
if (val === null)
{
return;
}
this.curSection = match[1].toLowerCase();
switch (this.curSection)
{
case "filter":
case "pattern":
case "subscription":
this.wantObj = true;
this.curObj = {};
break;
case "subscription filters":
case "subscription patterns":
case "user patterns":
this.wantObj = false;
this.curObj = [];
break;
default:
this.wantObj = undefined;
this.curObj = null;
}
}
else if (this.wantObj === false && val)
{
this.curObj.push(val.replace(/\\\[/g, "["));
}
}
finally
{
Filter.knownFilters = origKnownFilters;
Subscription.knownSubscriptions = origKnownSubscriptions;
}
}
};
return exports;
})();
require.scopes["elemHide"] = (function()
{
var exports = {};
var Utils = require("utils").Utils;
var IO = require("io").IO;
var Prefs = require("prefs").Prefs;
var ElemHideException = require("filterClasses").ElemHideException;
var FilterNotifier = require("filterNotifier").FilterNotifier;
var AboutHandler = require("elemHideHitRegistration").AboutHandler;
var filterByKey =
{
__proto__: null
};
var keyByFilter =
{
__proto__: null
};
var knownExceptions =
{
__proto__: null
};
var exceptions =
{
__proto__: null
};
var styleURL = null;
var ElemHide = exports.ElemHide =
{
isDirty: false,
applied: false,
init: function()
{
Prefs.addListener(function(name)
{
if (name == "enabled")
{
ElemHide.apply();
}
});
onShutdown.add(function()
{
ElemHide.unapply();
});
var styleFile = IO.resolveFilePath(Prefs.data_directory);
styleFile.append("elemhide.css");
styleURL = Services.io.newFileURI(styleFile).QueryInterface(Ci.nsIFileURL);
},
clear: function()
{
filterByKey =
{
__proto__: null
};
keyByFilter =
{
__proto__: null
};
knownExceptions =
{
__proto__: null
};
exceptions =
{
__proto__: null
};
ElemHide.isDirty = false;
ElemHide.unapply();
},
add: function(filter)
{
if (filter instanceof ElemHideException)
{
if (filter.text in knownExceptions)
{
return;
}
var selector = filter.selector;
if (!(selector in exceptions))
{
exceptions[selector] = [];
}
exceptions[selector].push(filter);
knownExceptions[filter.text] = true;
}
else
{
if (filter.text in keyByFilter)
{
return;
}
var key;
do
{
key = Math.random().toFixed(15).substr(5);
}
while (key in filterByKey);
filterByKey[key] = filter;
keyByFilter[filter.text] = key;
ElemHide.isDirty = true;
}
},
remove: function(filter)
{
if (filter instanceof ElemHideException)
{
if (!(filter.text in knownExceptions))
{
return;
}
var list = exceptions[filter.selector];
var index = list.indexOf(filter);
if (index >= 0)
{
list.splice(index, 1);
}
delete knownExceptions[filter.text];
}
else
{
if (!(filter.text in keyByFilter))
{
return;
}
var key = keyByFilter[filter.text];
delete filterByKey[key];
delete keyByFilter[filter.text];
ElemHide.isDirty = true;
}
},
getException: function(filter, docDomain)
{
var selector = filter.selector;
if (!(filter.selector in exceptions))
{
return null;
}
var list = exceptions[filter.selector];
for (var i = list.length - 1; i >= 0; i--)
{
if (list[i].isActiveOnDomain(docDomain))
{
return list[i];
}
}
return null;
},
_applying: false,
_needsApply: false,
apply: function()
{
if (this._applying)
{
this._needsApply = true;
return;
}
if (!ElemHide.isDirty || !Prefs.enabled)
{
if (Prefs.enabled && !ElemHide.applied)
{
try
{
Utils.styleService.loadAndRegisterSheet(styleURL, Ci.nsIStyleSheetService.USER_SHEET);
ElemHide.applied = true;
}
catch (e)
{
Cu.reportError(e);
}
}
else if (!Prefs.enabled && ElemHide.applied)
{
ElemHide.unapply();
}
return;
}
IO.writeToFile(styleURL.file, false, this._generateCSSContent(), function(e)
{
this._applying = false;
if (e && e.result == Cr.NS_ERROR_NOT_AVAILABLE)
{
IO.removeFile(styleURL.file, function(e2){});
}
else if (e)
{
Cu.reportError(e);
}
if (this._needsApply)
{
this._needsApply = false;
this.apply();
}
else if (!e || e.result == Cr.NS_ERROR_NOT_AVAILABLE)
{
ElemHide.isDirty = false;
ElemHide.unapply();
if (!e)
{
try
{
Utils.styleService.loadAndRegisterSheet(styleURL, Ci.nsIStyleSheetService.USER_SHEET);
ElemHide.applied = true;
}
catch (e)
{
Cu.reportError(e);
}
}
FilterNotifier.triggerListeners("elemhideupdate");
}
}.bind(this), "ElemHideWrite");
this._applying = true;
},
_generateCSSContent: function()
{
var _generatorResult12 = [];
var domains =
{
__proto__: null
};
var hasFilters = false;
for (var key in filterByKey)
{
var filter = filterByKey[key];
var domain = filter.selectorDomain || "";
var list;
if (domain in domains)
{
list = domains[domain];
}
else
{
list =
{
__proto__: null
};
domains[domain] = list;
}
list[filter.selector] = key;
hasFilters = true;
}
if (!hasFilters)
{
throw Cr.NS_ERROR_NOT_AVAILABLE;
}
function escapeChar(match)
{
return "\\" + match.charCodeAt(0).toString(16) + " ";
}
var cssTemplate = "-moz-binding: url(about:" + AboutHandler.aboutPrefix + "?%ID%#dummy) !important;";
for (var domain in domains)
{
var rules = [];
var list = domains[domain];
if (domain)
{
_generatorResult12.push(("@-moz-document domain(\"" + domain.split(",").join("\"),domain(\"") + "\"){").replace(/[^\x01-\x7F]/g, escapeChar));
}
else
{
_generatorResult12.push("@-moz-document url-prefix(\"http://\"),url-prefix(\"https://\")," + "url-prefix(\"mailbox://\"),url-prefix(\"imap://\")," + "url-prefix(\"news://\"),url-prefix(\"snews://\"){");
}
for (var selector in list)
{
_generatorResult12.push(selector.replace(/[^\x01-\x7F]/g, escapeChar) + "{" + cssTemplate.replace("%ID%", list[selector]) + "}");
}
_generatorResult12.push("}");
}
return _generatorResult12;
},
unapply: function()
{
if (ElemHide.applied)
{
try
{
Utils.styleService.unregisterSheet(styleURL, Ci.nsIStyleSheetService.USER_SHEET);
}
catch (e)
{
Cu.reportError(e);
}
ElemHide.applied = false;
}
},
get styleURL()
{
return ElemHide.applied ? styleURL.spec : null;
},
getFilterByKey: function(key)
{
return key in filterByKey ? filterByKey[key] : null;
},
getSelectorsForDomain: function(domain, specificOnly)
{
var result = [];
for (var key in filterByKey)
{
var filter = filterByKey[key];
if (specificOnly && (!filter.domains || filter.domains[""]))
{
continue;
}
if (filter.isActiveOnDomain(domain) && !this.getException(filter, domain))
{
result.push(filter.selector);
}
}
return result;
}
};
return exports;
})();
require.scopes["matcher"] = (function()
{
var exports = {};
var _tempVar18 = require("filterClasses");
var Filter = _tempVar18.Filter;
var RegExpFilter = _tempVar18.RegExpFilter;
var WhitelistFilter = _tempVar18.WhitelistFilter;
function Matcher()
{
this.clear();
}
exports.Matcher = Matcher;
Matcher.prototype =
{
filterByKeyword: null,
keywordByFilter: null,
clear: function()
{
this.filterByKeyword =
{
__proto__: null
};
this.keywordByFilter =
{
__proto__: null
};
},
add: function(filter)
{
if (filter.text in this.keywordByFilter)
{
return;
}
var keyword = this.findKeyword(filter);
var oldEntry = this.filterByKeyword[keyword];
if (typeof oldEntry == "undefined")
{
this.filterByKeyword[keyword] = filter;
}
else if (oldEntry.length == 1)
{
this.filterByKeyword[keyword] = [oldEntry, filter];
}
else
{
oldEntry.push(filter);
}
this.keywordByFilter[filter.text] = keyword;
},
remove: function(filter)
{
if (!(filter.text in this.keywordByFilter))
{
return;
}
var keyword = this.keywordByFilter[filter.text];
var list = this.filterByKeyword[keyword];
if (list.length <= 1)
{
delete this.filterByKeyword[keyword];
}
else
{
var index = list.indexOf(filter);
if (index >= 0)
{
list.splice(index, 1);
if (list.length == 1)
{
this.filterByKeyword[keyword] = list[0];
}
}
}
delete this.keywordByFilter[filter.text];
},
findKeyword: function(filter)
{
var defaultResult = filter.contentType & RegExpFilter.typeMap.DONOTTRACK ? "donottrack" : "";
var text = filter.text;
if (Filter.regexpRegExp.test(text))
{
return defaultResult;
}
var match = Filter.optionsRegExp.exec(text);
if (match)
{
text = match.input.substr(0, match.index);
}
if (text.substr(0, 2) == "@@")
{
text = text.substr(2);
}
var candidates = text.toLowerCase().match(/[^a-z0-9%*][a-z0-9%]{3,}(?=[^a-z0-9%*])/g);
if (!candidates)
{
return defaultResult;
}
var hash = this.filterByKeyword;
var result = defaultResult;
var resultCount = 16777215;
var resultLength = 0;
for (var i = 0, l = candidates.length; i < l; i++)
{
var candidate = candidates[i].substr(1);
var count = candidate in hash ? hash[candidate].length : 0;
if (count < resultCount || count == resultCount && candidate.length > resultLength)
{
result = candidate;
resultCount = count;
resultLength = candidate.length;
}
}
return result;
},
hasFilter: function(filter)
{
return filter.text in this.keywordByFilter;
},
getKeywordForFilter: function(filter)
{
if (filter.text in this.keywordByFilter)
{
return this.keywordByFilter[filter.text];
}
else
{
return null;
}
},
_checkEntryMatch: function(keyword, location, contentType, docDomain, thirdParty)
{
var list = this.filterByKeyword[keyword];
for (var i = 0; i < list.length; i++)
{
var filter = list[i];
if (filter.matches(location, contentType, docDomain, thirdParty))
{
return filter;
}
}
return null;
},
matchesAny: function(location, contentType, docDomain, thirdParty)
{
var candidates = location.toLowerCase().match(/[a-z0-9%]{3,}/g);
if (candidates === null)
{
candidates = [];
}
if (contentType == "DONOTTRACK")
{
candidates.unshift("donottrack");
}
else
{
candidates.push("");
}
for (var i = 0, l = candidates.length; i < l; i++)
{
var substr = candidates[i];
if (substr in this.filterByKeyword)
{
var result = this._checkEntryMatch(substr, location, contentType, docDomain, thirdParty);
if (result)
{
return result;
}
}
}
return null;
}
};
function CombinedMatcher()
{
this.blacklist = new Matcher();
this.whitelist = new Matcher();
this.keys =
{
__proto__: null
};
this.resultCache =
{
__proto__: null
};
}
exports.CombinedMatcher = CombinedMatcher;
CombinedMatcher.maxCacheEntries = 1000;
CombinedMatcher.prototype =
{
blacklist: null,
whitelist: null,
keys: null,
resultCache: null,
cacheEntries: 0,
clear: function()
{
this.blacklist.clear();
this.whitelist.clear();
this.keys =
{
__proto__: null
};
this.resultCache =
{
__proto__: null
};
this.cacheEntries = 0;
},
add: function(filter)
{
if (filter instanceof WhitelistFilter)
{
if (filter.siteKeys)
{
for (var i = 0; i < filter.siteKeys.length; i++)
{
this.keys[filter.siteKeys[i]] = filter.text;
}
}
else
{
this.whitelist.add(filter);
}
}
else
{
this.blacklist.add(filter);
}
if (this.cacheEntries > 0)
{
this.resultCache =
{
__proto__: null
};
this.cacheEntries = 0;
}
},
remove: function(filter)
{
if (filter instanceof WhitelistFilter)
{
if (filter.siteKeys)
{
for (var i = 0; i < filter.siteKeys.length; i++)
{
delete this.keys[filter.siteKeys[i]];
}
}
else
{
this.whitelist.remove(filter);
}
}
else
{
this.blacklist.remove(filter);
}
if (this.cacheEntries > 0)
{
this.resultCache =
{
__proto__: null
};
this.cacheEntries = 0;
}
},
findKeyword: function(filter)
{
if (filter instanceof WhitelistFilter)
{
return this.whitelist.findKeyword(filter);
}
else
{
return this.blacklist.findKeyword(filter);
}
},
hasFilter: function(filter)
{
if (filter instanceof WhitelistFilter)
{
return this.whitelist.hasFilter(filter);
}
else
{
return this.blacklist.hasFilter(filter);
}
},
getKeywordForFilter: function(filter)
{
if (filter instanceof WhitelistFilter)
{
return this.whitelist.getKeywordForFilter(filter);
}
else
{
return this.blacklist.getKeywordForFilter(filter);
}
},
isSlowFilter: function(filter)
{
var matcher = filter instanceof WhitelistFilter ? this.whitelist : this.blacklist;
if (matcher.hasFilter(filter))
{
return !matcher.getKeywordForFilter(filter);
}
else
{
return !matcher.findKeyword(filter);
}
},
matchesAnyInternal: function(location, contentType, docDomain, thirdParty)
{
var candidates = location.toLowerCase().match(/[a-z0-9%]{3,}/g);
if (candidates === null)
{
candidates = [];
}
if (contentType == "DONOTTRACK")
{
candidates.unshift("donottrack");
}
else
{
candidates.push("");
}
var blacklistHit = null;
for (var i = 0, l = candidates.length; i < l; i++)
{
var substr = candidates[i];
if (substr in this.whitelist.filterByKeyword)
{
var result = this.whitelist._checkEntryMatch(substr, location, contentType, docDomain, thirdParty);
if (result)
{
return result;
}
}
if (substr in this.blacklist.filterByKeyword && blacklistHit === null)
{
blacklistHit = this.blacklist._checkEntryMatch(substr, location, contentType, docDomain, thirdParty);
}
}
return blacklistHit;
},
matchesAny: function(location, contentType, docDomain, thirdParty)
{
var key = location + " " + contentType + " " + docDomain + " " + thirdParty;
if (key in this.resultCache)
{
return this.resultCache[key];
}
var result = this.matchesAnyInternal(location, contentType, docDomain, thirdParty);
if (this.cacheEntries >= CombinedMatcher.maxCacheEntries)
{
this.resultCache =
{
__proto__: null
};
this.cacheEntries = 0;
}
this.resultCache[key] = result;
this.cacheEntries++;
return result;
},
matchesByKey: function(location, key, docDomain)
{
key = key.toUpperCase();
if (key in this.keys)
{
var filter = Filter.knownFilters[this.keys[key]];
if (filter && filter.matches(location, "DOCUMENT", docDomain, false))
{
return filter;
}
else
{
return null;
}
}
else
{
return null;
}
}
};
var defaultMatcher = exports.defaultMatcher = new CombinedMatcher();
return exports;
})();
require.scopes["filterListener"] = (function()
{
var exports = {};
var FilterStorage = require("filterStorage").FilterStorage;
var FilterNotifier = require("filterNotifier").FilterNotifier;
var ElemHide = require("elemHide").ElemHide;
var defaultMatcher = require("matcher").defaultMatcher;
var _tempVar19 = require("filterClasses");
var ActiveFilter = _tempVar19.ActiveFilter;
var RegExpFilter = _tempVar19.RegExpFilter;
var ElemHideBase = _tempVar19.ElemHideBase;
var Prefs = require("prefs").Prefs;
var batchMode = false;
var isDirty = 0;
var FilterListener = exports.FilterListener =
{
get batchMode()
{
return batchMode;
},
set batchMode(value)
{
batchMode = value;
flushElemHide();
},
setDirty: function(factor)
{
if (factor == 0 && isDirty > 0)
{
isDirty = 1;
}
else
{
isDirty += factor;
}
if (isDirty >= 1)
{
FilterStorage.saveToDisk();
}
}
};
var HistoryPurgeObserver =
{
observe: function(subject, topic, data)
{
if (topic == "browser:purge-session-history" && Prefs.clearStatsOnHistoryPurge)
{
FilterStorage.resetHitCounts();
FilterListener.setDirty(0);
Prefs.recentReports = [];
}
},
QueryInterface: XPCOMUtils.generateQI([Ci.nsISupportsWeakReference, Ci.nsIObserver])
};
function init()
{
FilterNotifier.addListener(function(action, item, newValue, oldValue)
{
var match = /^(\w+)\.(.*)/.exec(action);
if (match && match[1] == "filter")
{
onFilterChange(match[2], item, newValue, oldValue);
}
else if (match && match[1] == "subscription")
{
onSubscriptionChange(match[2], item, newValue, oldValue);
}
else
{
onGenericChange(action, item);
}
});
var application = require("info").application;
if (application == "chrome")
{
flushElemHide = function(){};
}
else
{
ElemHide.init();
}
FilterStorage.loadFromDisk();
Services.obs.addObserver(HistoryPurgeObserver, "browser:purge-session-history", true);
onShutdown.add(function()
{
Services.obs.removeObserver(HistoryPurgeObserver, "browser:purge-session-history");
});
}
init();
function flushElemHide()
{
if (!batchMode && ElemHide.isDirty)
{
ElemHide.apply();
}
}
function addFilter(filter)
{
if (!(filter instanceof ActiveFilter) || filter.disabled)
{
return;
}
var hasEnabled = false;
for (var i = 0; i < filter.subscriptions.length; i++)
{
if (!filter.subscriptions[i].disabled)
{
hasEnabled = true;
}
}
if (!hasEnabled)
{
return;
}
if (filter instanceof RegExpFilter)
{
defaultMatcher.add(filter);
}
else if (filter instanceof ElemHideBase)
{
ElemHide.add(filter);
}
}
function removeFilter(filter)
{
if (!(filter instanceof ActiveFilter))
{
return;
}
if (!filter.disabled)
{
var hasEnabled = false;
for (var i = 0; i < filter.subscriptions.length; i++)
{
if (!filter.subscriptions[i].disabled)
{
hasEnabled = true;
}
}
if (hasEnabled)
{
return;
}
}
if (filter instanceof RegExpFilter)
{
defaultMatcher.remove(filter);
}
else if (filter instanceof ElemHideBase)
{
ElemHide.remove(filter);
}
}
function onSubscriptionChange(action, subscription, newValue, oldValue)
{
FilterListener.setDirty(1);
if (action != "added" && action != "removed" && action != "disabled" && action != "updated")
{
return;
}
if (action != "removed" && !(subscription.url in FilterStorage.knownSubscriptions))
{
return;
}
if ((action == "added" || action == "removed" || action == "updated") && subscription.disabled)
{
return;
}
if (action == "added" || action == "removed" || action == "disabled")
{
var method = action == "added" || action == "disabled" && newValue == false ? addFilter : removeFilter;
if (subscription.filters)
{
subscription.filters.forEach(method);
}
}
else if (action == "updated")
{
subscription.oldFilters.forEach(removeFilter);
subscription.filters.forEach(addFilter);
}
flushElemHide();
}
function onFilterChange(action, filter, newValue, oldValue)
{
if (action == "hitCount" || action == "lastHit")
{
FilterListener.setDirty(0.002);
}
else
{
FilterListener.setDirty(1);
}
if (action != "added" && action != "removed" && action != "disabled")
{
return;
}
if ((action == "added" || action == "removed") && filter.disabled)
{
return;
}
if (action == "added" || action == "disabled" && newValue == false)
{
addFilter(filter);
}
else
{
removeFilter(filter);
}
flushElemHide();
}
function onGenericChange(action)
{
if (action == "load")
{
isDirty = 0;
defaultMatcher.clear();
ElemHide.clear();
for (var _loopIndex20 = 0; _loopIndex20 < FilterStorage.subscriptions.length; ++_loopIndex20)
{
var subscription = FilterStorage.subscriptions[_loopIndex20];
if (!subscription.disabled)
{
subscription.filters.forEach(addFilter);
}
}
flushElemHide();
}
else if (action == "save")
{
isDirty = 0;
}
}
return exports;
})();
require.scopes["synchronizer"] = (function()
{
var exports = {};
var Utils = require("utils").Utils;
var FilterStorage = require("filterStorage").FilterStorage;
var FilterNotifier = require("filterNotifier").FilterNotifier;
var Prefs = require("prefs").Prefs;
var _tempVar21 = require("filterClasses");
var Filter = _tempVar21.Filter;
var CommentFilter = _tempVar21.CommentFilter;
var _tempVar22 = require("subscriptionClasses");
var Subscription = _tempVar22.Subscription;
var DownloadableSubscription = _tempVar22.DownloadableSubscription;
var MILLISECONDS_IN_SECOND = 1000;
var SECONDS_IN_MINUTE = 60;
var SECONDS_IN_HOUR = 60 * SECONDS_IN_MINUTE;
var SECONDS_IN_DAY = 24 * SECONDS_IN_HOUR;
var INITIAL_DELAY = 6 * SECONDS_IN_MINUTE;
var CHECK_INTERVAL = SECONDS_IN_HOUR;
var MIN_EXPIRATION_INTERVAL = 1 * SECONDS_IN_DAY;
var MAX_EXPIRATION_INTERVAL = 14 * SECONDS_IN_DAY;
var MAX_ABSENSE_INTERVAL = 1 * SECONDS_IN_DAY;
var timer = null;
var executing =
{
__proto__: null
};
var Synchronizer = exports.Synchronizer =
{
init: function()
{
var callback = function()
{
timer.delay = CHECK_INTERVAL * MILLISECONDS_IN_SECOND;
checkSubscriptions();
};
timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
timer.initWithCallback(callback, INITIAL_DELAY * MILLISECONDS_IN_SECOND, Ci.nsITimer.TYPE_REPEATING_SLACK);
onShutdown.add(function()
{
timer.cancel();
});
},
isExecuting: function(url)
{
return url in executing;
},
execute: function(subscription, manual, forceDownload)
{
Utils.runAsync(this.executeInternal, this, subscription, manual, forceDownload);
},
executeInternal: function(subscription, manual, forceDownload)
{
var url = subscription.url;
if (url in executing)
{
return;
}
var newURL = subscription.nextURL;
var hadTemporaryRedirect = false;
subscription.nextURL = null;
var loadFrom = newURL;
var isBaseLocation = true;
if (!loadFrom)
{
loadFrom = url;
}
if (loadFrom == url)
{
if (subscription.alternativeLocations)
{
var options = [
[1, url]
];
var totalWeight = 1;
for (var _loopIndex23 = 0; _loopIndex23 < subscription.alternativeLocations.split(",").length; ++_loopIndex23)
{
var alternative = subscription.alternativeLocations.split(",")[_loopIndex23];
if (!/^https?:\/\//.test(alternative))
{
continue;
}
var weight = 1;
var match = /;q=([\d\.]+)$/.exec(alternative);
if (match)
{
weight = parseFloat(match[1]);
if (isNaN(weight) || !isFinite(weight) || weight < 0)
{
weight = 1;
}
if (weight > 10)
{
weight = 10;
}
alternative = alternative.substr(0, match.index);
}
options.push([weight, alternative]);
totalWeight += weight;
}
var choice = Math.random() * totalWeight;
for (var _loopIndex24 = 0; _loopIndex24 < options.length; ++_loopIndex24)
{
var _tempVar25 = options[_loopIndex24];
var weight = _tempVar25[0];
var alternative = _tempVar25[1];
choice -= weight;
if (choice < 0)
{
loadFrom = alternative;
break;
}
}
isBaseLocation = loadFrom == url;
}
}
else
{
forceDownload = true;
}
var addonVersion = require("info").addonVersion;
loadFrom = loadFrom.replace(/%VERSION%/, "ABP" + addonVersion);
var request = null;
function errorCallback(error)
{
var channelStatus = -1;
try
{
channelStatus = request.channel.status;
}
catch (e){}
var responseStatus = "";
try
{
responseStatus = request.channel.QueryInterface(Ci.nsIHttpChannel).responseStatus;
}
catch (e){}
setError(subscription, error, channelStatus, responseStatus, loadFrom, isBaseLocation, manual);
}
try
{
request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
request.mozBackgroundRequest = true;
request.open("GET", loadFrom);
}
catch (e)
{
errorCallback("synchronize_invalid_url");
return;
}
try
{
request.overrideMimeType("text/plain");
request.channel.loadFlags = request.channel.loadFlags | request.channel.INHIBIT_CACHING | request.channel.VALIDATE_ALWAYS;
if (request.channel instanceof Ci.nsIHttpChannel)
{
request.channel.redirectionLimit = 5;
}
var oldNotifications = request.channel.notificationCallbacks;
var oldEventSink = null;
request.channel.notificationCallbacks =
{
QueryInterface: XPCOMUtils.generateQI([Ci.nsIInterfaceRequestor, Ci.nsIChannelEventSink]),
getInterface: function(iid)
{
if (iid.equals(Ci.nsIChannelEventSink))
{
try
{
oldEventSink = oldNotifications.QueryInterface(iid);
}
catch (e){}
return this;
}
if (oldNotifications)
{
return oldNotifications.QueryInterface(iid);
}
else
{
throw Cr.NS_ERROR_NO_INTERFACE;
}
},
asyncOnChannelRedirect: function(oldChannel, newChannel, flags, callback)
{
if (isBaseLocation && !hadTemporaryRedirect && oldChannel instanceof Ci.nsIHttpChannel)
{
try
{
subscription.alternativeLocations = oldChannel.getResponseHeader("X-Alternative-Locations");
}
catch (e)
{
subscription.alternativeLocations = null;
}
}
if (flags & Ci.nsIChannelEventSink.REDIRECT_TEMPORARY)
{
hadTemporaryRedirect = true;
}
else if (!hadTemporaryRedirect)
{
newURL = newChannel.URI.spec;
}
if (oldEventSink)
{
oldEventSink.asyncOnChannelRedirect(oldChannel, newChannel, flags, callback);
}
else
{
callback.onRedirectVerifyCallback(Cr.NS_OK);
}
}
};
}
catch (e)
{
Cu.reportError(e);
}
if (subscription.lastModified && !forceDownload)
{
request.setRequestHeader("If-Modified-Since", subscription.lastModified);
}
request.addEventListener("error", function(ev)
{
if (onShutdown.done)
{
return;
}
delete executing[url];
try
{
request.channel.notificationCallbacks = null;
}
catch (e){}
errorCallback("synchronize_connection_error");
}, false);
request.addEventListener("load", function(ev)
{
if (onShutdown.done)
{
return;
}
delete executing[url];
try
{
request.channel.notificationCallbacks = null;
}
catch (e){}
if (request.status && request.status != 200 && request.status != 304)
{
errorCallback("synchronize_connection_error");
return;
}
var newFilters = null;
if (request.status != 304)
{
newFilters = readFilters(subscription, request.responseText, errorCallback);
if (!newFilters)
{
return;
}
subscription.lastModified = request.getResponseHeader("Last-Modified");
}
if (isBaseLocation && !hadTemporaryRedirect)
{
subscription.alternativeLocations = request.getResponseHeader("X-Alternative-Locations");
}
subscription.lastSuccess = subscription.lastDownload = Math.round(Date.now() / MILLISECONDS_IN_SECOND);
subscription.downloadStatus = "synchronize_ok";
subscription.errors = 0;
var now = Math.round(((new Date(request.getResponseHeader("Date"))).getTime() || Date.now()) / MILLISECONDS_IN_SECOND);
var expires = Math.round((new Date(request.getResponseHeader("Expires"))).getTime() / MILLISECONDS_IN_SECOND) || 0;
var expirationInterval = expires ? expires - now : 0;
for (var _loopIndex26 = 0; _loopIndex26 < (newFilters || subscription.filters).length; ++_loopIndex26)
{
var filter = (newFilters || subscription.filters)[_loopIndex26];
if (!(filter instanceof CommentFilter))
{
continue;
}
var match = /\bExpires\s*(?::|after)\s*(\d+)\s*(h)?/i.exec(filter.text);
if (match)
{
var interval = parseInt(match[1], 10);
if (match[2])
{
interval *= SECONDS_IN_HOUR;
}
else
{
interval *= SECONDS_IN_DAY;
}
if (interval > expirationInterval)
{
expirationInterval = interval;
}
}
}
expirationInterval = Math.min(Math.max(expirationInterval, MIN_EXPIRATION_INTERVAL), MAX_EXPIRATION_INTERVAL);
subscription.expires = subscription.lastDownload + expirationInterval * 2;
subscription.softExpiration = subscription.lastDownload + Math.round(expirationInterval * (Math.random() * 0.4 + 0.8));
if (newFilters)
{
var fixedTitle = false;
for (var i = 0; i < newFilters.length; i++)
{
var filter = newFilters[i];
if (!(filter instanceof CommentFilter))
{
continue;
}
var match = /^!\s*(\w+)\s*:\s*(.*)/.exec(filter.text);
if (match)
{
var keyword = match[1].toLowerCase();
var value = match[2];
var known = true;
if (keyword == "redirect")
{
if (isBaseLocation && value != url)
{
subscription.nextURL = value;
}
}
else if (keyword == "homepage")
{
var uri = Utils.makeURI(value);
if (uri && (uri.scheme == "http" || uri.scheme == "https"))
{
subscription.homepage = uri.spec;
}
}
else if (keyword == "title")
{
if (value)
{
subscription.title = value;
fixedTitle = true;
}
}
else
{
known = false;
}
if (known)
{
newFilters.splice(i--, 1);
}
}
}
subscription.fixedTitle = fixedTitle;
}
if (isBaseLocation && newURL && newURL != url)
{
var listed = subscription.url in FilterStorage.knownSubscriptions;
if (listed)
{
FilterStorage.removeSubscription(subscription);
}
url = newURL;
var newSubscription = Subscription.fromURL(url);
for (var key in newSubscription)
{
delete newSubscription[key];
}
for (var key in subscription)
{
newSubscription[key] = subscription[key];
}
delete Subscription.knownSubscriptions[subscription.url];
newSubscription.oldSubscription = subscription;
subscription = newSubscription;
subscription.url = url;
if (!(subscription.url in FilterStorage.knownSubscriptions) && listed)
{
FilterStorage.addSubscription(subscription);
}
}
if (newFilters)
{
FilterStorage.updateSubscriptionFilters(subscription, newFilters);
}
delete subscription.oldSubscription;
}, false);
executing[url] = true;
FilterNotifier.triggerListeners("subscription.downloadStatus", subscription);
try
{
request.send(null);
}
catch (e)
{
delete executing[url];
errorCallback("synchronize_connection_error");
return;
}
}
};
Synchronizer.init();
function checkSubscriptions()
{
if (!Prefs.subscriptions_autoupdate)
{
return;
}
var time = Math.round(Date.now() / MILLISECONDS_IN_SECOND);
for (var _loopIndex27 = 0; _loopIndex27 < FilterStorage.subscriptions.length; ++_loopIndex27)
{
var subscription = FilterStorage.subscriptions[_loopIndex27];
if (!(subscription instanceof DownloadableSubscription))
{
continue;
}
if (subscription.lastCheck && time - subscription.lastCheck > MAX_ABSENSE_INTERVAL)
{
subscription.softExpiration += time - subscription.lastCheck;
}
subscription.lastCheck = time;
if (subscription.expires - time > MAX_EXPIRATION_INTERVAL)
{
subscription.expires = time + MAX_EXPIRATION_INTERVAL;
}
if (subscription.softExpiration - time > MAX_EXPIRATION_INTERVAL)
{
subscription.softExpiration = time + MAX_EXPIRATION_INTERVAL;
}
if (subscription.softExpiration > time && subscription.expires > time)
{
continue;
}
if (time - subscription.lastDownload >= MIN_EXPIRATION_INTERVAL)
{
Synchronizer.execute(subscription, false);
}
}
}
function readFilters(subscription, text, errorCallback)
{
var lines = text.split(/[\r\n]+/);
var match = /\[Adblock(?:\s*Plus\s*([\d\.]+)?)?\]/i.exec(lines[0]);
if (!match)
{
errorCallback("synchronize_invalid_data");
return null;
}
var minVersion = match[1];
for (var i = 0; i < lines.length; i++)
{
var match = /!\s*checksum[\s\-:]+([\w\+\/]+)/i.exec(lines[i]);
if (match)
{
lines.splice(i, 1);
var checksum = Utils.generateChecksum(lines);
if (checksum && checksum != match[1])
{
errorCallback("synchronize_checksum_mismatch");
return null;
}
break;
}
}
delete subscription.requiredVersion;
delete subscription.upgradeRequired;
if (minVersion)
{
var addonVersion = require("info").addonVersion;
subscription.requiredVersion = minVersion;
if (Services.vc.compare(minVersion, addonVersion) > 0)
{
subscription.upgradeRequired = true;
}
}
lines.shift();
var result = [];
for (var _loopIndex28 = 0; _loopIndex28 < lines.length; ++_loopIndex28)
{
var line = lines[_loopIndex28];
line = Filter.normalize(line);
if (line)
{
result.push(Filter.fromText(line));
}
}
return result;
}
function setError(subscription, error, channelStatus, responseStatus, downloadURL, isBaseLocation, manual)
{
if (!isBaseLocation)
{
subscription.alternativeLocations = null;
}
try
{
Cu.reportError("Adblock Plus: Downloading filter subscription " + subscription.title + " failed (" + Utils.getString(error) + ")\n" + "Download address: " + downloadURL + "\n" + "Channel status: " + channelStatus + "\n" + "Server response: " + responseStatus);
}
catch (e){}
subscription.lastDownload = Math.round(Date.now() / MILLISECONDS_IN_SECOND);
subscription.downloadStatus = error;
if (!manual)
{
if (error == "synchronize_checksum_mismatch")
{
subscription.errors = 0;
}
else
{
subscription.errors++;
}
if (subscription.errors >= Prefs.subscriptions_fallbackerrors && /^https?:\/\//i.test(subscription.url))
{
subscription.errors = 0;
var fallbackURL = Prefs.subscriptions_fallbackurl;
var addonVersion = require("info").addonVersion;
fallbackURL = fallbackURL.replace(/%VERSION%/g, encodeURIComponent(addonVersion));
fallbackURL = fallbackURL.replace(/%SUBSCRIPTION%/g, encodeURIComponent(subscription.url));
fallbackURL = fallbackURL.replace(/%URL%/g, encodeURIComponent(downloadURL));
fallbackURL = fallbackURL.replace(/%ERROR%/g, encodeURIComponent(error));
fallbackURL = fallbackURL.replace(/%CHANNELSTATUS%/g, encodeURIComponent(channelStatus));
fallbackURL = fallbackURL.replace(/%RESPONSESTATUS%/g, encodeURIComponent(responseStatus));
var request = Cc["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(Ci.nsIXMLHttpRequest);
request.mozBackgroundRequest = true;
request.open("GET", fallbackURL);
request.overrideMimeType("text/plain");
request.channel.loadFlags = request.channel.loadFlags | request.channel.INHIBIT_CACHING | request.channel.VALIDATE_ALWAYS;
request.addEventListener("load", function(ev)
{
if (onShutdown.done)
{
return;
}
if (!(subscription.url in FilterStorage.knownSubscriptions))
{
return;
}
var match = /^(\d+)(?:\s+(\S+))?$/.exec(request.responseText);
if (match && match[1] == "301" && match[2])
{
subscription.nextURL = match[2];
}
else if (match && match[1] == "410")
{
var data = "[Adblock]\n" + subscription.filters.map(function(f)
{
return f.text;
}).join("\n");
var url = "data:text/plain," + encodeURIComponent(data);
var newSubscription = Subscription.fromURL(url);
newSubscription.title = subscription.title;
newSubscription.disabled = subscription.disabled;
FilterStorage.removeSubscription(subscription);
FilterStorage.addSubscription(newSubscription);
Synchronizer.execute(newSubscription);
}
}, false);
request.send(null);
}
}
}
return exports;
})();
var publicSuffixes = {
"0.bg": 1,
"1.bg": 1,
"2.bg": 1,
"2000.hu": 1,
"3.bg": 1,
"4.bg": 1,
"5.bg": 1,
"6.bg": 1,
"6bone.pl": 1,
"7.bg": 1,
"8.bg": 1,
"9.bg": 1,
"a.bg": 1,
"a.se": 1,
"aa.no": 1,
"aarborte.no": 1,
"ab.ca": 1,
"abashiri.hokkaido.jp": 1,
"abeno.osaka.jp": 1,
"abiko.chiba.jp": 1,
"abira.hokkaido.jp": 1,
"abo.pa": 1,
"abu.yamaguchi.jp": 1,
"ac.ae": 1,
"ac.at": 1,
"ac.be": 1,
"ac.ci": 1,
"ac.cn": 1,
"ac.cr": 1,
"ac.gn": 1,
"ac.id": 1,
"ac.im": 1,
"ac.in": 1,
"ac.ir": 1,
"ac.jp": 1,
"ac.kr": 1,
"ac.ma": 1,
"ac.me": 1,
"ac.mu": 1,
"ac.mw": 1,
"ac.ng": 1,
"ac.pa": 1,
"ac.pr": 1,
"ac.rs": 1,
"ac.ru": 1,
"ac.rw": 1,
"ac.se": 1,
"ac.sz": 1,
"ac.th": 1,
"ac.tj": 1,
"ac.tz": 1,
"ac.ug": 1,
"ac.vn": 1,
"aca.pro": 1,
"academy.museum": 1,
"accident-investigation.aero": 1,
"accident-prevention.aero": 1,
"achi.nagano.jp": 1,
"act.au": 1,
"act.edu.au": 1,
"act.gov.au": 1,
"ad.jp": 1,
"adachi.tokyo.jp": 1,
"adm.br": 1,
"adult.ht": 1,
"adv.br": 1,
"adygeya.ru": 1,
"ae.org": 1,
"aejrie.no": 1,
"aero.mv": 1,
"aero.tt": 1,
"aerobatic.aero": 1,
"aeroclub.aero": 1,
"aerodrome.aero": 1,
"aeroport.fr": 1,
"afjord.no": 1,
"ag.it": 1,
"aga.niigata.jp": 1,
"agano.niigata.jp": 1,
"agdenes.no": 1,
"agematsu.nagano.jp": 1,
"agents.aero": 1,
"agr.br": 1,
"agrar.hu": 1,
"agriculture.museum": 1,
"agrigento.it": 1,
"agrinet.tn": 1,
"agro.pl": 1,
"aguni.okinawa.jp": 1,
"ah.cn": 1,
"ah.no": 1,
"aibetsu.hokkaido.jp": 1,
"aichi.jp": 1,
"aid.pl": 1,
"aikawa.kanagawa.jp": 1,
"ainan.ehime.jp": 1,
"aioi.hyogo.jp": 1,
"aip.ee": 1,
"air-surveillance.aero": 1,
"air-traffic-control.aero": 1,
"air.museum": 1,
"aircraft.aero": 1,
"airguard.museum": 1,
"airline.aero": 1,
"airport.aero": 1,
"airtraffic.aero": 1,
"aisai.aichi.jp": 1,
"aisho.shiga.jp": 1,
"aizubange.fukushima.jp": 1,
"aizumi.tokushima.jp": 1,
"aizumisato.fukushima.jp": 1,
"aizuwakamatsu.fukushima.jp": 1,
"ak.us": 1,
"akabira.hokkaido.jp": 1,
"akagi.shimane.jp": 1,
"akaiwa.okayama.jp": 1,
"akashi.hyogo.jp": 1,
"aki.kochi.jp": 1,
"akiruno.tokyo.jp": 1,
"akishima.tokyo.jp": 1,
"akita.akita.jp": 1,
"akita.jp": 1,
"akkeshi.hokkaido.jp": 1,
"aknoluokta.no": 1,
"ako.hyogo.jp": 1,
"akrehamn.no": 1,
"akune.kagoshima.jp": 1,
"al.it": 1,
"al.no": 1,
"al.us": 1,
"alabama.museum": 1,
"alaheadju.no": 1,
"aland.fi": 1,
"alaska.museum": 1,
"alessandria.it": 1,
"alesund.no": 1,
"algard.no": 1,
"alstahaug.no": 1,
"alta.no": 1,
"altai.ru": 1,
"alto-adige.it": 1,
"altoadige.it": 1,
"alvdal.no": 1,
"am.br": 1,
"ama.aichi.jp": 1,
"ama.shimane.jp": 1,
"amagasaki.hyogo.jp": 1,
"amakusa.kumamoto.jp": 1,
"amami.kagoshima.jp": 1,
"amber.museum": 1,
"ambulance.aero": 1,
"ambulance.museum": 1,
"american.museum": 1,
"americana.museum": 1,
"americanantiques.museum": 1,
"americanart.museum": 1,
"ami.ibaraki.jp": 1,
"amli.no": 1,
"amot.no": 1,
"amsterdam.museum": 1,
"amur.ru": 1,
"amursk.ru": 1,
"amusement.aero": 1,
"an.it": 1,
"anamizu.ishikawa.jp": 1,
"anan.nagano.jp": 1,
"anan.tokushima.jp": 1,
"ancona.it": 1,
"and.museum": 1,
"andasuolo.no": 1,
"andebu.no": 1,
"ando.nara.jp": 1,
"andoy.no": 1,
"andria-barletta-trani.it": 1,
"andria-trani-barletta.it": 1,
"andriabarlettatrani.it": 1,
"andriatranibarletta.it": 1,
"and\u00f8y.no": 1,
"anjo.aichi.jp": 1,
"annaka.gunma.jp": 1,
"annefrank.museum": 1,
"anpachi.gifu.jp": 1,
"anthro.museum": 1,
"anthropology.museum": 1,
"antiques.museum": 1,
"ao.it": 1,
"aogaki.hyogo.jp": 1,
"aogashima.tokyo.jp": 1,
"aoki.nagano.jp": 1,
"aomori.aomori.jp": 1,
"aomori.jp": 1,
"aosta.it": 1,
"aoste.it": 1,
"ap.it": 1,
"appspot.com": 1,
"aq.it": 1,
"aquarium.museum": 1,
"aquila.it": 1,
"ar": 2,
"ar.com": 1,
"ar.it": 1,
"ar.us": 1,
"arai.shizuoka.jp": 1,
"arakawa.saitama.jp": 1,
"arakawa.tokyo.jp": 1,
"arao.kumamoto.jp": 1,
"arboretum.museum": 1,
"archaeological.museum": 1,
"archaeology.museum": 1,
"architecture.museum": 1,
"ardal.no": 1,
"aremark.no": 1,
"arendal.no": 1,
"arezzo.it": 1,
"ariake.saga.jp": 1,
"arida.wakayama.jp": 1,
"aridagawa.wakayama.jp": 1,
"arita.saga.jp": 1,
"arkhangelsk.ru": 1,
"arna.no": 1,
"arq.br": 1,
"art.br": 1,
"art.do": 1,
"art.dz": 1,
"art.ht": 1,
"art.museum": 1,
"art.pl": 1,
"art.sn": 1,
"artanddesign.museum": 1,
"artcenter.museum": 1,
"artdeco.museum": 1,
"arteducation.museum": 1,
"artgallery.museum": 1,
"arts.co": 1,
"arts.museum": 1,
"arts.nf": 1,
"arts.ro": 1,
"artsandcrafts.museum": 1,
"as.us": 1,
"asago.hyogo.jp": 1,
"asahi.chiba.jp": 1,
"asahi.ibaraki.jp": 1,
"asahi.mie.jp": 1,
"asahi.nagano.jp": 1,
"asahi.toyama.jp": 1,
"asahi.yamagata.jp": 1,
"asahikawa.hokkaido.jp": 1,
"asaka.saitama.jp": 1,
"asakawa.fukushima.jp": 1,
"asakuchi.okayama.jp": 1,
"asaminami.hiroshima.jp": 1,
"ascoli-piceno.it": 1,
"ascolipiceno.it": 1,
"aseral.no": 1,
"ashibetsu.hokkaido.jp": 1,
"ashikaga.tochigi.jp": 1,
"ashiya.fukuoka.jp": 1,
"ashiya.hyogo.jp": 1,
"ashoro.hokkaido.jp": 1,
"asker.no": 1,
"askim.no": 1,
"askoy.no": 1,
"askvoll.no": 1,
"ask\u00f8y.no": 1,
"asmatart.museum": 1,
"asn.au": 1,
"asn.lv": 1,
"asnes.no": 1,
"aso.kumamoto.jp": 1,
"ass.km": 1,
"assabu.hokkaido.jp": 1,
"assassination.museum": 1,
"assedic.fr": 1,
"assisi.museum": 1,
"assn.lk": 1,
"asso.bj": 1,
"asso.ci": 1,
"asso.dz": 1,
"asso.fr": 1,
"asso.gp": 1,
"asso.ht": 1,
"asso.km": 1,
"asso.mc": 1,
"asso.nc": 1,
"asso.re": 1,
"association.aero": 1,
"association.museum": 1,
"asti.it": 1,
"astrakhan.ru": 1,
"astronomy.museum": 1,
"asuke.aichi.jp": 1,
"at-band-camp.net": 1,
"at.it": 1,
"atami.shizuoka.jp": 1,
"ath.cx": 1,
"atlanta.museum": 1,
"atm.pl": 1,
"ato.br": 1,
"atsugi.kanagawa.jp": 1,
"atsuma.hokkaido.jp": 1,
"audnedaln.no": 1,
"augustow.pl": 1,
"aukra.no": 1,
"aure.no": 1,
"aurland.no": 1,
"aurskog-holand.no": 1,
"aurskog-h\u00f8land.no": 1,
"austevoll.no": 1,
"austin.museum": 1,
"australia.museum": 1,
"austrheim.no": 1,
"author.aero": 1,
"auto.pl": 1,
"automotive.museum": 1,
"av.it": 1,
"avellino.it": 1,
"averoy.no": 1,
"aver\u00f8y.no": 1,
"aviation.museum": 1,
"avocat.fr": 1,
"avoues.fr": 1,
"awaji.hyogo.jp": 1,
"axis.museum": 1,
"aya.miyazaki.jp": 1,
"ayabe.kyoto.jp": 1,
"ayagawa.kagawa.jp": 1,
"ayase.kanagawa.jp": 1,
"az.us": 1,
"azumino.nagano.jp": 1,
"a\u00e9roport.ci": 1,
"b.bg": 1,
"b.br": 1,
"b.se": 1,
"ba.it": 1,
"babia-gora.pl": 1,
"badaddja.no": 1,
"badajoz.museum": 1,
"baghdad.museum": 1,
"bahcavuotna.no": 1,
"bahccavuotna.no": 1,
"bahn.museum": 1,
"baidar.no": 1,
"baikal.ru": 1,
"bajddar.no": 1,
"balat.no": 1,
"bale.museum": 1,
"balestrand.no": 1,
"ballangen.no": 1,
"ballooning.aero": 1,
"balsan.it": 1,
"balsfjord.no": 1,
"baltimore.museum": 1,
"bamble.no": 1,
"bandai.fukushima.jp": 1,
"bando.ibaraki.jp": 1,
"bar.pro": 1,
"barcelona.museum": 1,
"bardu.no": 1,
"bari.it": 1,
"barletta-trani-andria.it": 1,
"barlettatraniandria.it": 1,
"barreau.bj": 1,
"barrel-of-knowledge.info": 1,
"barrell-of-knowledge.info": 1,
"barum.no": 1,
"baseball.museum": 1,
"basel.museum": 1,
"bashkiria.ru": 1,
"baths.museum": 1,
"bato.tochigi.jp": 1,
"batsfjord.no": 1,
"bauern.museum": 1,
"bc.ca": 1,
"bd": 2,
"bd.se": 1,
"bearalvahki.no": 1,
"bearalv\u00e1hki.no": 1,
"beardu.no": 1,
"beauxarts.museum": 1,
"bedzin.pl": 1,
"beeldengeluid.museum": 1,
"beiarn.no": 1,
"belau.pw": 1,
"belgorod.ru": 1,
"bellevue.museum": 1,
"belluno.it": 1,
"benevento.it": 1,
"beppu.oita.jp": 1,
"berg.no": 1,
"bergamo.it": 1,
"bergbau.museum": 1,
"bergen.no": 1,
"berkeley.museum": 1,
"berlevag.no": 1,
"berlev\u00e5g.no": 1,
"berlin.museum": 1,
"bern.museum": 1,
"beskidy.pl": 1,
"better-than.tv": 1,
"bg.it": 1,
"bi.it": 1,
"bialowieza.pl": 1,
"bialystok.pl": 1,
"bibai.hokkaido.jp": 1,
"bible.museum": 1,
"biei.hokkaido.jp": 1,
"bielawa.pl": 1,
"biella.it": 1,
"bieszczady.pl": 1,
"bievat.no": 1,
"biev\u00e1t.no": 1,
"bifuka.hokkaido.jp": 1,
"bihoro.hokkaido.jp": 1,
"bilbao.museum": 1,
"bill.museum": 1,
"bindal.no": 1,
"bio.br": 1,
"bir.ru": 1,
"biratori.hokkaido.jp": 1,
"birdart.museum": 1,
"birkenes.no": 1,
"birthplace.museum": 1,
"biz.at": 1,
"biz.az": 1,
"biz.bb": 1,
"biz.ki": 1,
"biz.mv": 1,
"biz.mw": 1,
"biz.nr": 1,
"biz.pk": 1,
"biz.pl": 1,
"biz.pr": 1,
"biz.tj": 1,
"biz.tt": 1,
"biz.vn": 1,
"bizen.okayama.jp": 1,
"bj.cn": 1,
"bjarkoy.no": 1,
"bjark\u00f8y.no": 1,
"bjerkreim.no": 1,
"bjugn.no": 1,
"bl.it": 1,
"bl.uk": 0,
"blog.br": 1,
"blogdns.com": 1,
"blogdns.net": 1,
"blogdns.org": 1,
"blogsite.org": 1,
"bmd.br": 1,
"bn": 2,
"bn.it": 1,
"bo.it": 1,
"bo.nordland.no": 1,
"bo.telemark.no": 1,
"bodo.no": 1,
"bod\u00f8.no": 1,
"bokn.no": 1,
"boldlygoingnowhere.org": 1,
"boleslawiec.pl": 1,
"bologna.it": 1,
"bolt.hu": 1,
"bolzano.it": 1,
"bomlo.no": 1,
"bonn.museum": 1,
"boston.museum": 1,
"botanical.museum": 1,
"botanicalgarden.museum": 1,
"botanicgarden.museum": 1,
"botany.museum": 1,
"bozen.it": 1,
"br.com": 1,
"br.it": 1,
"brand.se": 1,
"brandywinevalley.museum": 1,
"brasil.museum": 1,
"bremanger.no": 1,
"brescia.it": 1,
"brindisi.it": 1,
"bristol.museum": 1,
"british-library.uk": 0,
"british.museum": 1,
"britishcolumbia.museum": 1,
"broadcast.museum": 1,
"broke-it.net": 1,
"broker.aero": 1,
"bronnoy.no": 1,
"bronnoysund.no": 1,
"brumunddal.no": 1,
"brunel.museum": 1,
"brussel.museum": 1,
"brussels.museum": 1,
"bruxelles.museum": 1,
"bryansk.ru": 1,
"bryne.no": 1,
"br\u00f8nn\u00f8y.no": 1,
"br\u00f8nn\u00f8ysund.no": 1,
"bs.it": 1,
"bt.it": 1,
"bu.no": 1,
"budejju.no": 1,
"building.museum": 1,
"bungoono.oita.jp": 1,
"bungotakada.oita.jp": 1,
"bunkyo.tokyo.jp": 1,
"burghof.museum": 1,
"buryatia.ru": 1,
"bus.museum": 1,
"busan.kr": 1,
"bushey.museum": 1,
"buyshouses.net": 1,
"buzen.fukuoka.jp": 1,
"bv.nl": 1,
"bydgoszcz.pl": 1,
"bygland.no": 1,
"bykle.no": 1,
"bytom.pl": 1,
"bz.it": 1,
"b\u00e1hcavuotna.no": 1,
"b\u00e1hccavuotna.no": 1,
"b\u00e1id\u00e1r.no": 1,
"b\u00e1jddar.no": 1,
"b\u00e1l\u00e1t.no": 1,
"b\u00e5d\u00e5ddj\u00e5.no": 1,
"b\u00e5tsfjord.no": 1,
"b\u00e6rum.no": 1,
"b\u00f8.nordland.no": 1,
"b\u00f8.telemark.no": 1,
"b\u00f8mlo.no": 1,
"c.bg": 1,
"c.la": 1,
"c.se": 1,
"ca.it": 1,
"ca.na": 1,
"ca.us": 1,
"caa.aero": 1,
"cadaques.museum": 1,
"cagliari.it": 1,
"cahcesuolo.no": 1,
"california.museum": 1,
"caltanissetta.it": 1,
"cambridge.museum": 1,
"campidano-medio.it": 1,
"campidanomedio.it": 1,
"campobasso.it": 1,
"can.museum": 1,
"canada.museum": 1,
"capebreton.museum": 1,
"carbonia-iglesias.it": 1,
"carboniaiglesias.it": 1,
"cargo.aero": 1,
"carrara-massa.it": 1,
"carraramassa.it": 1,
"carrier.museum": 1,
"cartoonart.museum": 1,
"casadelamoneda.museum": 1,
"caserta.it": 1,
"casino.hu": 1,
"castle.museum": 1,
"castres.museum": 1,
"catania.it": 1,
"catanzaro.it": 1,
"catering.aero": 1,
"cb.it": 1,
"cbg.ru": 1,
"cc.ak.us": 1,
"cc.al.us": 1,
"cc.ar.us": 1,
"cc.as.us": 1,
"cc.az.us": 1,
"cc.ca.us": 1,
"cc.co.us": 1,
"cc.ct.us": 1,
"cc.dc.us": 1,
"cc.de.us": 1,
"cc.fl.us": 1,
"cc.ga.us": 1,
"cc.gu.us": 1,
"cc.hi.us": 1,
"cc.ia.us": 1,
"cc.id.us": 1,
"cc.il.us": 1,
"cc.in.us": 1,
"cc.ks.us": 1,
"cc.ky.us": 1,
"cc.la.us": 1,
"cc.ma.us": 1,
"cc.md.us": 1,
"cc.me.us": 1,
"cc.mi.us": 1,
"cc.mn.us": 1,
"cc.mo.us": 1,
"cc.ms.us": 1,
"cc.mt.us": 1,
"cc.na": 1,
"cc.nc.us": 1,
"cc.nd.us": 1,
"cc.ne.us": 1,
"cc.nh.us": 1,
"cc.nj.us": 1,
"cc.nm.us": 1,
"cc.nv.us": 1,
"cc.ny.us": 1,
"cc.oh.us": 1,
"cc.ok.us": 1,
"cc.or.us": 1,
"cc.pa.us": 1,
"cc.pr.us": 1,
"cc.ri.us": 1,
"cc.sc.us": 1,
"cc.sd.us": 1,
"cc.tn.us": 1,
"cc.tx.us": 1,
"cc.ut.us": 1,
"cc.va.us": 1,
"cc.vi.us": 1,
"cc.vt.us": 1,
"cc.wa.us": 1,
"cc.wi.us": 1,
"cc.wv.us": 1,
"cc.wy.us": 1,
"cci.fr": 1,
"ce.it": 1,
"cechire.com": 1,
"celtic.museum": 1,
"center.museum": 1,
"certification.aero": 1,
"cesena-forli.it": 1,
"cesenaforli.it": 1,
"ch.it": 1,
"chambagri.fr": 1,
"championship.aero": 1,
"charter.aero": 1,
"chattanooga.museum": 1,
"chel.ru": 1,
"cheltenham.museum": 1,
"chelyabinsk.ru": 1,
"cherkassy.ua": 1,
"cherkasy.ua": 1,
"chernigov.ua": 1,
"chernihiv.ua": 1,
"chernivtsi.ua": 1,
"chernovtsy.ua": 1,
"chesapeakebay.museum": 1,
"chiba.jp": 1,
"chicago.museum": 1,
"chichibu.saitama.jp": 1,
"chieti.it": 1,
"chigasaki.kanagawa.jp": 1,
"chihayaakasaka.osaka.jp": 1,
"chijiwa.nagasaki.jp": 1,
"chikugo.fukuoka.jp": 1,
"chikuho.fukuoka.jp": 1,
"chikuhoku.nagano.jp": 1,
"chikujo.fukuoka.jp": 1,
"chikuma.nagano.jp": 1,
"chikusei.ibaraki.jp": 1,
"chikushino.fukuoka.jp": 1,
"chikuzen.fukuoka.jp": 1,
"children.museum": 1,
"childrens.museum": 1,
"childrensgarden.museum": 1,
"chino.nagano.jp": 1,
"chippubetsu.hokkaido.jp": 1,
"chiropractic.museum": 1,
"chirurgiens-dentistes.fr": 1,
"chiryu.aichi.jp": 1,
"chita.aichi.jp": 1,
"chita.ru": 1,
"chitose.hokkaido.jp": 1,
"chiyoda.gunma.jp": 1,
"chiyoda.tokyo.jp": 1,
"chizu.tottori.jp": 1,
"chocolate.museum": 1,
"chofu.tokyo.jp": 1,
"chonan.chiba.jp": 1,
"chosei.chiba.jp": 1,
"choshi.chiba.jp": 1,
"choyo.kumamoto.jp": 1,
"christiansburg.museum": 1,
"chtr.k12.ma.us": 1,
"chukotka.ru": 1,
"chungbuk.kr": 1,
"chungnam.kr": 1,
"chuo.chiba.jp": 1,
"chuo.fukuoka.jp": 1,
"chuo.osaka.jp": 1,
"chuo.tokyo.jp": 1,
"chuo.yamanashi.jp": 1,
"chuvashia.ru": 1,
"ci.it": 1,
"cieszyn.pl": 1,
"cim.br": 1,
"cincinnati.museum": 1,
"cinema.museum": 1,
"circus.museum": 1,
"city.hu": 1,
"city.kawasaki.jp": 0,
"city.kitakyushu.jp": 0,
"city.kobe.jp": 0,
"city.nagoya.jp": 0,
"city.sapporo.jp": 0,
"city.sendai.jp": 0,
"city.yokohama.jp": 0,
"civilaviation.aero": 1,
"civilisation.museum": 1,
"civilization.museum": 1,
"civilwar.museum": 1,
"ck": 2,
"ck.ua": 1,
"cl.it": 1,
"clinton.museum": 1,
"clock.museum": 1,
"club.aero": 1,
"club.tw": 1,
"cmw.ru": 1,
"cn.com": 1,
"cn.it": 1,
"cn.ua": 1,
"cng.br": 1,
"cnt.br": 1,
"co.ae": 1,
"co.ag": 1,
"co.ao": 1,
"co.at": 1,
"co.ba": 1,
"co.bi": 1,
"co.bw": 1,
"co.ca": 1,
"co.ci": 1,
"co.cl": 1,
"co.cr": 1,
"co.gg": 1,
"co.gy": 1,
"co.hu": 1,
"co.id": 1,
"co.im": 1,
"co.in": 1,
"co.ir": 1,
"co.it": 1,
"co.je": 1,
"co.jp": 1,
"co.kr": 1,
"co.lc": 1,
"co.ls": 1,
"co.ma": 1,
"co.me": 1,
"co.mu": 1,
"co.mw": 1,
"co.na": 1,
"co.nl": 1,
"co.no": 1,
"co.pl": 1,
"co.pn": 1,
"co.pw": 1,
"co.rs": 1,
"co.rw": 1,
"co.st": 1,
"co.sz": 1,
"co.th": 1,
"co.tj": 1,
"co.tm": 1,
"co.tt": 1,
"co.tz": 1,
"co.ua": 1,
"co.ug": 1,
"co.us": 1,
"co.uz": 1,
"co.ve": 1,
"co.vi": 1,
"coal.museum": 1,
"coastaldefence.museum": 1,
"cody.museum": 1,
"coldwar.museum": 1,
"collection.museum": 1,
"colonialwilliamsburg.museum": 1,
"coloradoplateau.museum": 1,
"columbia.museum": 1,
"columbus.museum": 1,
"com.ac": 1,
"com.af": 1,
"com.ag": 1,
"com.ai": 1,
"com.al": 1,
"com.an": 1,
"com.au": 1,
"com.aw": 1,
"com.az": 1,
"com.ba": 1,
"com.bb": 1,
"com.bh": 1,
"com.bi": 1,
"com.bm": 1,
"com.bo": 1,
"com.br": 1,
"com.bs": 1,
"com.bt": 1,
"com.by": 1,
"com.bz": 1,
"com.ci": 1,
"com.cn": 1,
"com.co": 1,
"com.cu": 1,
"com.de": 1,
"com.dm": 1,
"com.do": 1,
"com.dz": 1,
"com.ec": 1,
"com.ee": 1,
"com.eg": 1,
"com.es": 1,
"com.fr": 1,
"com.ge": 1,
"com.gh": 1,
"com.gi": 1,
"com.gn": 1,
"com.gp": 1,
"com.gr": 1,
"com.gy": 1,
"com.hk": 1,
"com.hn": 1,
"com.hr": 1,
"com.ht": 1,
"com.io": 1,
"com.iq": 1,
"com.is": 1,
"com.jo": 1,
"com.kg": 1,
"com.ki": 1,
"com.km": 1,
"com.kp": 1,
"com.ky": 1,
"com.kz": 1,
"com.la": 1,
"com.lb": 1,
"com.lc": 1,
"com.lk": 1,
"com.lr": 1,
"com.lv": 1,
"com.ly": 1,
"com.mg": 1,
"com.mk": 1,
"com.ml": 1,
"com.mo": 1,
"com.mu": 1,
"com.mv": 1,
"com.mw": 1,
"com.mx": 1,
"com.my": 1,
"com.na": 1,
"com.nf": 1,
"com.ng": 1,
"com.nr": 1,
"com.pa": 1,
"com.pe": 1,
"com.pf": 1,
"com.ph": 1,
"com.pk": 1,
"com.pl": 1,
"com.pr": 1,
"com.ps": 1,
"com.pt": 1,
"com.qa": 1,
"com.re": 1,
"com.ro": 1,
"com.ru": 1,
"com.rw": 1,
"com.sa": 1,
"com.sb": 1,
"com.sc": 1,
"com.sd": 1,
"com.sg": 1,
"com.sh": 1,
"com.sl": 1,
"com.sn": 1,
"com.so": 1,
"com.st": 1,
"com.sy": 1,
"com.tj": 1,
"com.tm": 1,
"com.tn": 1,
"com.to": 1,
"com.tt": 1,
"com.tw": 1,
"com.ua": 1,
"com.ug": 1,
"com.uy": 1,
"com.uz": 1,
"com.vc": 1,
"com.ve": 1,
"com.vi": 1,
"com.vn": 1,
"com.ws": 1,
"communication.museum": 1,
"communications.museum": 1,
"community.museum": 1,
"como.it": 1,
"computer.museum": 1,
"computerhistory.museum": 1,
"comunica\u00e7\u00f5es.museum": 1,
"conf.au": 1,
"conf.lv": 1,
"conference.aero": 1,
"congresodelalengua3.ar": 0,
"consulado.st": 1,
"consultant.aero": 1,
"consulting.aero": 1,
"contemporary.museum": 1,
"contemporaryart.museum": 1,
"control.aero": 1,
"convent.museum": 1,
"coop.br": 1,
"coop.ht": 1,
"coop.km": 1,
"coop.mv": 1,
"coop.mw": 1,
"coop.tt": 1,
"copenhagen.museum": 1,
"corporation.museum": 1,
"correios-e-telecomunica\u00e7\u00f5es.museum": 1,
"corvette.museum": 1,
"cosenza.it": 1,
"costume.museum": 1,
"council.aero": 1,
"countryestate.museum": 1,
"county.museum": 1,
"cpa.pro": 1,
"cq.cn": 1,
"cr.it": 1,
"cr.ua": 1,
"crafts.museum": 1,
"cranbrook.museum": 1,
"creation.museum": 1,
"cremona.it": 1,
"crew.aero": 1,
"crimea.ua": 1,
"crotone.it": 1,
"cs.it": 1,
"csiro.au": 1,
"ct.it": 1,
"ct.us": 1,
"cultural.museum": 1,
"culturalcenter.museum": 1,
"culture.museum": 1,
"cuneo.it": 1,
"cv.ua": 1,
"cy": 2,
"cyber.museum": 1,
"cymru.museum": 1,
"cz.it": 1,
"czeladz.pl": 1,
"czest.pl": 1,
"d.bg": 1,
"d.se": 1,
"daegu.kr": 1,
"daejeon.kr": 1,
"dagestan.ru": 1,
"daigo.ibaraki.jp": 1,
"daisen.akita.jp": 1,
"daito.osaka.jp": 1,
"daiwa.hiroshima.jp": 1,
"dali.museum": 1,
"dallas.museum": 1,
"database.museum": 1,
"date.fukushima.jp": 1,
"date.hokkaido.jp": 1,
"davvenjarga.no": 1,
"davvenj\u00e1rga.no": 1,
"davvesiida.no": 1,
"dazaifu.fukuoka.jp": 1,
"dc.us": 1,
"ddr.museum": 1,
"de.com": 1,
"de.us": 1,
"deatnu.no": 1,
"decorativearts.museum": 1,
"defense.tn": 1,
"delaware.museum": 1,
"dell-ogliastra.it": 1,
"dellogliastra.it": 1,
"delmenhorst.museum": 1,
"denmark.museum": 1,
"dep.no": 1,
"depot.museum": 1,
"design.aero": 1,
"design.museum": 1,
"detroit.museum": 1,
"dgca.aero": 1,
"dielddanuorri.no": 1,
"dinosaur.museum": 1,
"discovery.museum": 1,
"divtasvuodna.no": 1,
"divttasvuotna.no": 1,
"dlugoleka.pl": 1,
"dn.ua": 1,
"dnepropetrovsk.ua": 1,
"dni.us": 1,
"dnipropetrovsk.ua": 1,
"dnsalias.com": 1,
"dnsalias.net": 1,
"dnsalias.org": 1,
"dnsdojo.com": 1,
"dnsdojo.net": 1,
"dnsdojo.org": 1,
"does-it.net": 1,
"doesntexist.com": 1,
"doesntexist.org": 1,
"dolls.museum": 1,
"dominic.ua": 1,
"donetsk.ua": 1,
"donna.no": 1,
"donostia.museum": 1,
"dontexist.com": 1,
"dontexist.net": 1,
"dontexist.org": 1,
"doomdns.com": 1,
"doomdns.org": 1,
"doshi.yamanashi.jp": 1,
"dovre.no": 1,
"dp.ua": 1,
"dr.na": 1,
"drammen.no": 1,
"drangedal.no": 1,
"dreamhosters.com": 1,
"drobak.no": 1,
"dr\u00f8bak.no": 1,
"dudinka.ru": 1,
"durham.museum": 1,
"dvrdns.org": 1,
"dyn-o-saur.com": 1,
"dynalias.com": 1,
"dynalias.net": 1,
"dynalias.org": 1,
"dynathome.net": 1,
"dyndns-at-home.com": 1,
"dyndns-at-work.com": 1,
"dyndns-blog.com": 1,
"dyndns-free.com": 1,
"dyndns-home.com": 1,
"dyndns-ip.com": 1,
"dyndns-mail.com": 1,
"dyndns-office.com": 1,
"dyndns-pics.com": 1,
"dyndns-remote.com": 1,
"dyndns-server.com": 1,
"dyndns-web.com": 1,
"dyndns-wiki.com": 1,
"dyndns-work.com": 1,
"dyndns.biz": 1,
"dyndns.info": 1,
"dyndns.org": 1,
"dyndns.tv": 1,
"dyndns.ws": 1,
"dyroy.no": 1,
"dyr\u00f8y.no": 1,
"d\u00f8nna.no": 1,
"e-burg.ru": 1,
"e.bg": 1,
"e.se": 1,
"e12.ve": 1,
"e164.arpa": 1,
"eastafrica.museum": 1,
"eastcoast.museum": 1,
"ebetsu.hokkaido.jp": 1,
"ebina.kanagawa.jp": 1,
"ebino.miyazaki.jp": 1,
"ebiz.tw": 1,
"echizen.fukui.jp": 1,
"ecn.br": 1,
"eco.br": 1,
"ed.ao": 1,
"ed.ci": 1,
"ed.cr": 1,
"ed.jp": 1,
"ed.pw": 1,
"edogawa.tokyo.jp": 1,
"edu.ac": 1,
"edu.af": 1,
"edu.al": 1,
"edu.an": 1,
"edu.au": 1,
"edu.az": 1,
"edu.ba": 1,
"edu.bb": 1,
"edu.bh": 1,
"edu.bi": 1,
"edu.bm": 1,
"edu.bo": 1,
"edu.br": 1,
"edu.bs": 1,
"edu.bt": 1,
"edu.bz": 1,
"edu.ci": 1,
"edu.cn": 1,
"edu.co": 1,
"edu.cu": 1,
"edu.dm": 1,
"edu.do": 1,
"edu.dz": 1,
"edu.ec": 1,
"edu.ee": 1,
"edu.eg": 1,
"edu.es": 1,
"edu.ge": 1,
"edu.gh": 1,
"edu.gi": 1,
"edu.gn": 1,
"edu.gp": 1,
"edu.gr": 1,
"edu.hk": 1,
"edu.hn": 1,
"edu.ht": 1,
"edu.in": 1,
"edu.iq": 1,
"edu.is": 1,
"edu.it": 1,
"edu.jo": 1,
"edu.kg": 1,
"edu.ki": 1,
"edu.km": 1,
"edu.kn": 1,
"edu.kp": 1,
"edu.ky": 1,
"edu.kz": 1,
"edu.la": 1,
"edu.lb": 1,
"edu.lc": 1,
"edu.lk": 1,
"edu.lr": 1,
"edu.lv": 1,
"edu.ly": 1,
"edu.me": 1,
"edu.mg": 1,
"edu.mk": 1,
"edu.ml": 1,
"edu.mn": 1,
"edu.mo": 1,
"edu.mv": 1,
"edu.mw": 1,
"edu.mx": 1,
"edu.my": 1,
"edu.ng": 1,
"edu.nr": 1,
"edu.pa": 1,
"edu.pe": 1,
"edu.pf": 1,
"edu.ph": 1,
"edu.pk": 1,
"edu.pl": 1,
"edu.pn": 1,
"edu.pr": 1,
"edu.ps": 1,
"edu.pt": 1,
"edu.qa": 1,
"edu.rs": 1,
"edu.ru": 1,
"edu.rw": 1,
"edu.sa": 1,
"edu.sb": 1,
"edu.sc": 1,
"edu.sd": 1,
"edu.sg": 1,
"edu.sl": 1,
"edu.sn": 1,
"edu.st": 1,
"edu.sy": 1,
"edu.tj": 1,
"edu.tm": 1,
"edu.to": 1,
"edu.tt": 1,
"edu.tw": 1,
"edu.ua": 1,
"edu.uy": 1,
"edu.vc": 1,
"edu.ve": 1,
"edu.vn": 1,
"edu.ws": 1,
"educ.ar": 0,
"education.museum": 1,
"educational.museum": 1,
"educator.aero": 1,
"edunet.tn": 1,
"egersund.no": 1,
"egyptian.museum": 1,
"ehime.jp": 1,
"eid.no": 1,
"eidfjord.no": 1,
"eidsberg.no": 1,
"eidskog.no": 1,
"eidsvoll.no": 1,
"eigersund.no": 1,
"eiheiji.fukui.jp": 1,
"eisenbahn.museum": 1,
"elblag.pl": 1,
"elburg.museum": 1,
"elk.pl": 1,
"elvendrell.museum": 1,
"elverum.no": 1,
"embaixada.st": 1,
"embetsu.hokkaido.jp": 1,
"embroidery.museum": 1,
"emergency.aero": 1,
"emp.br": 1,
"en.it": 1,
"ena.gifu.jp": 1,
"encyclopedic.museum": 1,
"endofinternet.net": 1,
"endofinternet.org": 1,
"endoftheinternet.org": 1,
"enebakk.no": 1,
"eng.br": 1,
"eng.pro": 1,
"engerdal.no": 1,
"engine.aero": 1,
"engineer.aero": 1,
"england.museum": 1,
"eniwa.hokkaido.jp": 1,
"enna.it": 1,
"ens.tn": 1,
"entertainment.aero": 1,
"entomology.museum": 1,
"environment.museum": 1,
"environmentalconservation.museum": 1,
"epilepsy.museum": 1,
"equipment.aero": 1,
"er": 2,
"erimo.hokkaido.jp": 1,
"erotica.hu": 1,
"erotika.hu": 1,
"es.kr": 1,
"esan.hokkaido.jp": 1,
"esashi.hokkaido.jp": 1,
"esp.br": 1,
"essex.museum": 1,
"est-a-la-maison.com": 1,
"est-a-la-masion.com": 1,
"est-le-patron.com": 1,
"est-mon-blogueur.com": 1,
"est.pr": 1,
"estate.museum": 1,
"et": 2,
"etajima.hiroshima.jp": 1,
"etc.br": 1,
"ethnology.museum": 1,
"eti.br": 1,
"etne.no": 1,
"etnedal.no": 1,
"eu.com": 1,
"eu.int": 1,
"eun.eg": 1,
"evenassi.no": 1,
"evenes.no": 1,
"even\u00e1\u0161\u0161i.no": 1,
"evje-og-hornnes.no": 1,
"exchange.aero": 1,
"exeter.museum": 1,
"exhibition.museum": 1,
"experts-comptables.fr": 1,
"express.aero": 1,
"f.bg": 1,
"f.se": 1,
"fam.pk": 1,
"family.museum": 1,
"far.br": 1,
"fareast.ru": 1,
"farm.museum": 1,
"farmequipment.museum": 1,
"farmers.museum": 1,
"farmstead.museum": 1,
"farsund.no": 1,
"fauske.no": 1,
"fc.it": 1,
"fe.it": 1,
"fed.us": 1,
"federation.aero": 1,
"fedje.no": 1,
"fermo.it": 1,
"ferrara.it": 1,
"fet.no": 1,
"fetsund.no": 1,
"fg.it": 1,
"fh.se": 1,
"fhs.no": 1,
"fhsk.se": 1,
"fhv.se": 1,
"fi.cr": 1,
"fi.it": 1,
"fie.ee": 1,
"field.museum": 1,
"figueres.museum": 1,
"filatelia.museum": 1,
"film.hu": 1,
"film.museum": 1,
"fin.ec": 1,
"fin.tn": 1,
"fineart.museum": 1,
"finearts.museum": 1,
"finland.museum": 1,
"finnoy.no": 1,
"finn\u00f8y.no": 1,
"firenze.it": 1,
"firm.co": 1,
"firm.ht": 1,
"firm.in": 1,
"firm.nf": 1,
"firm.ro": 1,
"fitjar.no": 1,
"fj": 2,
"fj.cn": 1,
"fjaler.no": 1,
"fjell.no": 1,
"fk": 2,
"fl.us": 1,
"fla.no": 1,
"flakstad.no": 1,
"flanders.museum": 1,
"flatanger.no": 1,
"flekkefjord.no": 1,
"flesberg.no": 1,
"flight.aero": 1,
"flog.br": 1,
"flora.no": 1,
"florence.it": 1,
"florida.museum": 1,
"floro.no": 1,
"flor\u00f8.no": 1,
"fl\u00e5.no": 1,
"fm.br": 1,
"fm.it": 1,
"fm.no": 1,
"fnd.br": 1,
"foggia.it": 1,
"folkebibl.no": 1,
"folldal.no": 1,
"for-better.biz": 1,
"for-more.biz": 1,
"for-our.info": 1,
"for-some.biz": 1,
"for-the.biz": 1,
"force.museum": 1,
"forde.no": 1,
"forgot.her.name": 1,
"forgot.his.name": 1,
"forli-cesena.it": 1,
"forlicesena.it": 1,
"forsand.no": 1,
"fortmissoula.museum": 1,
"fortworth.museum": 1,
"forum.hu": 1,
"fosnes.no": 1,
"fot.br": 1,
"foundation.museum": 1,
"fr.it": 1,
"frana.no": 1,
"francaise.museum": 1,
"frankfurt.museum": 1,
"franziskaner.museum": 1,
"fredrikstad.no": 1,
"freemasonry.museum": 1,
"frei.no": 1,
"freiburg.museum": 1,
"freight.aero": 1,
"fribourg.museum": 1,
"frog.museum": 1,
"frogn.no": 1,
"froland.no": 1,
"from-ak.com": 1,
"from-al.com": 1,
"from-ar.com": 1,
"from-az.net": 1,
"from-ca.com": 1,
"from-co.net": 1,
"from-ct.com": 1,
"from-dc.com": 1,
"from-de.com": 1,
"from-fl.com": 1,
"from-ga.com": 1,
"from-hi.com": 1,
"from-ia.com": 1,
"from-id.com": 1,
"from-il.com": 1,
"from-in.com": 1,
"from-ks.com": 1,
"from-ky.com": 1,
"from-la.net": 1,
"from-ma.com": 1,
"from-md.com": 1,
"from-me.org": 1,
"from-mi.com": 1,
"from-mn.com": 1,
"from-mo.com": 1,
"from-ms.com": 1,
"from-mt.com": 1,
"from-nc.com": 1,
"from-nd.com": 1,
"from-ne.com": 1,
"from-nh.com": 1,
"from-nj.com": 1,
"from-nm.com": 1,
"from-nv.com": 1,
"from-ny.net": 1,
"from-oh.com": 1,
"from-ok.com": 1,
"from-or.com": 1,
"from-pa.com": 1,
"from-pr.com": 1,
"from-ri.com": 1,
"from-sc.com": 1,
"from-sd.com": 1,
"from-tn.com": 1,
"from-tx.com": 1,
"from-ut.com": 1,
"from-va.com": 1,
"from-vt.com": 1,
"from-wa.com": 1,
"from-wi.com": 1,
"from-wv.com": 1,
"from-wy.com": 1,
"from.hr": 1,
"frosinone.it": 1,
"frosta.no": 1,
"froya.no": 1,
"fr\u00e6na.no": 1,
"fr\u00f8ya.no": 1,
"fst.br": 1,
"ftpaccess.cc": 1,
"fuchu.hiroshima.jp": 1,
"fuchu.tokyo.jp": 1,
"fuchu.toyama.jp": 1,
"fudai.iwate.jp": 1,
"fuefuki.yamanashi.jp": 1,
"fuel.aero": 1,
"fuettertdasnetz.de": 1,
"fuji.shizuoka.jp": 1,
"fujieda.shizuoka.jp": 1,
"fujiidera.osaka.jp": 1,
"fujikawa.shizuoka.jp": 1,
"fujikawa.yamanashi.jp": 1,
"fujikawaguchiko.yamanashi.jp": 1,
"fujimi.nagano.jp": 1,
"fujimi.saitama.jp": 1,
"fujimino.saitama.jp": 1,
"fujinomiya.shizuoka.jp": 1,
"fujioka.gunma.jp": 1,
"fujisato.akita.jp": 1,
"fujisawa.iwate.jp": 1,
"fujisawa.kanagawa.jp": 1,
"fujishiro.ibaraki.jp": 1,
"fujiyoshida.yamanashi.jp": 1,
"fukagawa.hokkaido.jp": 1,
"fukaya.saitama.jp": 1,
"fukuchi.fukuoka.jp": 1,
"fukuchiyama.kyoto.jp": 1,
"fukudomi.saga.jp": 1,
"fukui.fukui.jp": 1,
"fukui.jp": 1,
"fukumitsu.toyama.jp": 1,
"fukuoka.jp": 1,
"fukuroi.shizuoka.jp": 1,
"fukusaki.hyogo.jp": 1,
"fukushima.fukushima.jp": 1,
"fukushima.hokkaido.jp": 1,
"fukushima.jp": 1,
"fukuyama.hiroshima.jp": 1,
"funabashi.chiba.jp": 1,
"funagata.yamagata.jp": 1,
"funahashi.toyama.jp": 1,
"fundacio.museum": 1,
"fuoisku.no": 1,
"fuossko.no": 1,
"furano.hokkaido.jp": 1,
"furniture.museum": 1,
"furubira.hokkaido.jp": 1,
"furudono.fukushima.jp": 1,
"furukawa.miyagi.jp": 1,
"fusa.no": 1,
"fuso.aichi.jp": 1,
"fussa.tokyo.jp": 1,
"futaba.fukushima.jp": 1,
"futsu.nagasaki.jp": 1,
"futtsu.chiba.jp": 1,
"fylkesbibl.no": 1,
"fyresdal.no": 1,
"f\u00f8rde.no": 1,
"g.bg": 1,
"g.se": 1,
"g12.br": 1,
"ga.us": 1,
"gaivuotna.no": 1,
"gallery.museum": 1,
"galsa.no": 1,
"gamagori.aichi.jp": 1,
"game-host.org": 1,
"game-server.cc": 1,
"game.tw": 1,
"games.hu": 1,
"gamo.shiga.jp": 1,
"gamvik.no": 1,
"gangaviika.no": 1,
"gangwon.kr": 1,
"garden.museum": 1,
"gateway.museum": 1,
"gaular.no": 1,
"gausdal.no": 1,
"gb.com": 1,
"gb.net": 1,
"gc.ca": 1,
"gd.cn": 1,
"gda.pl": 1,
"gdansk.pl": 1,
"gdynia.pl": 1,
"ge.it": 1,
"geelvinck.museum": 1,
"geisei.kochi.jp": 1,
"gemological.museum": 1,
"gen.in": 1,
"genkai.saga.jp": 1,
"genoa.it": 1,
"genova.it": 1,
"geology.museum": 1,
"geometre-expert.fr": 1,
"georgia.museum": 1,
"getmyip.com": 1,
"gets-it.net": 1,
"ggf.br": 1,
"giehtavuoatna.no": 1,
"giessen.museum": 1,
"gifu.gifu.jp": 1,
"gifu.jp": 1,
"gildeskal.no": 1,
"gildesk\u00e5l.no": 1,
"ginan.gifu.jp": 1,
"ginowan.okinawa.jp": 1,
"ginoza.okinawa.jp": 1,
"giske.no": 1,
"gjemnes.no": 1,
"gjerdrum.no": 1,
"gjerstad.no": 1,
"gjesdal.no": 1,
"gjovik.no": 1,
"gj\u00f8vik.no": 1,
"glas.museum": 1,
"glass.museum": 1,
"gliding.aero": 1,
"gliwice.pl": 1,
"glogow.pl": 1,
"gloppen.no": 1,
"gmina.pl": 1,
"gniezno.pl": 1,
"go.ci": 1,
"go.cr": 1,
"go.dyndns.org": 1,
"go.id": 1,
"go.it": 1,
"go.jp": 1,
"go.kr": 1,
"go.pw": 1,
"go.th": 1,
"go.tj": 1,
"go.tz": 1,
"go.ug": 1,
"gob.bo": 1,
"gob.cl": 1,
"gob.do": 1,
"gob.ec": 1,
"gob.es": 1,
"gob.hn": 1,
"gob.mx": 1,
"gob.pa": 1,
"gob.pe": 1,
"gob.pk": 1,
"gobiernoelectronico.ar": 0,
"gobo.wakayama.jp": 1,
"godo.gifu.jp": 1,
"gojome.akita.jp": 1,
"gok.pk": 1,
"gokase.miyazaki.jp": 1,
"gol.no": 1,
"gon.pk": 1,
"gonohe.aomori.jp": 1,
"gop.pk": 1,
"gorge.museum": 1,
"gorizia.it": 1,
"gorlice.pl": 1,
"gos.pk": 1,
"gose.nara.jp": 1,
"gosen.niigata.jp": 1,
"goshiki.hyogo.jp": 1,
"gotdns.com": 1,
"gotdns.org": 1,
"gotemba.shizuoka.jp": 1,
"goto.nagasaki.jp": 1,
"gotsu.shimane.jp": 1,
"gouv.bj": 1,
"gouv.ci": 1,
"gouv.fr": 1,
"gouv.ht": 1,
"gouv.km": 1,
"gouv.ml": 1,
"gouv.rw": 1,
"gouv.sn": 1,
"gov.ac": 1,
"gov.ae": 1,
"gov.af": 1,
"gov.al": 1,
"gov.as": 1,
"gov.au": 1,
"gov.az": 1,
"gov.ba": 1,
"gov.bb": 1,
"gov.bf": 1,
"gov.bh": 1,
"gov.bm": 1,
"gov.bo": 1,
"gov.br": 1,
"gov.bs": 1,
"gov.bt": 1,
"gov.by": 1,
"gov.bz": 1,
"gov.cd": 1,
"gov.cl": 1,
"gov.cm": 1,
"gov.cn": 1,
"gov.co": 1,
"gov.cu": 1,
"gov.cx": 1,
"gov.dm": 1,
"gov.do": 1,
"gov.dz": 1,
"gov.ec": 1,
"gov.ee": 1,
"gov.eg": 1,
"gov.ge": 1,
"gov.gg": 1,
"gov.gh": 1,
"gov.gi": 1,
"gov.gn": 1,
"gov.gr": 1,
"gov.hk": 1,
"gov.ie": 1,
"gov.im": 1,
"gov.in": 1,
"gov.iq": 1,
"gov.ir": 1,
"gov.is": 1,
"gov.it": 1,
"gov.je": 1,
"gov.jo": 1,
"gov.kg": 1,
"gov.ki": 1,
"gov.km": 1,
"gov.kn": 1,
"gov.kp": 1,
"gov.ky": 1,
"gov.kz": 1,
"gov.la": 1,
"gov.lb": 1,
"gov.lc": 1,
"gov.lk": 1,
"gov.lr": 1,
"gov.lt": 1,
"gov.lv": 1,
"gov.ly": 1,
"gov.ma": 1,
"gov.me": 1,
"gov.mg": 1,
"gov.mk": 1,
"gov.ml": 1,
"gov.mn": 1,
"gov.mo": 1,
"gov.mr": 1,
"gov.mu": 1,
"gov.mv": 1,
"gov.mw": 1,
"gov.my": 1,
"gov.nc.tr": 1,
"gov.ng": 1,
"gov.nr": 1,
"gov.ph": 1,
"gov.pk": 1,
"gov.pl": 1,
"gov.pn": 1,
"gov.pr": 1,
"gov.ps": 1,
"gov.pt": 1,
"gov.qa": 1,
"gov.rs": 1,
"gov.ru": 1,
"gov.rw": 1,
"gov.sa": 1,
"gov.sb": 1,
"gov.sc": 1,
"gov.sd": 1,
"gov.sg": 1,
"gov.sh": 1,
"gov.sl": 1,
"gov.st": 1,
"gov.sx": 1,
"gov.sy": 1,
"gov.tj": 1,
"gov.tl": 1,
"gov.tm": 1,
"gov.tn": 1,
"gov.to": 1,
"gov.tt": 1,
"gov.tw": 1,
"gov.ua": 1,
"gov.vc": 1,
"gov.ve": 1,
"gov.vn": 1,
"gov.ws": 1,
"government.aero": 1,
"gr.com": 1,
"gr.it": 1,
"gr.jp": 1,
"grajewo.pl": 1,
"gran.no": 1,
"grandrapids.museum": 1,
"grane.no": 1,
"granvin.no": 1,
"gratangen.no": 1,
"graz.museum": 1,
"greta.fr": 1,
"grimstad.no": 1,
"groks-the.info": 1,
"groks-this.info": 1,
"grong.no": 1,
"grosseto.it": 1,
"groundhandling.aero": 1,
"group.aero": 1,
"grozny.ru": 1,
"grp.lk": 1,
"grue.no": 1,
"gs.aa.no": 1,
"gs.ah.no": 1,
"gs.bu.no": 1,
"gs.cn": 1,
"gs.fm.no": 1,
"gs.hl.no": 1,
"gs.hm.no": 1,
"gs.jan-mayen.no": 1,
"gs.mr.no": 1,
"gs.nl.no": 1,
"gs.nt.no": 1,
"gs.of.no": 1,
"gs.ol.no": 1,
"gs.oslo.no": 1,
"gs.rl.no": 1,
"gs.sf.no": 1,
"gs.st.no": 1,
"gs.svalbard.no": 1,
"gs.tm.no": 1,
"gs.tr.no": 1,
"gs.va.no": 1,
"gs.vf.no": 1,
"gsm.pl": 1,
"gt": 2,
"gu": 2,
"gu.us": 1,
"gub.uy": 1,
"guernsey.museum": 1,
"gujo.gifu.jp": 1,
"gulen.no": 1,
"gunma.jp": 1,
"guovdageaidnu.no": 1,
"gushikami.okinawa.jp": 1,
"gv.ao": 1,
"gv.at": 1,
"gwangju.kr": 1,
"gx.cn": 1,
"gyeongbuk.kr": 1,
"gyeonggi.kr": 1,
"gyeongnam.kr": 1,
"gyokuto.kumamoto.jp": 1,
"gz.cn": 1,
"g\u00e1ivuotna.no": 1,
"g\u00e1ls\u00e1.no": 1,
"g\u00e1\u014bgaviika.no": 1,
"h.bg": 1,
"h.se": 1,
"ha.cn": 1,
"ha.no": 1,
"habikino.osaka.jp": 1,
"habmer.no": 1,
"haboro.hokkaido.jp": 1,
"hachijo.tokyo.jp": 1,
"hachinohe.aomori.jp": 1,
"hachioji.tokyo.jp": 1,
"hachirogata.akita.jp": 1,
"hadano.kanagawa.jp": 1,
"hadsel.no": 1,
"haebaru.okinawa.jp": 1,
"haga.tochigi.jp": 1,
"hagebostad.no": 1,
"hagi.yamaguchi.jp": 1,
"haibara.shizuoka.jp": 1,
"hakata.fukuoka.jp": 1,
"hakodate.hokkaido.jp": 1,
"hakone.kanagawa.jp": 1,
"hakuba.nagano.jp": 1,
"hakui.ishikawa.jp": 1,
"hakusan.ishikawa.jp": 1,
"halden.no": 1,
"halloffame.museum": 1,
"halsa.no": 1,
"ham-radio-op.net": 1,
"hamada.shimane.jp": 1,
"hamamatsu.shizuoka.jp": 1,
"hamar.no": 1,
"hamaroy.no": 1,
"hamatama.saga.jp": 1,
"hamatonbetsu.hokkaido.jp": 1,
"hamburg.museum": 1,
"hammarfeasta.no": 1,
"hammerfest.no": 1,
"hamura.tokyo.jp": 1,
"hanamaki.iwate.jp": 1,
"hanamigawa.chiba.jp": 1,
"hanawa.fukushima.jp": 1,
"handa.aichi.jp": 1,
"handson.museum": 1,
"hanggliding.aero": 1,
"hannan.osaka.jp": 1,
"hanno.saitama.jp": 1,
"hanyu.saitama.jp": 1,
"hapmir.no": 1,
"happou.akita.jp": 1,
"hara.nagano.jp": 1,
"haram.no": 1,
"hareid.no": 1,
"harima.hyogo.jp": 1,
"harstad.no": 1,
"harvestcelebration.museum": 1,
"hasama.oita.jp": 1,
"hasami.nagasaki.jp": 1,
"hashikami.aomori.jp": 1,
"hashima.gifu.jp": 1,
"hashimoto.wakayama.jp": 1,
"hasuda.saitama.jp": 1,
"hasvik.no": 1,
"hatogaya.saitama.jp": 1,
"hatoyama.saitama.jp": 1,
"hatsukaichi.hiroshima.jp": 1,
"hattfjelldal.no": 1,
"haugesund.no": 1,
"hawaii.museum": 1,
"hayakawa.yamanashi.jp": 1,
"hayashima.okayama.jp": 1,
"hazu.aichi.jp": 1,
"hb.cn": 1,
"he.cn": 1,
"health.museum": 1,
"health.vn": 1,
"heguri.nara.jp": 1,
"heimatunduhren.museum": 1,
"hekinan.aichi.jp": 1,
"hellas.museum": 1,
"helsinki.museum": 1,
"hembygdsforbund.museum": 1,
"hemne.no": 1,
"hemnes.no": 1,
"hemsedal.no": 1,
"herad.no": 1,
"here-for-more.info": 1,
"heritage.museum": 1,
"heroy.more-og-romsdal.no": 1,
"heroy.nordland.no": 1,
"her\u00f8y.m\u00f8re-og-romsdal.no": 1,
"her\u00f8y.nordland.no": 1,
"hi.cn": 1,
"hi.us": 1,
"hichiso.gifu.jp": 1,
"hida.gifu.jp": 1,
"hidaka.hokkaido.jp": 1,
"hidaka.kochi.jp": 1,
"hidaka.saitama.jp": 1,
"hidaka.wakayama.jp": 1,
"higashi.fukuoka.jp": 1,
"higashi.fukushima.jp": 1,
"higashi.okinawa.jp": 1,
"higashiagatsuma.gunma.jp": 1,
"higashichichibu.saitama.jp": 1,
"higashihiroshima.hiroshima.jp": 1,
"higashiizu.shizuoka.jp": 1,
"higashiizumo.shimane.jp": 1,
"higashikagawa.kagawa.jp": 1,
"higashikagura.hokkaido.jp": 1,
"higashikawa.hokkaido.jp": 1,
"higashikurume.tokyo.jp": 1,
"higashimatsushima.miyagi.jp": 1,
"higashimatsuyama.saitama.jp": 1,
"higashimurayama.tokyo.jp": 1,
"higashinaruse.akita.jp": 1,
"higashine.yamagata.jp": 1,
"higashiomi.shiga.jp": 1,
"higashiosaka.osaka.jp": 1,
"higashishirakawa.gifu.jp": 1,
"higashisumiyoshi.osaka.jp": 1,
"higashitsuno.kochi.jp": 1,
"higashiura.aichi.jp": 1,
"higashiyama.kyoto.jp": 1,
"higashiyamato.tokyo.jp": 1,
"higashiyodogawa.osaka.jp": 1,
"higashiyoshino.nara.jp": 1,
"hiji.oita.jp": 1,
"hikari.yamaguchi.jp": 1,
"hikawa.shimane.jp": 1,
"hikimi.shimane.jp": 1,
"hikone.shiga.jp": 1,
"himeji.hyogo.jp": 1,
"himeshima.oita.jp": 1,
"himi.toyama.jp": 1,
"hino.tokyo.jp": 1,
"hino.tottori.jp": 1,
"hinode.tokyo.jp": 1,
"hinohara.tokyo.jp": 1,
"hioki.kagoshima.jp": 1,
"hirado.nagasaki.jp": 1,
"hiraizumi.iwate.jp": 1,
"hirakata.osaka.jp": 1,
"hiranai.aomori.jp": 1,
"hirara.okinawa.jp": 1,
"hirata.fukushima.jp": 1,
"hiratsuka.kanagawa.jp": 1,
"hiraya.nagano.jp": 1,
"hirogawa.wakayama.jp": 1,
"hirokawa.fukuoka.jp": 1,
"hirono.fukushima.jp": 1,
"hirono.iwate.jp": 1,
"hiroo.hokkaido.jp": 1,
"hirosaki.aomori.jp": 1,
"hiroshima.jp": 1,
"hisayama.fukuoka.jp": 1,
"histoire.museum": 1,
"historical.museum": 1,
"historicalsociety.museum": 1,
"historichouses.museum": 1,
"historisch.museum": 1,
"historisches.museum": 1,
"history.museum": 1,
"historyofscience.museum": 1,
"hita.oita.jp": 1,
"hitachi.ibaraki.jp": 1,
"hitachinaka.ibaraki.jp": 1,
"hitachiomiya.ibaraki.jp": 1,
"hitachiota.ibaraki.jp": 1,
"hitoyoshi.kumamoto.jp": 1,
"hitra.no": 1,
"hizen.saga.jp": 1,
"hjartdal.no": 1,
"hjelmeland.no": 1,
"hk.cn": 1,
"hl.cn": 1,
"hl.no": 1,
"hm.no": 1,
"hn.cn": 1,
"hobby-site.com": 1,
"hobby-site.org": 1,
"hobol.no": 1,
"hob\u00f8l.no": 1,
"hof.no": 1,
"hofu.yamaguchi.jp": 1,
"hokkaido.jp": 1,
"hokksund.no": 1,
"hokuryu.hokkaido.jp": 1,
"hokuto.hokkaido.jp": 1,
"hokuto.yamanashi.jp": 1,
"hol.no": 1,
"hole.no": 1,
"holmestrand.no": 1,
"holtalen.no": 1,
"holt\u00e5len.no": 1,
"home.dyndns.org": 1,
"homebuilt.aero": 1,
"homedns.org": 1,
"homeftp.net": 1,
"homeftp.org": 1,
"homeip.net": 1,
"homelinux.com": 1,
"homelinux.net": 1,
"homelinux.org": 1,
"homeunix.com": 1,
"homeunix.net": 1,
"homeunix.org": 1,
"honai.ehime.jp": 1,
"honbetsu.hokkaido.jp": 1,
"honefoss.no": 1,
"hongo.hiroshima.jp": 1,
"honjo.akita.jp": 1,
"honjo.saitama.jp": 1,
"honjyo.akita.jp": 1,
"hornindal.no": 1,
"horokanai.hokkaido.jp": 1,
"horology.museum": 1,
"horonobe.hokkaido.jp": 1,
"horten.no": 1,
"hotel.hu": 1,
"hotel.lk": 1,
"house.museum": 1,
"hoyanger.no": 1,
"hoylandet.no": 1,
"hs.kr": 1,
"hu.com": 1,
"hu.net": 1,
"huissier-justice.fr": 1,
"humanities.museum": 1,
"hurdal.no": 1,
"hurum.no": 1,
"hvaler.no": 1,
"hyllestad.no": 1,
"hyogo.jp": 1,
"hyuga.miyazaki.jp": 1,
"h\u00e1bmer.no": 1,
"h\u00e1mm\u00e1rfeasta.no": 1,
"h\u00e1pmir.no": 1,
"h\u00e5.no": 1,
"h\u00e6gebostad.no": 1,
"h\u00f8nefoss.no": 1,
"h\u00f8yanger.no": 1,
"h\u00f8ylandet.no": 1,
"i.bg": 1,
"i.ph": 1,
"i.se": 1,
"ia.us": 1,
"iamallama.com": 1,
"ibara.okayama.jp": 1,
"ibaraki.ibaraki.jp": 1,
"ibaraki.jp": 1,
"ibaraki.osaka.jp": 1,
"ibestad.no": 1,
"ibigawa.gifu.jp": 1,
"ichiba.tokushima.jp": 1,
"ichihara.chiba.jp": 1,
"ichikai.tochigi.jp": 1,
"ichikawa.chiba.jp": 1,
"ichikawa.hyogo.jp": 1,
"ichikawamisato.yamanashi.jp": 1,
"ichinohe.iwate.jp": 1,
"ichinomiya.aichi.jp": 1,
"ichinomiya.chiba.jp": 1,
"ichinoseki.iwate.jp": 1,
"id.au": 1,
"id.ir": 1,
"id.lv": 1,
"id.ly": 1,
"id.us": 1,
"ide.kyoto.jp": 1,
"idrett.no": 1,
"idv.hk": 1,
"idv.tw": 1,
"if.ua": 1,
"iglesias-carbonia.it": 1,
"iglesiascarbonia.it": 1,
"iheya.okinawa.jp": 1,
"iida.nagano.jp": 1,
"iide.yamagata.jp": 1,
"iijima.nagano.jp": 1,
"iitate.fukushima.jp": 1,
"iiyama.nagano.jp": 1,
"iizuka.fukuoka.jp": 1,
"iizuna.nagano.jp": 1,
"ikaruga.nara.jp": 1,
"ikata.ehime.jp": 1,
"ikawa.akita.jp": 1,
"ikeda.fukui.jp": 1,
"ikeda.gifu.jp": 1,
"ikeda.hokkaido.jp": 1,
"ikeda.nagano.jp": 1,
"ikeda.osaka.jp": 1,
"iki.fi": 1,
"iki.nagasaki.jp": 1,
"ikoma.nara.jp": 1,
"ikusaka.nagano.jp": 1,
"il": 2,
"il.us": 1,
"ilawa.pl": 1,
"illustration.museum": 1,
"im.it": 1,
"imabari.ehime.jp": 1,
"imageandsound.museum": 1,
"imakane.hokkaido.jp": 1,
"imari.saga.jp": 1,
"imb.br": 1,
"imizu.toyama.jp": 1,
"imperia.it": 1,
"in-addr.arpa": 1,
"in-the-band.net": 1,
"in.na": 1,
"in.rs": 1,
"in.th": 1,
"in.ua": 1,
"in.us": 1,
"ina.ibaraki.jp": 1,
"ina.nagano.jp": 1,
"ina.saitama.jp": 1,
"inabe.mie.jp": 1,
"inagawa.hyogo.jp": 1,
"inagi.tokyo.jp": 1,
"inami.toyama.jp": 1,
"inami.wakayama.jp": 1,
"inashiki.ibaraki.jp": 1,
"inatsuki.fukuoka.jp": 1,
"inawashiro.fukushima.jp": 1,
"inazawa.aichi.jp": 1,
"incheon.kr": 1,
"ind.br": 1,
"ind.in": 1,
"ind.tn": 1,
"inderoy.no": 1,
"inder\u00f8y.no": 1,
"indian.museum": 1,
"indiana.museum": 1,
"indianapolis.museum": 1,
"indianmarket.museum": 1,
"ine.kyoto.jp": 1,
"inf.br": 1,
"inf.cu": 1,
"inf.mk": 1,
"info.at": 1,
"info.au": 1,
"info.az": 1,
"info.bb": 1,
"info.co": 1,
"info.ec": 1,
"info.ht": 1,
"info.hu": 1,
"info.ki": 1,
"info.la": 1,
"info.mv": 1,
"info.na": 1,
"info.nf": 1,
"info.nr": 1,
"info.pk": 1,
"info.pl": 1,
"info.pr": 1,
"info.ro": 1,
"info.sd": 1,
"info.tn": 1,
"info.tt": 1,
"info.ve": 1,
"info.vn": 1,
"ing.pa": 1,
"ingatlan.hu": 1,
"ino.kochi.jp": 1,
"insurance.aero": 1,
"int.az": 1,
"int.bo": 1,
"int.ci": 1,
"int.co": 1,
"int.is": 1,
"int.la": 1,
"int.lk": 1,
"int.mv": 1,
"int.mw": 1,
"int.pt": 1,
"int.ru": 1,
"int.rw": 1,
"int.tj": 1,
"int.tt": 1,
"int.vn": 1,
"intelligence.museum": 1,
"interactive.museum": 1,
"intl.tn": 1,
"inuyama.aichi.jp": 1,
"inzai.chiba.jp": 1,
"ip6.arpa": 1,
"iraq.museum": 1,
"irc.pl": 1,
"iris.arpa": 1,
"irkutsk.ru": 1,
"iron.museum": 1,
"iruma.saitama.jp": 1,
"is-a-anarchist.com": 1,
"is-a-blogger.com": 1,
"is-a-bookkeeper.com": 1,
"is-a-bruinsfan.org": 1,
"is-a-bulls-fan.com": 1,
"is-a-candidate.org": 1,
"is-a-caterer.com": 1,
"is-a-celticsfan.org": 1,
"is-a-chef.com": 1,
"is-a-chef.net": 1,
"is-a-chef.org": 1,
"is-a-conservative.com": 1,
"is-a-cpa.com": 1,
"is-a-cubicle-slave.com": 1,
"is-a-democrat.com": 1,
"is-a-designer.com": 1,
"is-a-doctor.com": 1,
"is-a-financialadvisor.com": 1,
"is-a-geek.com": 1,
"is-a-geek.net": 1,
"is-a-geek.org": 1,
"is-a-green.com": 1,
"is-a-guru.com": 1,
"is-a-hard-worker.com": 1,
"is-a-hunter.com": 1,
"is-a-knight.org": 1,
"is-a-landscaper.com": 1,
"is-a-lawyer.com": 1,
"is-a-liberal.com": 1,
"is-a-libertarian.com": 1,
"is-a-linux-user.org": 1,
"is-a-llama.com": 1,
"is-a-musician.com": 1,
"is-a-nascarfan.com": 1,
"is-a-nurse.com": 1,
"is-a-painter.com": 1,
"is-a-patsfan.org": 1,
"is-a-personaltrainer.com": 1,
"is-a-photographer.com": 1,
"is-a-player.com": 1,
"is-a-republican.com": 1,
"is-a-rockstar.com": 1,
"is-a-socialist.com": 1,
"is-a-soxfan.org": 1,
"is-a-student.com": 1,
"is-a-teacher.com": 1,
"is-a-techie.com": 1,
"is-a-therapist.com": 1,
"is-an-accountant.com": 1,
"is-an-actor.com": 1,
"is-an-actress.com": 1,
"is-an-anarchist.com": 1,
"is-an-artist.com": 1,
"is-an-engineer.com": 1,
"is-an-entertainer.com": 1,
"is-by.us": 1,
"is-certified.com": 1,
"is-found.org": 1,
"is-gone.com": 1,
"is-into-anime.com": 1,
"is-into-cars.com": 1,
"is-into-cartoons.com": 1,
"is-into-games.com": 1,
"is-leet.com": 1,
"is-lost.org": 1,
"is-not-certified.com": 1,
"is-saved.org": 1,
"is-slick.com": 1,
"is-uberleet.com": 1,
"is-very-bad.org": 1,
"is-very-evil.org": 1,
"is-very-good.org": 1,
"is-very-nice.org": 1,
"is-very-sweet.org": 1,
"is-with-theband.com": 1,
"is.it": 1,
"isa-geek.com": 1,
"isa-geek.net": 1,
"isa-geek.org": 1,
"isa-hockeynut.com": 1,
"isa.kagoshima.jp": 1,
"isa.us": 1,
"isahaya.nagasaki.jp": 1,
"ise.mie.jp": 1,
"isehara.kanagawa.jp": 1,
"isen.kagoshima.jp": 1,
"isernia.it": 1,
"isesaki.gunma.jp": 1,
"ishigaki.okinawa.jp": 1,
"ishikari.hokkaido.jp": 1,
"ishikawa.fukushima.jp": 1,
"ishikawa.jp": 1,
"ishikawa.okinawa.jp": 1,
"ishinomaki.miyagi.jp": 1,
"isla.pr": 1,
"isleofman.museum": 1,
"isshiki.aichi.jp": 1,
"issmarterthanyou.com": 1,
"isteingeek.de": 1,
"istmein.de": 1,
"isumi.chiba.jp": 1,
"it.ao": 1,
"itabashi.tokyo.jp": 1,
"itako.ibaraki.jp": 1,
"itakura.gunma.jp": 1,
"itami.hyogo.jp": 1,
"itano.tokushima.jp": 1,
"itayanagi.aomori.jp": 1,
"ito.shizuoka.jp": 1,
"itoigawa.niigata.jp": 1,
"itoman.okinawa.jp": 1,
"its.me": 1,
"ivano-frankivsk.ua": 1,
"ivanovo.ru": 1,
"iveland.no": 1,
"ivgu.no": 1,
"iwade.wakayama.jp": 1,
"iwafune.tochigi.jp": 1,
"iwaizumi.iwate.jp": 1,
"iwaki.fukushima.jp": 1,
"iwakuni.yamaguchi.jp": 1,
"iwakura.aichi.jp": 1,
"iwama.ibaraki.jp": 1,
"iwamizawa.hokkaido.jp": 1,
"iwanai.hokkaido.jp": 1,
"iwanuma.miyagi.jp": 1,
"iwata.shizuoka.jp": 1,
"iwate.iwate.jp": 1,
"iwate.jp": 1,
"iwatsuki.saitama.jp": 1,
"iyo.ehime.jp": 1,
"iz.hr": 1,
"izena.okinawa.jp": 1,
"izhevsk.ru": 1,
"izu.shizuoka.jp": 1,
"izumi.kagoshima.jp": 1,
"izumi.osaka.jp": 1,
"izumiotsu.osaka.jp": 1,
"izumisano.osaka.jp": 1,
"izumizaki.fukushima.jp": 1,
"izumo.shimane.jp": 1,
"izumozaki.niigata.jp": 1,
"izunokuni.shizuoka.jp": 1,
"j.bg": 1,
"jamal.ru": 1,
"jamison.museum": 1,
"jan-mayen.no": 1,
"jar.ru": 1,
"jaworzno.pl": 1,
"jefferson.museum": 1,
"jeju.kr": 1,
"jelenia-gora.pl": 1,
"jeonbuk.kr": 1,
"jeonnam.kr": 1,
"jerusalem.museum": 1,
"jessheim.no": 1,
"jet.uk": 0,
"jevnaker.no": 1,
"jewelry.museum": 1,
"jewish.museum": 1,
"jewishart.museum": 1,
"jfk.museum": 1,
"jgora.pl": 1,
"jinsekikogen.hiroshima.jp": 1,
"jl.cn": 1,
"jm": 2,
"joboji.iwate.jp": 1,
"jobs.tt": 1,
"joetsu.niigata.jp": 1,
"jogasz.hu": 1,
"johana.toyama.jp": 1,
"jolster.no": 1,
"jondal.no": 1,
"jor.br": 1,
"jorpeland.no": 1,
"joshkar-ola.ru": 1,
"joso.ibaraki.jp": 1,
"journal.aero": 1,
"journalism.museum": 1,
"journalist.aero": 1,
"joyo.kyoto.jp": 1,
"jp.net": 1,
"jpn.com": 1,
"js.cn": 1,
"judaica.museum": 1,
"judygarland.museum": 1,
"juedisches.museum": 1,
"juif.museum": 1,
"jur.pro": 1,
"jus.br": 1,
"jx.cn": 1,
"j\u00f8lster.no": 1,
"j\u00f8rpeland.no": 1,
"k-uralsk.ru": 1,
"k.bg": 1,
"k.se": 1,
"k12.ak.us": 1,
"k12.al.us": 1,
"k12.ar.us": 1,
"k12.as.us": 1,
"k12.az.us": 1,
"k12.ca.us": 1,
"k12.co.us": 1,
"k12.ct.us": 1,
"k12.dc.us": 1,
"k12.de.us": 1,
"k12.ec": 1,
"k12.fl.us": 1,
"k12.ga.us": 1,
"k12.gu.us": 1,
"k12.ia.us": 1,
"k12.id.us": 1,
"k12.il.us": 1,
"k12.in.us": 1,
"k12.ks.us": 1,
"k12.ky.us": 1,
"k12.la.us": 1,
"k12.ma.us": 1,
"k12.md.us": 1,
"k12.me.us": 1,
"k12.mi.us": 1,
"k12.mn.us": 1,
"k12.mo.us": 1,
"k12.ms.us": 1,
"k12.mt.us": 1,
"k12.nc.us": 1,
"k12.nd.us": 1,
"k12.ne.us": 1,
"k12.nh.us": 1,
"k12.nj.us": 1,
"k12.nm.us": 1,
"k12.nv.us": 1,
"k12.ny.us": 1,
"k12.oh.us": 1,
"k12.ok.us": 1,
"k12.or.us": 1,
"k12.pa.us": 1,
"k12.pr.us": 1,
"k12.ri.us": 1,
"k12.sc.us": 1,
"k12.sd.us": 1,
"k12.tn.us": 1,
"k12.tx.us": 1,
"k12.ut.us": 1,
"k12.va.us": 1,
"k12.vi": 1,
"k12.vi.us": 1,
"k12.vt.us": 1,
"k12.wa.us": 1,
"k12.wi.us": 1,
"k12.wv.us": 1,
"k12.wy.us": 1,
"kadena.okinawa.jp": 1,
"kadogawa.miyazaki.jp": 1,
"kadoma.osaka.jp": 1,
"kafjord.no": 1,
"kaga.ishikawa.jp": 1,
"kagami.kochi.jp": 1,
"kagamiishi.fukushima.jp": 1,
"kagamino.okayama.jp": 1,
"kagawa.jp": 1,
"kagoshima.jp": 1,
"kagoshima.kagoshima.jp": 1,
"kaho.fukuoka.jp": 1,
"kahoku.ishikawa.jp": 1,
"kahoku.yamagata.jp": 1,
"kai.yamanashi.jp": 1,
"kainan.tokushima.jp": 1,
"kainan.wakayama.jp": 1,
"kaisei.kanagawa.jp": 1,
"kaita.hiroshima.jp": 1,
"kaizuka.osaka.jp": 1,
"kakamigahara.gifu.jp": 1,
"kakegawa.shizuoka.jp": 1,
"kakinoki.shimane.jp": 1,
"kakogawa.hyogo.jp": 1,
"kakuda.miyagi.jp": 1,
"kalisz.pl": 1,
"kalmykia.ru": 1,
"kaluga.ru": 1,
"kamagaya.chiba.jp": 1,
"kamaishi.iwate.jp": 1,
"kamakura.kanagawa.jp": 1,
"kamchatka.ru": 1,
"kameoka.kyoto.jp": 1,
"kameyama.mie.jp": 1,
"kami.kochi.jp": 1,
"kami.miyagi.jp": 1,
"kamiamakusa.kumamoto.jp": 1,
"kamifurano.hokkaido.jp": 1,
"kamigori.hyogo.jp": 1,
"kamiichi.toyama.jp": 1,
"kamiizumi.saitama.jp": 1,
"kamijima.ehime.jp": 1,
"kamikawa.hokkaido.jp": 1,
"kamikawa.hyogo.jp": 1,
"kamikawa.saitama.jp": 1,
"kamikitayama.nara.jp": 1,
"kamikoani.akita.jp": 1,
"kamimine.saga.jp": 1,
"kaminokawa.tochigi.jp": 1,
"kaminoyama.yamagata.jp": 1,
"kamioka.akita.jp": 1,
"kamisato.saitama.jp": 1,
"kamishihoro.hokkaido.jp": 1,
"kamisu.ibaraki.jp": 1,
"kamisunagawa.hokkaido.jp": 1,
"kamitonda.wakayama.jp": 1,
"kamitsue.oita.jp": 1,
"kamo.kyoto.jp": 1,
"kamo.niigata.jp": 1,
"kamoenai.hokkaido.jp": 1,
"kamogawa.chiba.jp": 1,
"kanagawa.jp": 1,
"kanan.osaka.jp": 1,
"kanazawa.ishikawa.jp": 1,
"kanegasaki.iwate.jp": 1,
"kaneyama.fukushima.jp": 1,
"kaneyama.yamagata.jp": 1,
"kani.gifu.jp": 1,
"kanie.aichi.jp": 1,
"kanmaki.nara.jp": 1,
"kanna.gunma.jp": 1,
"kannami.shizuoka.jp": 1,
"kanonji.kagawa.jp": 1,
"kanoya.kagoshima.jp": 1,
"kanra.gunma.jp": 1,
"kanuma.tochigi.jp": 1,
"kanzaki.saga.jp": 1,
"karasjohka.no": 1,
"karasjok.no": 1,
"karasuyama.tochigi.jp": 1,
"karate.museum": 1,
"karatsu.saga.jp": 1,
"karelia.ru": 1,
"karikatur.museum": 1,
"kariwa.niigata.jp": 1,
"kariya.aichi.jp": 1,
"karlsoy.no": 1,
"karmoy.no": 1,
"karm\u00f8y.no": 1,
"karpacz.pl": 1,
"kartuzy.pl": 1,
"karuizawa.nagano.jp": 1,
"karumai.iwate.jp": 1,
"kasahara.gifu.jp": 1,
"kasai.hyogo.jp": 1,
"kasama.ibaraki.jp": 1,
"kasamatsu.gifu.jp": 1,
"kasaoka.okayama.jp": 1,
"kashiba.nara.jp": 1,
"kashihara.nara.jp": 1,
"kashima.ibaraki.jp": 1,
"kashima.kumamoto.jp": 1,
"kashima.saga.jp": 1,
"kashiwa.chiba.jp": 1,
"kashiwara.osaka.jp": 1,
"kashiwazaki.niigata.jp": 1,
"kasuga.fukuoka.jp": 1,
"kasuga.hyogo.jp": 1,
"kasugai.aichi.jp": 1,
"kasukabe.saitama.jp": 1,
"kasumigaura.ibaraki.jp": 1,
"kasuya.fukuoka.jp": 1,
"kaszuby.pl": 1,
"katagami.akita.jp": 1,
"katano.osaka.jp": 1,
"katashina.gunma.jp": 1,
"katori.chiba.jp": 1,
"katowice.pl": 1,
"katsuragi.nara.jp": 1,
"katsuragi.wakayama.jp": 1,
"katsushika.tokyo.jp": 1,
"katsuura.chiba.jp": 1,
"katsuyama.fukui.jp": 1,
"kautokeino.no": 1,
"kawaba.gunma.jp": 1,
"kawachinagano.osaka.jp": 1,
"kawagoe.mie.jp": 1,
"kawagoe.saitama.jp": 1,
"kawaguchi.saitama.jp": 1,
"kawahara.tottori.jp": 1,
"kawai.iwate.jp": 1,
"kawai.nara.jp": 1,
"kawajima.saitama.jp": 1,
"kawakami.nagano.jp": 1,
"kawakami.nara.jp": 1,
"kawakita.ishikawa.jp": 1,
"kawamata.fukushima.jp": 1,
"kawaminami.miyazaki.jp": 1,
"kawanabe.kagoshima.jp": 1,
"kawanehon.shizuoka.jp": 1,
"kawanishi.hyogo.jp": 1,
"kawanishi.nara.jp": 1,
"kawanishi.yamagata.jp": 1,
"kawara.fukuoka.jp": 1,
"kawasaki.jp": 2,
"kawasaki.miyagi.jp": 1,
"kawatana.nagasaki.jp": 1,
"kawaue.gifu.jp": 1,
"kawazu.shizuoka.jp": 1,
"kayabe.hokkaido.jp": 1,
"kazan.ru": 1,
"kazimierz-dolny.pl": 1,
"kazo.saitama.jp": 1,
"kazuno.akita.jp": 1,
"kchr.ru": 1,
"ke": 2,
"keisen.fukuoka.jp": 1,
"kembuchi.hokkaido.jp": 1,
"kemerovo.ru": 1,
"kepno.pl": 1,
"kesennuma.miyagi.jp": 1,
"ketrzyn.pl": 1,
"kg.kr": 1,
"kh": 2,
"kh.ua": 1,
"khabarovsk.ru": 1,
"khakassia.ru": 1,
"kharkiv.ua": 1,
"kharkov.ua": 1,
"kherson.ua": 1,
"khmelnitskiy.ua": 1,
"khmelnytskyi.ua": 1,
"khv.ru": 1,
"kibichuo.okayama.jp": 1,
"kicks-ass.net": 1,
"kicks-ass.org": 1,
"kids.museum": 1,
"kids.us": 1,
"kiev.ua": 1,
"kiho.mie.jp": 1,
"kihoku.ehime.jp": 1,
"kijo.miyazaki.jp": 1,
"kikonai.hokkaido.jp": 1,
"kikuchi.kumamoto.jp": 1,
"kikugawa.shizuoka.jp": 1,
"kimino.wakayama.jp": 1,
"kimitsu.chiba.jp": 1,
"kimobetsu.hokkaido.jp": 1,
"kin.okinawa.jp": 1,
"kinko.kagoshima.jp": 1,
"kinokawa.wakayama.jp": 1,
"kira.aichi.jp": 1,
"kirkenes.no": 1,
"kirov.ru": 1,
"kirovograd.ua": 1,
"kiryu.gunma.jp": 1,
"kisarazu.chiba.jp": 1,
"kishiwada.osaka.jp": 1,
"kiso.nagano.jp": 1,
"kisofukushima.nagano.jp": 1,
"kisosaki.mie.jp": 1,
"kita.kyoto.jp": 1,
"kita.osaka.jp": 1,
"kita.tokyo.jp": 1,
"kitaaiki.nagano.jp": 1,
"kitaakita.akita.jp": 1,
"kitadaito.okinawa.jp": 1,
"kitagata.gifu.jp": 1,
"kitagata.saga.jp": 1,
"kitagawa.kochi.jp": 1,
"kitagawa.miyazaki.jp": 1,
"kitahata.saga.jp": 1,
"kitahiroshima.hokkaido.jp": 1,
"kitakami.iwate.jp": 1,
"kitakata.fukushima.jp": 1,
"kitakata.miyazaki.jp": 1,
"kitakyushu.jp": 2,
"kitami.hokkaido.jp": 1,
"kitamoto.saitama.jp": 1,
"kitanakagusuku.okinawa.jp": 1,
"kitashiobara.fukushima.jp": 1,
"kitaura.miyazaki.jp": 1,
"kitayama.wakayama.jp": 1,
"kiwa.mie.jp": 1,
"kiyama.saga.jp": 1,
"kiyokawa.kanagawa.jp": 1,
"kiyosato.hokkaido.jp": 1,
"kiyose.tokyo.jp": 1,
"kiyosu.aichi.jp": 1,
"kizu.kyoto.jp": 1,
"klabu.no": 1,
"klepp.no": 1,
"klodzko.pl": 1,
"kl\u00e6bu.no": 1,
"km.ua": 1,
"kms.ru": 1,
"knowsitall.info": 1,
"kobayashi.miyazaki.jp": 1,
"kobe.jp": 2,
"kobierzyce.pl": 1,
"kochi.jp": 1,
"kochi.kochi.jp": 1,
"kodaira.tokyo.jp": 1,
"koebenhavn.museum": 1,
"koeln.museum": 1,
"koenig.ru": 1,
"kofu.yamanashi.jp": 1,
"koga.fukuoka.jp": 1,
"koga.ibaraki.jp": 1,
"koganei.tokyo.jp": 1,
"koge.tottori.jp": 1,
"koka.shiga.jp": 1,
"kokonoe.oita.jp": 1,
"kokubunji.tokyo.jp": 1,
"kolobrzeg.pl": 1,
"komae.tokyo.jp": 1,
"komagane.nagano.jp": 1,
"komaki.aichi.jp": 1,
"komatsu.ishikawa.jp": 1,
"komatsushima.tokushima.jp": 1,
"komforb.se": 1,
"komi.ru": 1,
"kommunalforbund.se": 1,
"kommune.no": 1,
"komono.mie.jp": 1,
"komoro.nagano.jp": 1,
"komvux.se": 1,
"konan.aichi.jp": 1,
"konan.shiga.jp": 1,
"kongsberg.no": 1,
"kongsvinger.no": 1,
"konin.pl": 1,
"konskowola.pl": 1,
"konyvelo.hu": 1,
"koori.fukushima.jp": 1,
"kopervik.no": 1,
"koriyama.fukushima.jp": 1,
"koryo.nara.jp": 1,
"kosa.kumamoto.jp": 1,
"kosai.shizuoka.jp": 1,
"kosaka.akita.jp": 1,
"kosei.shiga.jp": 1,
"koshigaya.saitama.jp": 1,
"koshimizu.hokkaido.jp": 1,
"koshu.yamanashi.jp": 1,
"kostroma.ru": 1,
"kosuge.yamanashi.jp": 1,
"kota.aichi.jp": 1,
"koto.shiga.jp": 1,
"koto.tokyo.jp": 1,
"kotohira.kagawa.jp": 1,
"kotoura.tottori.jp": 1,
"kouhoku.saga.jp": 1,
"kounosu.saitama.jp": 1,
"kouyama.kagoshima.jp": 1,
"kouzushima.tokyo.jp": 1,
"koya.wakayama.jp": 1,
"koza.wakayama.jp": 1,
"kozagawa.wakayama.jp": 1,
"kozaki.chiba.jp": 1,
"kr.com": 1,
"kr.it": 1,
"kr.ua": 1,
"kraanghke.no": 1,
"kragero.no": 1,
"krager\u00f8.no": 1,
"krakow.pl": 1,
"krasnoyarsk.ru": 1,
"kristiansand.no": 1,
"kristiansund.no": 1,
"krodsherad.no": 1,
"krokstadelva.no": 1,
"krym.ua": 1,
"kr\u00e5anghke.no": 1,
"kr\u00f8dsherad.no": 1,
"ks.ua": 1,
"ks.us": 1,
"kuban.ru": 1,
"kuchinotsu.nagasaki.jp": 1,
"kudamatsu.yamaguchi.jp": 1,
"kudoyama.wakayama.jp": 1,
"kui.hiroshima.jp": 1,
"kuji.iwate.jp": 1,
"kuju.oita.jp": 1,
"kujukuri.chiba.jp": 1,
"kuki.saitama.jp": 1,
"kumagaya.saitama.jp": 1,
"kumakogen.ehime.jp": 1,
"kumamoto.jp": 1,
"kumamoto.kumamoto.jp": 1,
"kumano.hiroshima.jp": 1,
"kumano.mie.jp": 1,
"kumatori.osaka.jp": 1,
"kumejima.okinawa.jp": 1,
"kumenan.okayama.jp": 1,
"kumiyama.kyoto.jp": 1,
"kunigami.okinawa.jp": 1,
"kunimi.fukushima.jp": 1,
"kunisaki.oita.jp": 1,
"kunitachi.tokyo.jp": 1,
"kunitomi.miyazaki.jp": 1,
"kunneppu.hokkaido.jp": 1,
"kunohe.iwate.jp": 1,
"kunst.museum": 1,
"kunstsammlung.museum": 1,
"kunstunddesign.museum": 1,
"kurashiki.okayama.jp": 1,
"kurate.fukuoka.jp": 1,
"kure.hiroshima.jp": 1,
"kurgan.ru": 1,
"kuriyama.hokkaido.jp": 1,
"kurobe.toyama.jp": 1,
"kurogi.fukuoka.jp": 1,
"kuroishi.aomori.jp": 1,
"kuroiso.tochigi.jp": 1,
"kuromatsunai.hokkaido.jp": 1,
"kurotaki.nara.jp": 1,
"kursk.ru": 1,
"kurume.fukuoka.jp": 1,
"kusatsu.gunma.jp": 1,
"kusatsu.shiga.jp": 1,
"kushima.miyazaki.jp": 1,
"kushimoto.wakayama.jp": 1,
"kushiro.hokkaido.jp": 1,
"kustanai.ru": 1,
"kusu.oita.jp": 1,
"kutchan.hokkaido.jp": 1,
"kutno.pl": 1,
"kuwana.mie.jp": 1,
"kuzbass.ru": 1,
"kuzumaki.iwate.jp": 1,
"kv.ua": 1,
"kvafjord.no": 1,
"kvalsund.no": 1,
"kvam.no": 1,
"kvanangen.no": 1,
"kvinesdal.no": 1,
"kvinnherad.no": 1,
"kviteseid.no": 1,
"kvitsoy.no": 1,
"kvits\u00f8y.no": 1,
"kv\u00e6fjord.no": 1,
"kv\u00e6nangen.no": 1,
"kw": 2,
"ky.us": 1,
"kyiv.ua": 1,
"kyonan.chiba.jp": 1,
"kyotamba.kyoto.jp": 1,
"kyotanabe.kyoto.jp": 1,
"kyotango.kyoto.jp": 1,
"kyoto.jp": 1,
"kyowa.akita.jp": 1,
"kyowa.hokkaido.jp": 1,
"kyuragi.saga.jp": 1,
"k\u00e1r\u00e1\u0161johka.no": 1,
"k\u00e5fjord.no": 1,
"l.bg": 1,
"l.se": 1,
"la-spezia.it": 1,
"la.us": 1,
"laakesvuemie.no": 1,
"labor.museum": 1,
"labour.museum": 1,
"lahppi.no": 1,
"lajolla.museum": 1,
"lakas.hu": 1,
"lanbib.se": 1,
"lancashire.museum": 1,
"land-4-sale.us": 1,
"landes.museum": 1,
"langevag.no": 1,
"langev\u00e5g.no": 1,
"lans.museum": 1,
"lapy.pl": 1,
"laquila.it": 1,
"lardal.no": 1,
"larsson.museum": 1,
"larvik.no": 1,
"laspezia.it": 1,
"latina.it": 1,
"lavagis.no": 1,
"lavangen.no": 1,
"law.pro": 1,
"lc.it": 1,
"le.it": 1,
"leangaviika.no": 1,
"leasing.aero": 1,
"lea\u014bgaviika.no": 1,
"lebesby.no": 1,
"lebork.pl": 1,
"lebtimnetz.de": 1,
"lecce.it": 1,
"lecco.it": 1,
"leg.br": 1,
"legnica.pl": 1,
"leikanger.no": 1,
"leirfjord.no": 1,
"leirvik.no": 1,
"leitungsen.de": 1,
"leka.no": 1,
"leksvik.no": 1,
"lel.br": 1,
"lenvik.no": 1,
"lerdal.no": 1,
"lesja.no": 1,
"levanger.no": 1,
"lewismiller.museum": 1,
"lezajsk.pl": 1,
"lg.jp": 1,
"lg.ua": 1,
"li.it": 1,
"lib.ak.us": 1,
"lib.al.us": 1,
"lib.ar.us": 1,
"lib.as.us": 1,
"lib.az.us": 1,
"lib.ca.us": 1,
"lib.co.us": 1,
"lib.ct.us": 1,
"lib.dc.us": 1,
"lib.de.us": 1,
"lib.ee": 1,
"lib.fl.us": 1,
"lib.ga.us": 1,
"lib.gu.us": 1,
"lib.hi.us": 1,
"lib.ia.us": 1,
"lib.id.us": 1,
"lib.il.us": 1,
"lib.in.us": 1,
"lib.ks.us": 1,
"lib.ky.us": 1,
"lib.la.us": 1,
"lib.ma.us": 1,
"lib.md.us": 1,
"lib.me.us": 1,
"lib.mi.us": 1,
"lib.mn.us": 1,
"lib.mo.us": 1,
"lib.ms.us": 1,
"lib.mt.us": 1,
"lib.nc.us": 1,
"lib.nd.us": 1,
"lib.ne.us": 1,
"lib.nh.us": 1,
"lib.nj.us": 1,
"lib.nm.us": 1,
"lib.nv.us": 1,
"lib.ny.us": 1,
"lib.oh.us": 1,
"lib.ok.us": 1,
"lib.or.us": 1,
"lib.pa.us": 1,
"lib.pr.us": 1,
"lib.ri.us": 1,
"lib.sc.us": 1,
"lib.sd.us": 1,
"lib.tn.us": 1,
"lib.tx.us": 1,
"lib.ut.us": 1,
"lib.va.us": 1,
"lib.vi.us": 1,
"lib.vt.us": 1,
"lib.wa.us": 1,
"lib.wi.us": 1,
"lib.wv.us": 1,
"lib.wy.us": 1,
"lier.no": 1,
"lierne.no": 1,
"likes-pie.com": 1,
"likescandy.com": 1,
"lillehammer.no": 1,
"lillesand.no": 1,
"limanowa.pl": 1,
"lincoln.museum": 1,
"lindas.no": 1,
"lindesnes.no": 1,
"lind\u00e5s.no": 1,
"linz.museum": 1,
"lipetsk.ru": 1,
"living.museum": 1,
"livinghistory.museum": 1,
"livorno.it": 1,
"ln.cn": 1,
"lo.it": 1,
"loabat.no": 1,
"loab\u00e1t.no": 1,
"localhistory.museum": 1,
"lodi.it": 1,
"lodingen.no": 1,
"logistics.aero": 1,
"lom.no": 1,
"lomza.pl": 1,
"london.museum": 1,
"loppa.no": 1,
"lorenskog.no": 1,
"losangeles.museum": 1,
"loten.no": 1,
"louvre.museum": 1,
"lowicz.pl": 1,
"loyalist.museum": 1,
"lt.it": 1,
"lt.ua": 1,
"ltd.co.im": 1,
"ltd.gi": 1,
"ltd.lk": 1,
"lu.it": 1,
"lubin.pl": 1,
"lucca.it": 1,
"lucerne.museum": 1,
"lugansk.ua": 1,
"lukow.pl": 1,
"lund.no": 1,
"lunner.no": 1,
"luroy.no": 1,
"lur\u00f8y.no": 1,
"luster.no": 1,
"lutsk.ua": 1,
"luxembourg.museum": 1,
"luzern.museum": 1,
"lv.ua": 1,
"lviv.ua": 1,
"lyngdal.no": 1,
"lyngen.no": 1,
"l\u00e1hppi.no": 1,
"l\u00e4ns.museum": 1,
"l\u00e6rdal.no": 1,
"l\u00f8dingen.no": 1,
"l\u00f8renskog.no": 1,
"l\u00f8ten.no": 1,
"m.bg": 1,
"m.se": 1,
"ma.us": 1,
"macerata.it": 1,
"machida.tokyo.jp": 1,
"mad.museum": 1,
"madrid.museum": 1,
"maebashi.gunma.jp": 1,
"magadan.ru": 1,
"magazine.aero": 1,
"magnitka.ru": 1,
"maibara.shiga.jp": 1,
"mail.pl": 1,
"maintenance.aero": 1,
"maizuru.kyoto.jp": 1,
"makinohara.shizuoka.jp": 1,
"makurazaki.kagoshima.jp": 1,
"malatvuopmi.no": 1,
"malbork.pl": 1,
"mallorca.museum": 1,
"malopolska.pl": 1,
"malselv.no": 1,
"malvik.no": 1,
"mamurogawa.yamagata.jp": 1,
"manchester.museum": 1,
"mandal.no": 1,
"maniwa.okayama.jp": 1,
"manno.kagawa.jp": 1,
"mansion.museum": 1,
"mansions.museum": 1,
"mantova.it": 1,
"manx.museum": 1,
"marburg.museum": 1,
"mari-el.ru": 1,
"mari.ru": 1,
"marine.ru": 1,
"maritime.museum": 1,
"maritimo.museum": 1,
"marker.no": 1,
"marketplace.aero": 1,
"marnardal.no": 1,
"marugame.kagawa.jp": 1,
"marumori.miyagi.jp": 1,
"maryland.museum": 1,
"marylhurst.museum": 1,
"masaki.ehime.jp": 1,
"masfjorden.no": 1,
"mashike.hokkaido.jp": 1,
"mashiki.kumamoto.jp": 1,
"mashiko.tochigi.jp": 1,
"masoy.no": 1,
"massa-carrara.it": 1,
"massacarrara.it": 1,
"masuda.shimane.jp": 1,
"mat.br": 1,
"matera.it": 1,
"matsubara.osaka.jp": 1,
"matsubushi.saitama.jp": 1,
"matsuda.kanagawa.jp": 1,
"matsudo.chiba.jp": 1,
"matsue.shimane.jp": 1,
"matsukawa.nagano.jp": 1,
"matsumae.hokkaido.jp": 1,
"matsumoto.kagoshima.jp": 1,
"matsumoto.nagano.jp": 1,
"matsuno.ehime.jp": 1,
"matsusaka.mie.jp": 1,
"matsushige.tokushima.jp": 1,
"matsushima.miyagi.jp": 1,
"matsuura.nagasaki.jp": 1,
"matsuyama.ehime.jp": 1,
"matsuzaki.shizuoka.jp": 1,
"matta-varjjat.no": 1,
"mazowsze.pl": 1,
"mazury.pl": 1,
"mb.ca": 1,
"mb.it": 1,
"mbone.pl": 1,
"mc.it": 1,
"md.ci": 1,
"md.us": 1,
"me.it": 1,
"me.us": 1,
"mecon.ar": 0,
"med.br": 1,
"med.ec": 1,
"med.ee": 1,
"med.ht": 1,
"med.ly": 1,
"med.pa": 1,
"med.pl": 1,
"med.pro": 1,
"med.sa": 1,
"med.sd": 1,
"medecin.fr": 1,
"medecin.km": 1,
"media.aero": 1,
"media.hu": 1,
"media.museum": 1,
"media.pl": 1,
"mediaphone.om": 0,
"medical.museum": 1,
"medio-campidano.it": 1,
"mediocampidano.it": 1,
"medizinhistorisches.museum": 1,
"meeres.museum": 1,
"meguro.tokyo.jp": 1,
"meiwa.gunma.jp": 1,
"meiwa.mie.jp": 1,
"meland.no": 1,
"meldal.no": 1,
"melhus.no": 1,
"meloy.no": 1,
"mel\u00f8y.no": 1,
"memorial.museum": 1,
"meraker.no": 1,
"merseine.nu": 1,
"mer\u00e5ker.no": 1,
"mesaverde.museum": 1,
"messina.it": 1,
"mi.it": 1,
"mi.th": 1,
"mi.us": 1,
"miasa.nagano.jp": 1,
"miasta.pl": 1,
"mibu.tochigi.jp": 1,
"michigan.museum": 1,
"microlight.aero": 1,
"midatlantic.museum": 1,
"midori.chiba.jp": 1,
"midori.gunma.jp": 1,
"midsund.no": 1,
"midtre-gauldal.no": 1,
"mie.jp": 1,
"mielec.pl": 1,
"mielno.pl": 1,
"mifune.kumamoto.jp": 1,
"mihama.aichi.jp": 1,
"mihama.chiba.jp": 1,
"mihama.fukui.jp": 1,
"mihama.mie.jp": 1,
"mihama.wakayama.jp": 1,
"mihara.hiroshima.jp": 1,
"mihara.kochi.jp": 1,
"miharu.fukushima.jp": 1,
"miho.ibaraki.jp": 1,
"mikasa.hokkaido.jp": 1,
"mikawa.yamagata.jp": 1,
"miki.hyogo.jp": 1,
"mil.ac": 1,
"mil.ae": 1,
"mil.al": 1,
"mil.az": 1,
"mil.ba": 1,
"mil.bo": 1,
"mil.br": 1,
"mil.by": 1,
"mil.cl": 1,
"mil.cn": 1,
"mil.co": 1,
"mil.do": 1,
"mil.ec": 1,
"mil.eg": 1,
"mil.ge": 1,
"mil.gh": 1,
"mil.hn": 1,
"mil.id": 1,
"mil.in": 1,
"mil.iq": 1,
"mil.jo": 1,
"mil.kg": 1,
"mil.km": 1,
"mil.kr": 1,
"mil.kz": 1,
"mil.lv": 1,
"mil.mg": 1,
"mil.mv": 1,
"mil.my": 1,
"mil.no": 1,
"mil.pe": 1,
"mil.ph": 1,
"mil.pl": 1,
"mil.qa": 1,
"mil.ru": 1,
"mil.rw": 1,
"mil.sh": 1,
"mil.st": 1,
"mil.sy": 1,
"mil.tj": 1,
"mil.tm": 1,
"mil.to": 1,
"mil.tw": 1,
"mil.tz": 1,
"mil.uy": 1,
"mil.vc": 1,
"mil.ve": 1,
"milan.it": 1,
"milano.it": 1,
"military.museum": 1,
"mill.museum": 1,
"mima.tokushima.jp": 1,
"mimata.miyazaki.jp": 1,
"minakami.gunma.jp": 1,
"minamata.kumamoto.jp": 1,
"minami-alps.yamanashi.jp": 1,
"minami.fukuoka.jp": 1,
"minami.kyoto.jp": 1,
"minami.tokushima.jp": 1,
"minamiaiki.nagano.jp": 1,
"minamiashigara.kanagawa.jp": 1,
"minamiawaji.hyogo.jp": 1,
"minamiboso.chiba.jp": 1,
"minamidaito.okinawa.jp": 1,
"minamiechizen.fukui.jp": 1,
"minamifurano.hokkaido.jp": 1,
"minamiise.mie.jp": 1,
"minamiizu.shizuoka.jp": 1,
"minamimaki.nagano.jp": 1,
"minamiminowa.nagano.jp": 1,
"minamioguni.kumamoto.jp": 1,
"minamisanriku.miyagi.jp": 1,
"minamitane.kagoshima.jp": 1,
"minamiuonuma.niigata.jp": 1,
"minamiyamashiro.kyoto.jp": 1,
"minano.saitama.jp": 1,
"minato.osaka.jp": 1,
"minato.tokyo.jp": 1,
"mincom.tn": 1,
"mine.nu": 1,
"miners.museum": 1,
"mining.museum": 1,
"minnesota.museum": 1,
"mino.gifu.jp": 1,
"minobu.yamanashi.jp": 1,
"minoh.osaka.jp": 1,
"minokamo.gifu.jp": 1,
"minowa.nagano.jp": 1,
"misaki.okayama.jp": 1,
"misaki.osaka.jp": 1,
"misasa.tottori.jp": 1,
"misato.akita.jp": 1,
"misato.miyagi.jp": 1,
"misato.saitama.jp": 1,
"misato.shimane.jp": 1,
"misato.wakayama.jp": 1,
"misawa.aomori.jp": 1,
"misconfused.org": 1,
"mishima.fukushima.jp": 1,
"mishima.shizuoka.jp": 1,
"missile.museum": 1,
"missoula.museum": 1,
"misugi.mie.jp": 1,
"mitaka.tokyo.jp": 1,
"mitake.gifu.jp": 1,
"mitane.akita.jp": 1,
"mito.ibaraki.jp": 1,
"mitou.yamaguchi.jp": 1,
"mitoyo.kagawa.jp": 1,
"mitsue.nara.jp": 1,
"mitsuke.niigata.jp": 1,
"miura.kanagawa.jp": 1,
"miyada.nagano.jp": 1,
"miyagi.jp": 1,
"miyake.nara.jp": 1,
"miyako.fukuoka.jp": 1,
"miyako.iwate.jp": 1,
"miyakonojo.miyazaki.jp": 1,
"miyama.fukuoka.jp": 1,
"miyama.mie.jp": 1,
"miyashiro.saitama.jp": 1,
"miyawaka.fukuoka.jp": 1,
"miyazaki.jp": 1,
"miyazaki.miyazaki.jp": 1,
"miyazu.kyoto.jp": 1,
"miyoshi.aichi.jp": 1,
"miyoshi.hiroshima.jp": 1,
"miyoshi.saitama.jp": 1,
"miyoshi.tokushima.jp": 1,
"miyota.nagano.jp": 1,
"mizuho.tokyo.jp": 1,
"mizumaki.fukuoka.jp": 1,
"mizunami.gifu.jp": 1,
"mizusawa.iwate.jp": 1,
"mjondalen.no": 1,
"mj\u00f8ndalen.no": 1,
"mk.ua": 1,
"mm": 2,
"mn.it": 1,
"mn.us": 1,
"mo-i-rana.no": 1,
"mo.cn": 1,
"mo.it": 1,
"mo.us": 1,
"moareke.no": 1,
"mobara.chiba.jp": 1,
"mobi.gp": 1,
"mobi.na": 1,
"mobi.tt": 1,
"mochizuki.nagano.jp": 1,
"mod.gi": 1,
"mod.uk": 0,
"modalen.no": 1,
"modelling.aero": 1,
"modena.it": 1,
"modern.museum": 1,
"modum.no": 1,
"moka.tochigi.jp": 1,
"molde.no": 1,
"moma.museum": 1,
"mombetsu.hokkaido.jp": 1,
"money.museum": 1,
"monmouth.museum": 1,
"monticello.museum": 1,
"montreal.museum": 1,
"monza-brianza.it": 1,
"monza-e-della-brianza.it": 1,
"monza.it": 1,
"monzabrianza.it": 1,
"monzaebrianza.it": 1,
"monzaedellabrianza.it": 1,
"mordovia.ru": 1,
"moriguchi.osaka.jp": 1,
"morimachi.shizuoka.jp": 1,
"morioka.iwate.jp": 1,
"moriya.ibaraki.jp": 1,
"moriyama.shiga.jp": 1,
"moriyoshi.akita.jp": 1,
"morotsuka.miyazaki.jp": 1,
"moroyama.saitama.jp": 1,
"moscow.museum": 1,
"moseushi.hokkaido.jp": 1,
"mosjoen.no": 1,
"mosj\u00f8en.no": 1,
"moskenes.no": 1,
"mosreg.ru": 1,
"moss.no": 1,
"mosvik.no": 1,
"motegi.tochigi.jp": 1,
"motobu.okinawa.jp": 1,
"motorcycle.museum": 1,
"motosu.gifu.jp": 1,
"motoyama.kochi.jp": 1,
"mo\u00e5reke.no": 1,
"mr.no": 1,
"mragowo.pl": 1,
"ms.it": 1,
"ms.kr": 1,
"ms.us": 1,
"msk.ru": 1,
"mt": 2,
"mt.it": 1,
"mt.us": 1,
"muenchen.museum": 1,
"muenster.museum": 1,
"mugi.tokushima.jp": 1,
"muika.niigata.jp": 1,
"mukawa.hokkaido.jp": 1,
"muko.kyoto.jp": 1,
"mulhouse.museum": 1,
"munakata.fukuoka.jp": 1,
"muncie.museum": 1,
"muosat.no": 1,
"muos\u00e1t.no": 1,
"murakami.niigata.jp": 1,
"murata.miyagi.jp": 1,
"murayama.yamagata.jp": 1,
"murmansk.ru": 1,
"muroran.hokkaido.jp": 1,
"muroto.kochi.jp": 1,
"mus.br": 1,
"musashimurayama.tokyo.jp": 1,
"musashino.tokyo.jp": 1,
"museet.museum": 1,
"museum.mv": 1,
"museum.mw": 1,
"museum.no": 1,
"museum.tt": 1,
"museumcenter.museum": 1,
"museumvereniging.museum": 1,
"music.museum": 1,
"mutsu.aomori.jp": 1,
"mutsuzawa.chiba.jp": 1,
"mx.na": 1,
"mykolaiv.ua": 1,
"myoko.niigata.jp": 1,
"mypets.ws": 1,
"myphotos.cc": 1,
"mytis.ru": 1,
"mz": 2,
"m\u00e1latvuopmi.no": 1,
"m\u00e1tta-v\u00e1rjjat.no": 1,
"m\u00e5lselv.no": 1,
"m\u00e5s\u00f8y.no": 1,
"n.bg": 1,
"n.se": 1,
"na.it": 1,
"naamesjevuemie.no": 1,
"nabari.mie.jp": 1,
"nachikatsuura.wakayama.jp": 1,
"nacion.ar": 0,
"nagahama.shiga.jp": 1,
"nagai.yamagata.jp": 1,
"nagakute.aichi.jp": 1,
"nagano.jp": 1,
"nagano.nagano.jp": 1,
"naganohara.gunma.jp": 1,
"nagaoka.niigata.jp": 1,
"nagaokakyo.kyoto.jp": 1,
"nagara.chiba.jp": 1,
"nagareyama.chiba.jp": 1,
"nagasaki.jp": 1,
"nagasaki.nagasaki.jp": 1,
"nagasu.kumamoto.jp": 1,
"nagato.yamaguchi.jp": 1,
"nagatoro.saitama.jp": 1,
"nagawa.nagano.jp": 1,
"nagi.okayama.jp": 1,
"nagiso.nagano.jp": 1,
"nago.okinawa.jp": 1,
"nagoya.jp": 2,
"naha.okinawa.jp": 1,
"nahari.kochi.jp": 1,
"naie.hokkaido.jp": 1,
"naka.hiroshima.jp": 1,
"naka.ibaraki.jp": 1,
"nakadomari.aomori.jp": 1,
"nakagawa.fukuoka.jp": 1,
"nakagawa.hokkaido.jp": 1,
"nakagawa.nagano.jp": 1,
"nakagawa.tokushima.jp": 1,
"nakagusuku.okinawa.jp": 1,
"nakagyo.kyoto.jp": 1,
"nakai.kanagawa.jp": 1,
"nakama.fukuoka.jp": 1,
"nakamichi.yamanashi.jp": 1,
"nakamura.kochi.jp": 1,
"nakaniikawa.toyama.jp": 1,
"nakano.nagano.jp": 1,
"nakano.tokyo.jp": 1,
"nakanojo.gunma.jp": 1,
"nakanoto.ishikawa.jp": 1,
"nakasatsunai.hokkaido.jp": 1,
"nakatane.kagoshima.jp": 1,
"nakatombetsu.hokkaido.jp": 1,
"nakatsugawa.gifu.jp": 1,
"nakayama.yamagata.jp": 1,
"nakhodka.ru": 1,
"nakijin.okinawa.jp": 1,
"naklo.pl": 1,
"nalchik.ru": 1,
"namdalseid.no": 1,
"name.az": 1,
"name.eg": 1,
"name.hr": 1,
"name.jo": 1,
"name.mk": 1,
"name.mv": 1,
"name.my": 1,
"name.na": 1,
"name.pr": 1,
"name.qa": 1,
"name.tj": 1,
"name.tt": 1,
"name.vn": 1,
"namegata.ibaraki.jp": 1,
"namegawa.saitama.jp": 1,
"namerikawa.toyama.jp": 1,
"namie.fukushima.jp": 1,
"namikata.ehime.jp": 1,
"namsos.no": 1,
"namsskogan.no": 1,
"nanae.hokkaido.jp": 1,
"nanao.ishikawa.jp": 1,
"nanbu.tottori.jp": 1,
"nanbu.yamanashi.jp": 1,
"nango.fukushima.jp": 1,
"nanjo.okinawa.jp": 1,
"nankoku.kochi.jp": 1,
"nanmoku.gunma.jp": 1,
"nannestad.no": 1,
"nanporo.hokkaido.jp": 1,
"nantan.kyoto.jp": 1,
"nanto.toyama.jp": 1,
"nanyo.yamagata.jp": 1,
"naoshima.kagawa.jp": 1,
"naples.it": 1,
"napoli.it": 1,
"nara.jp": 1,
"nara.nara.jp": 1,
"narashino.chiba.jp": 1,
"narita.chiba.jp": 1,
"naroy.no": 1,
"narusawa.yamanashi.jp": 1,
"naruto.tokushima.jp": 1,
"narviika.no": 1,
"narvik.no": 1,
"nasu.tochigi.jp": 1,
"nasushiobara.tochigi.jp": 1,
"nat.tn": 1,
"national-library-scotland.uk": 0,
"national.museum": 1,
"nationalfirearms.museum": 1,
"nationalheritage.museum": 1,
"nativeamerican.museum": 1,
"natori.miyagi.jp": 1,
"naturalhistory.museum": 1,
"naturalhistorymuseum.museum": 1,
"naturalsciences.museum": 1,
"naturbruksgymn.se": 1,
"nature.museum": 1,
"naturhistorisches.museum": 1,
"natuurwetenschappen.museum": 1,
"naumburg.museum": 1,
"naustdal.no": 1,
"naval.museum": 1,
"navigation.aero": 1,
"navuotna.no": 1,
"nawras.om": 0,
"nawrastelecom.om": 0,
"nayoro.hokkaido.jp": 1,
"nb.ca": 1,
"nc.us": 1,
"nd.us": 1,
"ne.jp": 1,
"ne.kr": 1,
"ne.pw": 1,
"ne.tz": 1,
"ne.ug": 1,
"ne.us": 1,
"neat-url.com": 1,
"nebraska.museum": 1,
"nedre-eiker.no": 1,
"nel.uk": 0,
"nemuro.hokkaido.jp": 1,
"nerima.tokyo.jp": 1,
"nes.akershus.no": 1,
"nes.buskerud.no": 1,
"nesna.no": 1,
"nesodden.no": 1,
"nesoddtangen.no": 1,
"nesseby.no": 1,
"nesset.no": 1,
"net.ac": 1,
"net.ae": 1,
"net.af": 1,
"net.ag": 1,
"net.ai": 1,
"net.al": 1,
"net.an": 1,
"net.au": 1,
"net.az": 1,
"net.ba": 1,
"net.bb": 1,
"net.bh": 1,
"net.bm": 1,
"net.bo": 1,
"net.br": 1,
"net.bs": 1,
"net.bt": 1,
"net.bz": 1,
"net.ci": 1,
"net.cn": 1,
"net.co": 1,
"net.cu": 1,
"net.dm": 1,
"net.do": 1,
"net.dz": 1,
"net.ec": 1,
"net.eg": 1,
"net.ge": 1,
"net.gg": 1,
"net.gn": 1,
"net.gp": 1,
"net.gr": 1,
"net.gy": 1,
"net.hk": 1,
"net.hn": 1,
"net.ht": 1,
"net.id": 1,
"net.im": 1,
"net.in": 1,
"net.iq": 1,
"net.ir": 1,
"net.is": 1,
"net.je": 1,
"net.jo": 1,
"net.kg": 1,
"net.ki": 1,
"net.kn": 1,
"net.ky": 1,
"net.kz": 1,
"net.la": 1,
"net.lb": 1,
"net.lc": 1,
"net.lk": 1,
"net.lr": 1,
"net.lv": 1,
"net.ly": 1,
"net.ma": 1,
"net.me": 1,
"net.mk": 1,
"net.ml": 1,
"net.mo": 1,
"net.mu": 1,
"net.mv": 1,
"net.mw": 1,
"net.mx": 1,
"net.my": 1,
"net.nf": 1,
"net.ng": 1,
"net.nr": 1,
"net.pa": 1,
"net.pe": 1,
"net.ph": 1,
"net.pk": 1,
"net.pl": 1,
"net.pn": 1,
"net.pr": 1,
"net.ps": 1,
"net.pt": 1,
"net.qa": 1,
"net.ru": 1,
"net.rw": 1,
"net.sa": 1,
"net.sb": 1,
"net.sc": 1,
"net.sd": 1,
"net.sg": 1,
"net.sh": 1,
"net.sl": 1,
"net.so": 1,
"net.st": 1,
"net.sy": 1,
"net.th": 1,
"net.tj": 1,
"net.tm": 1,
"net.tn": 1,
"net.to": 1,
"net.tt": 1,
"net.tw": 1,
"net.ua": 1,
"net.uy": 1,
"net.uz": 1,
"net.vc": 1,
"net.ve": 1,
"net.vi": 1,
"net.vn": 1,
"net.ws": 1,
"neues.museum": 1,
"newhampshire.museum": 1,
"newjersey.museum": 1,
"newmexico.museum": 1,
"newport.museum": 1,
"news.hu": 1,
"newspaper.museum": 1,
"newyork.museum": 1,
"neyagawa.osaka.jp": 1,
"nf.ca": 1,
"ngo.lk": 1,
"ngo.ph": 1,
"ngo.pl": 1,
"nh.us": 1,
"nhs.uk": 2,
"ni": 2,
"nic.ar": 0,
"nic.im": 1,
"nic.in": 1,
"nic.tj": 1,
"nic.tr": 0,
"nic.uk": 0,
"nichinan.miyazaki.jp": 1,
"nichinan.tottori.jp": 1,
"niepce.museum": 1,
"nieruchomosci.pl": 1,
"niigata.jp": 1,
"niigata.niigata.jp": 1,
"niihama.ehime.jp": 1,
"niikappu.hokkaido.jp": 1,
"niimi.okayama.jp": 1,
"niiza.saitama.jp": 1,
"nikaho.akita.jp": 1,
"niki.hokkaido.jp": 1,
"nikko.tochigi.jp": 1,
"nikolaev.ua": 1,
"ninohe.iwate.jp": 1,
"ninomiya.kanagawa.jp": 1,
"nirasaki.yamanashi.jp": 1,
"nishi.fukuoka.jp": 1,
"nishi.osaka.jp": 1,
"nishiaizu.fukushima.jp": 1,
"nishiarita.saga.jp": 1,
"nishiawakura.okayama.jp": 1,
"nishiazai.shiga.jp": 1,
"nishigo.fukushima.jp": 1,
"nishihara.kumamoto.jp": 1,
"nishihara.okinawa.jp": 1,
"nishiizu.shizuoka.jp": 1,
"nishikata.tochigi.jp": 1,
"nishikatsura.yamanashi.jp": 1,
"nishikawa.yamagata.jp": 1,
"nishimera.miyazaki.jp": 1,
"nishinomiya.hyogo.jp": 1,
"nishinoomote.kagoshima.jp": 1,
"nishinoshima.shimane.jp": 1,
"nishio.aichi.jp": 1,
"nishiokoppe.hokkaido.jp": 1,
"nishitosa.kochi.jp": 1,
"nishiwaki.hyogo.jp": 1,
"nissedal.no": 1,
"nisshin.aichi.jp": 1,
"nittedal.no": 1,
"niyodogawa.kochi.jp": 1,
"nj.us": 1,
"nkz.ru": 1,
"nl.ca": 1,
"nl.no": 1,
"nls.uk": 0,
"nm.cn": 1,
"nm.us": 1,
"nnov.ru": 1,
"no.com": 1,
"no.it": 1,
"nobeoka.miyazaki.jp": 1,
"noboribetsu.hokkaido.jp": 1,
"noda.chiba.jp": 1,
"noda.iwate.jp": 1,
"nogata.fukuoka.jp": 1,
"nogi.tochigi.jp": 1,
"noheji.aomori.jp": 1,
"nom.ad": 1,
"nom.ag": 1,
"nom.br": 1,
"nom.co": 1,
"nom.es": 1,
"nom.fr": 1,
"nom.km": 1,
"nom.mg": 1,
"nom.pa": 1,
"nom.pe": 1,
"nom.pl": 1,
"nom.re": 1,
"nom.ro": 1,
"nom.tm": 1,
"nome.pt": 1,
"nomi.ishikawa.jp": 1,
"nonoichi.ishikawa.jp": 1,
"nord-aurdal.no": 1,
"nord-fron.no": 1,
"nord-odal.no": 1,
"norddal.no": 1,
"nordkapp.no": 1,
"nordre-land.no": 1,
"nordreisa.no": 1,
"nore-og-uvdal.no": 1,
"norfolk.museum": 1,
"norilsk.ru": 1,
"north.museum": 1,
"nose.osaka.jp": 1,
"nosegawa.nara.jp": 1,
"noshiro.akita.jp": 1,
"not.br": 1,
"notaires.fr": 1,
"notaires.km": 1,
"noto.ishikawa.jp": 1,
"notodden.no": 1,
"notogawa.shiga.jp": 1,
"notteroy.no": 1,
"nov.ru": 1,
"novara.it": 1,
"novosibirsk.ru": 1,
"nowaruda.pl": 1,
"nozawaonsen.nagano.jp": 1,
"np": 2,
"nrw.museum": 1,
"ns.ca": 1,
"nsk.ru": 1,
"nsn.us": 1,
"nsw.au": 1,
"nsw.edu.au": 1,
"nt.au": 1,
"nt.ca": 1,
"nt.edu.au": 1,
"nt.gov.au": 1,
"nt.no": 1,
"nt.ro": 1,
"ntr.br": 1,
"nu.ca": 1,
"nu.it": 1,
"nuernberg.museum": 1,
"numata.gunma.jp": 1,
"numata.hokkaido.jp": 1,
"numazu.shizuoka.jp": 1,
"nuoro.it": 1,
"nuremberg.museum": 1,
"nv.us": 1,
"nx.cn": 1,
"ny.us": 1,
"nyc.museum": 1,
"nyny.museum": 1,
"nysa.pl": 1,
"nyuzen.toyama.jp": 1,
"nz": 2,
"n\u00e1vuotna.no": 1,
"n\u00e5\u00e5mesjevuemie.no": 1,
"n\u00e6r\u00f8y.no": 1,
"n\u00f8tter\u00f8y.no": 1,
"o.bg": 1,
"o.se": 1,
"oamishirasato.chiba.jp": 1,
"oarai.ibaraki.jp": 1,
"obama.fukui.jp": 1,
"obama.nagasaki.jp": 1,
"obanazawa.yamagata.jp": 1,
"obihiro.hokkaido.jp": 1,
"obira.hokkaido.jp": 1,
"obu.aichi.jp": 1,
"obuse.nagano.jp": 1,
"oceanographic.museum": 1,
"oceanographique.museum": 1,
"ochi.kochi.jp": 1,
"od.ua": 1,
"odate.akita.jp": 1,
"odawara.kanagawa.jp": 1,
"odda.no": 1,
"odesa.ua": 1,
"odessa.ua": 1,
"odo.br": 1,
"oe.yamagata.jp": 1,
"of.by": 1,
"of.no": 1,
"off.ai": 1,
"office-on-the.net": 1,
"ofunato.iwate.jp": 1,
"og.ao": 1,
"og.it": 1,
"oga.akita.jp": 1,
"ogaki.gifu.jp": 1,
"ogano.saitama.jp": 1,
"ogasawara.tokyo.jp": 1,
"ogata.akita.jp": 1,
"ogawa.ibaraki.jp": 1,
"ogawa.nagano.jp": 1,
"ogawa.saitama.jp": 1,
"ogawara.miyagi.jp": 1,
"ogi.saga.jp": 1,
"ogimi.okinawa.jp": 1,
"ogliastra.it": 1,
"ogori.fukuoka.jp": 1,
"ogose.saitama.jp": 1,
"oguchi.aichi.jp": 1,
"oguni.kumamoto.jp": 1,
"oguni.yamagata.jp": 1,
"oh.us": 1,
"oharu.aichi.jp": 1,
"ohda.shimane.jp": 1,
"ohi.fukui.jp": 1,
"ohira.miyagi.jp": 1,
"ohira.tochigi.jp": 1,
"ohkura.yamagata.jp": 1,
"ohtawara.tochigi.jp": 1,
"oi.kanagawa.jp": 1,
"oirase.aomori.jp": 1,
"oishida.yamagata.jp": 1,
"oiso.kanagawa.jp": 1,
"oita.jp": 1,
"oita.oita.jp": 1,
"oizumi.gunma.jp": 1,
"oji.nara.jp": 1,
"ojiya.niigata.jp": 1,
"ok.us": 1,
"okagaki.fukuoka.jp": 1,
"okawa.fukuoka.jp": 1,
"okawa.kochi.jp": 1,
"okaya.nagano.jp": 1,
"okayama.jp": 1,
"okayama.okayama.jp": 1,
"okazaki.aichi.jp": 1,
"okegawa.saitama.jp": 1,
"oketo.hokkaido.jp": 1,
"oki.fukuoka.jp": 1,
"okinawa.jp": 1,
"okinawa.okinawa.jp": 1,
"okinoshima.shimane.jp": 1,
"okoppe.hokkaido.jp": 1,
"oksnes.no": 1,
"okuizumo.shimane.jp": 1,
"okuma.fukushima.jp": 1,
"okutama.tokyo.jp": 1,
"ol.no": 1,
"olawa.pl": 1,
"olbia-tempio.it": 1,
"olbiatempio.it": 1,
"olecko.pl": 1,
"olkusz.pl": 1,
"olsztyn.pl": 1,
"om": 2,
"omachi.nagano.jp": 1,
"omachi.saga.jp": 1,
"omaezaki.shizuoka.jp": 1,
"omaha.museum": 1,
"omanmobile.om": 0,
"omanpost.om": 0,
"omantel.om": 0,
"omasvuotna.no": 1,
"ome.tokyo.jp": 1,
"omi.nagano.jp": 1,
"omi.niigata.jp": 1,
"omigawa.chiba.jp": 1,
"omihachiman.shiga.jp": 1,
"omitama.ibaraki.jp": 1,
"omiya.saitama.jp": 1,
"omotego.fukushima.jp": 1,
"omsk.ru": 1,
"omura.nagasaki.jp": 1,
"omuta.fukuoka.jp": 1,
"on-the-web.tv": 1,
"on.ca": 1,
"onagawa.miyagi.jp": 1,
"onga.fukuoka.jp": 1,
"onjuku.chiba.jp": 1,
"online.museum": 1,
"onna.okinawa.jp": 1,
"ono.fukui.jp": 1,
"ono.fukushima.jp": 1,
"ono.hyogo.jp": 1,
"onojo.fukuoka.jp": 1,
"onomichi.hiroshima.jp": 1,
"ontario.museum": 1,
"ookuwa.nagano.jp": 1,
"ooshika.nagano.jp": 1,
"openair.museum": 1,
"operaunite.com": 1,
"opoczno.pl": 1,
"opole.pl": 1,
"oppdal.no": 1,
"oppegard.no": 1,
"oppeg\u00e5rd.no": 1,
"or.at": 1,
"or.bi": 1,
"or.ci": 1,
"or.cr": 1,
"or.id": 1,
"or.it": 1,
"or.jp": 1,
"or.kr": 1,
"or.mu": 1,
"or.na": 1,
"or.pw": 1,
"or.th": 1,
"or.tz": 1,
"or.ug": 1,
"or.us": 1,
"ora.gunma.jp": 1,
"oregon.museum": 1,
"oregontrail.museum": 1,
"orenburg.ru": 1,
"org.ac": 1,
"org.ae": 1,
"org.af": 1,
"org.ag": 1,
"org.ai": 1,
"org.al": 1,
"org.an": 1,
"org.au": 1,
"org.az": 1,
"org.ba": 1,
"org.bb": 1,
"org.bh": 1,
"org.bi": 1,
"org.bm": 1,
"org.bo": 1,
"org.br": 1,
"org.bs": 1,
"org.bt": 1,
"org.bw": 1,
"org.bz": 1,
"org.ci": 1,
"org.cn": 1,
"org.co": 1,
"org.cu": 1,
"org.dm": 1,
"org.do": 1,
"org.dz": 1,
"org.ec": 1,
"org.ee": 1,
"org.eg": 1,
"org.es": 1,
"org.ge": 1,
"org.gg": 1,
"org.gh": 1,
"org.gi": 1,
"org.gn": 1,
"org.gp": 1,
"org.gr": 1,
"org.hk": 1,
"org.hn": 1,
"org.ht": 1,
"org.hu": 1,
"org.im": 1,
"org.in": 1,
"org.iq": 1,
"org.ir": 1,
"org.is": 1,
"org.je": 1,
"org.jo": 1,
"org.kg": 1,
"org.ki": 1,
"org.km": 1,
"org.kn": 1,
"org.kp": 1,
"org.ky": 1,
"org.kz": 1,
"org.la": 1,
"org.lb": 1,
"org.lc": 1,
"org.lk": 1,
"org.lr": 1,
"org.ls": 1,
"org.lv": 1,
"org.ly": 1,
"org.ma": 1,
"org.me": 1,
"org.mg": 1,
"org.mk": 1,
"org.ml": 1,
"org.mn": 1,
"org.mo": 1,
"org.mu": 1,
"org.mv": 1,
"org.mw": 1,
"org.mx": 1,
"org.my": 1,
"org.na": 1,
"org.ng": 1,
"org.nr": 1,
"org.pa": 1,
"org.pe": 1,
"org.pf": 1,
"org.ph": 1,
"org.pk": 1,
"org.pl": 1,
"org.pn": 1,
"org.pr": 1,
"org.ps": 1,
"org.pt": 1,
"org.qa": 1,
"org.ro": 1,
"org.rs": 1,
"org.ru": 1,
"org.sa": 1,
"org.sb": 1,
"org.sc": 1,
"org.sd": 1,
"org.se": 1,
"org.sg": 1,
"org.sh": 1,
"org.sl": 1,
"org.sn": 1,
"org.so": 1,
"org.st": 1,
"org.sy": 1,
"org.sz": 1,
"org.tj": 1,
"org.tm": 1,
"org.tn": 1,
"org.to": 1,
"org.tt": 1,
"org.tw": 1,
"org.ua": 1,
"org.ug": 1,
"org.uy": 1,
"org.uz": 1,
"org.vc": 1,
"org.ve": 1,
"org.vi": 1,
"org.vn": 1,
"org.ws": 1,
"oristano.it": 1,
"orkanger.no": 1,
"orkdal.no": 1,
"orland.no": 1,
"orskog.no": 1,
"orsta.no": 1,
"oryol.ru": 1,
"os.hedmark.no": 1,
"os.hordaland.no": 1,
"osaka.jp": 1,
"osakasayama.osaka.jp": 1,
"osaki.miyagi.jp": 1,
"osakikamijima.hiroshima.jp": 1,
"osen.no": 1,
"oseto.nagasaki.jp": 1,
"oshima.tokyo.jp": 1,
"oshima.yamaguchi.jp": 1,
"oshino.yamanashi.jp": 1,
"oshu.iwate.jp": 1,
"oskol.ru": 1,
"oslo.no": 1,
"osoyro.no": 1,
"osteroy.no": 1,
"oster\u00f8y.no": 1,
"ostre-toten.no": 1,
"ostroda.pl": 1,
"ostroleka.pl": 1,
"ostrowiec.pl": 1,
"ostrowwlkp.pl": 1,
"os\u00f8yro.no": 1,
"ot.it": 1,
"ota.gunma.jp": 1,
"ota.tokyo.jp": 1,
"otago.museum": 1,
"otake.hiroshima.jp": 1,
"otaki.chiba.jp": 1,
"otaki.nagano.jp": 1,
"otaki.saitama.jp": 1,
"otama.fukushima.jp": 1,
"otari.nagano.jp": 1,
"otaru.hokkaido.jp": 1,
"other.nf": 1,
"oto.fukuoka.jp": 1,
"otobe.hokkaido.jp": 1,
"otofuke.hokkaido.jp": 1,
"otoineppu.hokkaido.jp": 1,
"otoyo.kochi.jp": 1,
"otsu.shiga.jp": 1,
"otsuchi.iwate.jp": 1,
"otsuki.kochi.jp": 1,
"otsuki.yamanashi.jp": 1,
"ouchi.saga.jp": 1,
"ouda.nara.jp": 1,
"oumu.hokkaido.jp": 1,
"overhalla.no": 1,
"ovre-eiker.no": 1,
"owani.aomori.jp": 1,
"owariasahi.aichi.jp": 1,
"oxford.museum": 1,
"oyabe.toyama.jp": 1,
"oyama.tochigi.jp": 1,
"oyamazaki.kyoto.jp": 1,
"oyer.no": 1,
"oygarden.no": 1,
"oyodo.nara.jp": 1,
"oystre-slidre.no": 1,
"oz.au": 1,
"ozora.hokkaido.jp": 1,
"ozu.ehime.jp": 1,
"ozu.kumamoto.jp": 1,
"p.bg": 1,
"p.se": 1,
"pa.gov.pl": 1,
"pa.it": 1,
"pa.us": 1,
"pacific.museum": 1,
"paderborn.museum": 1,
"padova.it": 1,
"padua.it": 1,
"palace.museum": 1,
"palana.ru": 1,
"paleo.museum": 1,
"palermo.it": 1,
"palmsprings.museum": 1,
"panama.museum": 1,
"parachuting.aero": 1,
"paragliding.aero": 1,
"paris.museum": 1,
"parliament.uk": 0,
"parma.it": 1,
"paroch.k12.ma.us": 1,
"parti.se": 1,
"pasadena.museum": 1,
"passenger-association.aero": 1,
"pavia.it": 1,
"pb.ao": 1,
"pc.it": 1,
"pc.pl": 1,
"pd.it": 1,
"pe.ca": 1,
"pe.it": 1,
"pe.kr": 1,
"penza.ru": 1,
"per.la": 1,
"per.nf": 1,
"per.sg": 1,
"perm.ru": 1,
"perso.ht": 1,
"perso.sn": 1,
"perso.tn": 1,
"perugia.it": 1,
"pesaro-urbino.it": 1,
"pesarourbino.it": 1,
"pescara.it": 1,
"pg": 2,
"pg.it": 1,
"pharmacien.fr": 1,
"pharmaciens.km": 1,
"pharmacy.museum": 1,
"philadelphia.museum": 1,
"philadelphiaarea.museum": 1,
"philately.museum": 1,
"phoenix.museum": 1,
"photography.museum": 1,
"pi.it": 1,
"piacenza.it": 1,
"pila.pl": 1,
"pilot.aero": 1,
"pilots.museum": 1,
"pippu.hokkaido.jp": 1,
"pisa.it": 1,
"pistoia.it": 1,
"pisz.pl": 1,
"pittsburgh.museum": 1,
"pl.ua": 1,
"planetarium.museum": 1,
"plantation.museum": 1,
"plants.museum": 1,
"plaza.museum": 1,
"plc.co.im": 1,
"plc.ly": 1,
"plo.ps": 1,
"pn.it": 1,
"po.gov.pl": 1,
"po.it": 1,
"podhale.pl": 1,
"podlasie.pl": 1,
"podzone.net": 1,
"podzone.org": 1,
"pol.dz": 1,
"pol.ht": 1,
"police.uk": 2,
"polkowice.pl": 1,
"poltava.ua": 1,
"pomorskie.pl": 1,
"pomorze.pl": 1,
"pordenone.it": 1,
"porsanger.no": 1,
"porsangu.no": 1,
"porsgrunn.no": 1,
"pors\u00e1\u014bgu.no": 1,
"port.fr": 1,
"portal.museum": 1,
"portland.museum": 1,
"portlligat.museum": 1,
"posts-and-telecommunications.museum": 1,
"potenza.it": 1,
"powiat.pl": 1,
"poznan.pl": 1,
"pp.az": 1,
"pp.ru": 1,
"pp.se": 1,
"pp.ua": 1,
"ppg.br": 1,
"pr.it": 1,
"pr.us": 1,
"prato.it": 1,
"prd.fr": 1,
"prd.km": 1,
"prd.mg": 1,
"preservation.museum": 1,
"presidio.museum": 1,
"press.aero": 1,
"press.ma": 1,
"press.museum": 1,
"press.se": 1,
"presse.ci": 1,
"presse.fr": 1,
"presse.km": 1,
"presse.ml": 1,
"pri.ee": 1,
"principe.st": 1,
"priv.at": 1,
"priv.hu": 1,
"priv.me": 1,
"priv.no": 1,
"priv.pl": 1,
"pro.az": 1,
"pro.br": 1,
"pro.ec": 1,
"pro.ht": 1,
"pro.mv": 1,
"pro.na": 1,
"pro.pr": 1,
"pro.tt": 1,
"pro.vn": 1,
"prochowice.pl": 1,
"production.aero": 1,
"prof.pr": 1,
"project.museum": 1,
"promocion.ar": 0,
"pruszkow.pl": 1,
"przeworsk.pl": 1,
"psc.br": 1,
"psi.br": 1,
"pskov.ru": 1,
"pt.it": 1,
"ptz.ru": 1,
"pu.it": 1,
"pub.sa": 1,
"publ.pt": 1,
"public.museum": 1,
"pubol.museum": 1,
"pulawy.pl": 1,
"pv.it": 1,
"pvt.ge": 1,
"pvt.k12.ma.us": 1,
"py": 2,
"pyatigorsk.ru": 1,
"pz.it": 1,
"q.bg": 1,
"qc.ca": 1,
"qc.com": 1,
"qh.cn": 1,
"qld.au": 1,
"qld.edu.au": 1,
"qld.gov.au": 1,
"qsl.br": 1,
"quebec.museum": 1,
"r.bg": 1,
"r.se": 1,
"ra.it": 1,
"rade.no": 1,
"radio.br": 1,
"radom.pl": 1,
"radoy.no": 1,
"rad\u00f8y.no": 1,
"ragusa.it": 1,
"rahkkeravju.no": 1,
"raholt.no": 1,
"railroad.museum": 1,
"railway.museum": 1,
"raisa.no": 1,
"rakkestad.no": 1,
"rakpetroleum.om": 0,
"ralingen.no": 1,
"rana.no": 1,
"randaberg.no": 1,
"rankoshi.hokkaido.jp": 1,
"ranzan.saitama.jp": 1,
"rauma.no": 1,
"ravenna.it": 1,
"rawa-maz.pl": 1,
"rc.it": 1,
"re.it": 1,
"re.kr": 1,
"readmyblog.org": 1,
"realestate.pl": 1,
"rebun.hokkaido.jp": 1,
"rec.br": 1,
"rec.co": 1,
"rec.nf": 1,
"rec.ro": 1,
"recreation.aero": 1,
"reggio-calabria.it": 1,
"reggio-emilia.it": 1,
"reggiocalabria.it": 1,
"reggioemilia.it": 1,
"reklam.hu": 1,
"rel.ht": 1,
"rel.pl": 1,
"rendalen.no": 1,
"rennebu.no": 1,
"rennesoy.no": 1,
"rennes\u00f8y.no": 1,
"rep.kp": 1,
"repbody.aero": 1,
"res.aero": 1,
"res.in": 1,
"research.aero": 1,
"research.museum": 1,
"resistance.museum": 1,
"retina.ar": 0,
"rg.it": 1,
"ri.it": 1,
"ri.us": 1,
"rieti.it": 1,
"rifu.miyagi.jp": 1,
"riik.ee": 1,
"rikubetsu.hokkaido.jp": 1,
"rikuzentakata.iwate.jp": 1,
"rimini.it": 1,
"rindal.no": 1,
"ringebu.no": 1,
"ringerike.no": 1,
"ringsaker.no": 1,
"riodejaneiro.museum": 1,
"rishiri.hokkaido.jp": 1,
"rishirifuji.hokkaido.jp": 1,
"risor.no": 1,
"rissa.no": 1,
"ris\u00f8r.no": 1,
"ritto.shiga.jp": 1,
"rivne.ua": 1,
"rl.no": 1,
"rm.it": 1,
"rn.it": 1,
"rnd.ru": 1,
"rnrt.tn": 1,
"rns.tn": 1,
"rnu.tn": 1,
"ro.it": 1,
"roan.no": 1,
"rochester.museum": 1,
"rockart.museum": 1,
"rodoy.no": 1,
"rokunohe.aomori.jp": 1,
"rollag.no": 1,
"roma.it": 1,
"roma.museum": 1,
"rome.it": 1,
"romsa.no": 1,
"romskog.no": 1,
"roros.no": 1,
"rost.no": 1,
"rotorcraft.aero": 1,
"rovigo.it": 1,
"rovno.ua": 1,
"royken.no": 1,
"royrvik.no": 1,
"rs.ba": 1,
"ru.com": 1,
"rubtsovsk.ru": 1,
"ruovat.no": 1,
"russia.museum": 1,
"rv.ua": 1,
"ryazan.ru": 1,
"rybnik.pl": 1,
"rygge.no": 1,
"ryokami.saitama.jp": 1,
"ryugasaki.ibaraki.jp": 1,
"ryuoh.shiga.jp": 1,
"rzeszow.pl": 1,
"r\u00e1hkker\u00e1vju.no": 1,
"r\u00e1isa.no": 1,
"r\u00e5de.no": 1,
"r\u00e5holt.no": 1,
"r\u00e6lingen.no": 1,
"r\u00f8d\u00f8y.no": 1,
"r\u00f8mskog.no": 1,
"r\u00f8ros.no": 1,
"r\u00f8st.no": 1,
"r\u00f8yken.no": 1,
"r\u00f8yrvik.no": 1,
"s.bg": 1,
"s.se": 1,
"sa.au": 1,
"sa.com": 1,
"sa.cr": 1,
"sa.edu.au": 1,
"sa.gov.au": 1,
"sa.it": 1,
"sabae.fukui.jp": 1,
"sado.niigata.jp": 1,
"safety.aero": 1,
"saga.jp": 1,
"saga.saga.jp": 1,
"sagae.yamagata.jp": 1,
"sagamihara.kanagawa.jp": 1,
"saigawa.fukuoka.jp": 1,
"saijo.ehime.jp": 1,
"saikai.nagasaki.jp": 1,
"saiki.oita.jp": 1,
"saintlouis.museum": 1,
"saitama.jp": 1,
"saitama.saitama.jp": 1,
"saito.miyazaki.jp": 1,
"saka.hiroshima.jp": 1,
"sakado.saitama.jp": 1,
"sakae.chiba.jp": 1,
"sakae.nagano.jp": 1,
"sakahogi.gifu.jp": 1,
"sakai.fukui.jp": 1,
"sakai.ibaraki.jp": 1,
"sakai.osaka.jp": 1,
"sakaiminato.tottori.jp": 1,
"sakaki.nagano.jp": 1,
"sakata.yamagata.jp": 1,
"sakawa.kochi.jp": 1,
"sakegawa.yamagata.jp": 1,
"sakhalin.ru": 1,
"saku.nagano.jp": 1,
"sakuho.nagano.jp": 1,
"sakura.chiba.jp": 1,
"sakura.tochigi.jp": 1,
"sakuragawa.ibaraki.jp": 1,
"sakurai.nara.jp": 1,
"sakyo.kyoto.jp": 1,
"salangen.no": 1,
"salat.no": 1,
"salem.museum": 1,
"salerno.it": 1,
"saltdal.no": 1,
"salvadordali.museum": 1,
"salzburg.museum": 1,
"samara.ru": 1,
"samegawa.fukushima.jp": 1,
"samnanger.no": 1,
"samukawa.kanagawa.jp": 1,
"sanagochi.tokushima.jp": 1,
"sanda.hyogo.jp": 1,
"sande.more-og-romsdal.no": 1,
"sande.m\u00f8re-og-romsdal.no": 1,
"sande.vestfold.no": 1,
"sandefjord.no": 1,
"sandiego.museum": 1,
"sandnes.no": 1,
"sandnessjoen.no": 1,
"sandnessj\u00f8en.no": 1,
"sandoy.no": 1,
"sand\u00f8y.no": 1,
"sanfrancisco.museum": 1,
"sango.nara.jp": 1,
"sanjo.niigata.jp": 1,
"sannan.hyogo.jp": 1,
"sannohe.aomori.jp": 1,
"sano.tochigi.jp": 1,
"sanok.pl": 1,
"santabarbara.museum": 1,
"santacruz.museum": 1,
"santafe.museum": 1,
"sanuki.kagawa.jp": 1,
"saotome.st": 1,
"sapporo.jp": 2,
"saratov.ru": 1,
"saroma.hokkaido.jp": 1,
"sarpsborg.no": 1,
"sarufutsu.hokkaido.jp": 1,
"sasaguri.fukuoka.jp": 1,
"sasayama.hyogo.jp": 1,
"sasebo.nagasaki.jp": 1,
"saskatchewan.museum": 1,
"sassari.it": 1,
"satosho.okayama.jp": 1,
"satsumasendai.kagoshima.jp": 1,
"satte.saitama.jp": 1,
"satx.museum": 1,
"sauda.no": 1,
"sauherad.no": 1,
"savannahga.museum": 1,
"saves-the-whales.com": 1,
"savona.it": 1,
"sayama.osaka.jp": 1,
"sayama.saitama.jp": 1,
"sayo.hyogo.jp": 1,
"sb.ua": 1,
"sc.cn": 1,
"sc.kr": 1,
"sc.tz": 1,
"sc.ug": 1,
"sc.us": 1,
"sch.ae": 1,
"sch.gg": 1,
"sch.id": 1,
"sch.ir": 1,
"sch.je": 1,
"sch.jo": 1,
"sch.lk": 1,
"sch.ly": 1,
"sch.qa": 1,
"sch.sa": 1,
"sch.uk": 2,
"schlesisches.museum": 1,
"schoenbrunn.museum": 1,
"schokoladen.museum": 1,
"school.museum": 1,
"school.na": 1,
"schweiz.museum": 1,
"sci.eg": 1,
"science-fiction.museum": 1,
"science.museum": 1,
"scienceandhistory.museum": 1,
"scienceandindustry.museum": 1,
"sciencecenter.museum": 1,
"sciencecenters.museum": 1,
"sciencehistory.museum": 1,
"sciences.museum": 1,
"sciencesnaturelles.museum": 1,
"scientist.aero": 1,
"scotland.museum": 1,
"scrapper-site.net": 1,
"scrapping.cc": 1,
"sd.cn": 1,
"sd.us": 1,
"se.com": 1,
"se.net": 1,
"seaport.museum": 1,
"sebastopol.ua": 1,
"sec.ps": 1,
"seihi.nagasaki.jp": 1,
"seika.kyoto.jp": 1,
"seiro.niigata.jp": 1,
"seirou.niigata.jp": 1,
"seiyo.ehime.jp": 1,
"sejny.pl": 1,
"seki.gifu.jp": 1,
"sekigahara.gifu.jp": 1,
"sekikawa.niigata.jp": 1,
"sel.no": 1,
"selbu.no": 1,
"selfip.biz": 1,
"selfip.com": 1,
"selfip.info": 1,
"selfip.net": 1,
"selfip.org": 1,
"selje.no": 1,
"seljord.no": 1,
"sells-for-less.com": 1,
"sells-for-u.com": 1,
"sells-it.net": 1,
"sellsyourhome.org": 1,
"semboku.akita.jp": 1,
"semine.miyagi.jp": 1,
"sendai.jp": 2,
"sennan.osaka.jp": 1,
"seoul.kr": 1,
"sera.hiroshima.jp": 1,
"seranishi.hiroshima.jp": 1,
"servebbs.com": 1,
"servebbs.net": 1,
"servebbs.org": 1,
"serveftp.net": 1,
"serveftp.org": 1,
"servegame.org": 1,
"services.aero": 1,
"setagaya.tokyo.jp": 1,
"seto.aichi.jp": 1,
"setouchi.okayama.jp": 1,
"settlement.museum": 1,
"settlers.museum": 1,
"settsu.osaka.jp": 1,
"sevastopol.ua": 1,
"sex.hu": 1,
"sex.pl": 1,
"sf.no": 1,
"sh.cn": 1,
"shacknet.nu": 1,
"shakotan.hokkaido.jp": 1,
"shari.hokkaido.jp": 1,
"shell.museum": 1,
"sherbrooke.museum": 1,
"shibata.miyagi.jp": 1,
"shibata.niigata.jp": 1,
"shibecha.hokkaido.jp": 1,
"shibetsu.hokkaido.jp": 1,
"shibukawa.gunma.jp": 1,
"shibuya.tokyo.jp": 1,
"shichikashuku.miyagi.jp": 1,
"shichinohe.aomori.jp": 1,
"shiga.jp": 1,
"shiiba.miyazaki.jp": 1,
"shijonawate.osaka.jp": 1,
"shika.ishikawa.jp": 1,
"shikabe.hokkaido.jp": 1,
"shikama.miyagi.jp": 1,
"shikaoi.hokkaido.jp": 1,
"shikatsu.aichi.jp": 1,
"shiki.saitama.jp": 1,
"shikokuchuo.ehime.jp": 1,
"shima.mie.jp": 1,
"shimabara.nagasaki.jp": 1,
"shimada.shizuoka.jp": 1,
"shimamaki.hokkaido.jp": 1,
"shimamoto.osaka.jp": 1,
"shimane.jp": 1,
"shimane.shimane.jp": 1,
"shimizu.hokkaido.jp": 1,
"shimizu.shizuoka.jp": 1,
"shimoda.shizuoka.jp": 1,
"shimodate.ibaraki.jp": 1,
"shimofusa.chiba.jp": 1,
"shimogo.fukushima.jp": 1,
"shimoichi.nara.jp": 1,
"shimoji.okinawa.jp": 1,
"shimokawa.hokkaido.jp": 1,
"shimokitayama.nara.jp": 1,
"shimonita.gunma.jp": 1,
"shimonoseki.yamaguchi.jp": 1,
"shimosuwa.nagano.jp": 1,
"shimotsuke.tochigi.jp": 1,
"shimotsuma.ibaraki.jp": 1,
"shinagawa.tokyo.jp": 1,
"shinanomachi.nagano.jp": 1,
"shingo.aomori.jp": 1,
"shingu.fukuoka.jp": 1,
"shingu.hyogo.jp": 1,
"shingu.wakayama.jp": 1,
"shinichi.hiroshima.jp": 1,
"shinjo.nara.jp": 1,
"shinjo.okayama.jp": 1,
"shinjo.yamagata.jp": 1,
"shinjuku.tokyo.jp": 1,
"shinkamigoto.nagasaki.jp": 1,
"shinonsen.hyogo.jp": 1,
"shinshinotsu.hokkaido.jp": 1,
"shinshiro.aichi.jp": 1,
"shinto.gunma.jp": 1,
"shintoku.hokkaido.jp": 1,
"shintomi.miyazaki.jp": 1,
"shinyoshitomi.fukuoka.jp": 1,
"shiogama.miyagi.jp": 1,
"shiojiri.nagano.jp": 1,
"shioya.tochigi.jp": 1,
"shirahama.wakayama.jp": 1,
"shirakawa.fukushima.jp": 1,
"shirakawa.gifu.jp": 1,
"shirako.chiba.jp": 1,
"shiranuka.hokkaido.jp": 1,
"shiraoi.hokkaido.jp": 1,
"shiraoka.saitama.jp": 1,
"shirataka.yamagata.jp": 1,
"shiriuchi.hokkaido.jp": 1,
"shiroi.chiba.jp": 1,
"shiroishi.miyagi.jp": 1,
"shiroishi.saga.jp": 1,
"shirosato.ibaraki.jp": 1,
"shishikui.tokushima.jp": 1,
"shiso.hyogo.jp": 1,
"shisui.chiba.jp": 1,
"shitara.aichi.jp": 1,
"shiwa.iwate.jp": 1,
"shizukuishi.iwate.jp": 1,
"shizuoka.jp": 1,
"shizuoka.shizuoka.jp": 1,
"shobara.hiroshima.jp": 1,
"shonai.fukuoka.jp": 1,
"shonai.yamagata.jp": 1,
"shoo.okayama.jp": 1,
"shop.ht": 1,
"shop.hu": 1,
"shop.pl": 1,
"show.aero": 1,
"showa.fukushima.jp": 1,
"showa.gunma.jp": 1,
"showa.yamanashi.jp": 1,
"shunan.yamaguchi.jp": 1,
"si.it": 1,
"sibenik.museum": 1,
"siedlce.pl": 1,
"siellak.no": 1,
"siemens.om": 0,
"siena.it": 1,
"sigdal.no": 1,
"siljan.no": 1,
"silk.museum": 1,
"simbirsk.ru": 1,
"simple-url.com": 1,
"siracusa.it": 1,
"sirdal.no": 1,
"sk.ca": 1,
"skanit.no": 1,
"skanland.no": 1,
"skaun.no": 1,
"skedsmo.no": 1,
"skedsmokorset.no": 1,
"ski.museum": 1,
"ski.no": 1,
"skien.no": 1,
"skierva.no": 1,
"skierv\u00e1.no": 1,
"skiptvet.no": 1,
"skjak.no": 1,
"skjervoy.no": 1,
"skjerv\u00f8y.no": 1,
"skj\u00e5k.no": 1,
"sklep.pl": 1,
"skoczow.pl": 1,
"skodje.no": 1,
"skole.museum": 1,
"skydiving.aero": 1,
"sk\u00e1nit.no": 1,
"sk\u00e5nland.no": 1,
"slask.pl": 1,
"slattum.no": 1,
"sld.do": 1,
"sld.pa": 1,
"slg.br": 1,
"slupsk.pl": 1,
"sm.ua": 1,
"smola.no": 1,
"smolensk.ru": 1,
"sm\u00f8la.no": 1,
"sn.cn": 1,
"snaase.no": 1,
"snasa.no": 1,
"snillfjord.no": 1,
"snoasa.no": 1,
"snz.ru": 1,
"sn\u00e5ase.no": 1,
"sn\u00e5sa.no": 1,
"so.gov.pl": 1,
"so.it": 1,
"sobetsu.hokkaido.jp": 1,
"soc.lk": 1,
"society.museum": 1,
"sodegaura.chiba.jp": 1,
"soeda.fukuoka.jp": 1,
"software.aero": 1,
"sogndal.no": 1,
"sogne.no": 1,
"soja.okayama.jp": 1,
"soka.saitama.jp": 1,
"sokndal.no": 1,
"sola.no": 1,
"sologne.museum": 1,
"solund.no": 1,
"soma.fukushima.jp": 1,
"somna.no": 1,
"sondre-land.no": 1,
"sondrio.it": 1,
"songdalen.no": 1,
"songfest.om": 0,
"soni.nara.jp": 1,
"soo.kagoshima.jp": 1,
"sopot.pl": 1,
"sor-aurdal.no": 1,
"sor-fron.no": 1,
"sor-odal.no": 1,
"sor-varanger.no": 1,
"sorfold.no": 1,
"sorreisa.no": 1,
"sortland.no": 1,
"sorum.no": 1,
"sos.pl": 1,
"sosa.chiba.jp": 1,
"sosnowiec.pl": 1,
"soundandvision.museum": 1,
"southcarolina.museum": 1,
"southwest.museum": 1,
"sowa.ibaraki.jp": 1,
"sp.it": 1,
"space-to-rent.com": 1,
"space.museum": 1,
"spb.ru": 1,
"spjelkavik.no": 1,
"sport.hu": 1,
"spy.museum": 1,
"spydeberg.no": 1,
"square.museum": 1,
"sr.gov.pl": 1,
"sr.it": 1,
"srv.br": 1,
"ss.it": 1,
"sshn.se": 1,
"st.no": 1,
"stadt.museum": 1,
"stalbans.museum": 1,
"stalowa-wola.pl": 1,
"stange.no": 1,
"starachowice.pl": 1,
"stargard.pl": 1,
"starnberg.museum": 1,
"starostwo.gov.pl": 1,
"stat.no": 1,
"state.museum": 1,
"statecouncil.om": 0,
"stateofdelaware.museum": 1,
"stathelle.no": 1,
"station.museum": 1,
"stavanger.no": 1,
"stavern.no": 1,
"stavropol.ru": 1,
"steam.museum": 1,
"steiermark.museum": 1,
"steigen.no": 1,
"steinkjer.no": 1,
"stjohn.museum": 1,
"stjordal.no": 1,
"stjordalshalsen.no": 1,
"stj\u00f8rdal.no": 1,
"stj\u00f8rdalshalsen.no": 1,
"stockholm.museum": 1,
"stokke.no": 1,
"stor-elvdal.no": 1,
"stord.no": 1,
"stordal.no": 1,
"store.bb": 1,
"store.nf": 1,
"store.ro": 1,
"store.st": 1,
"storfjord.no": 1,
"stpetersburg.museum": 1,
"strand.no": 1,
"stranda.no": 1,
"stryn.no": 1,
"student.aero": 1,
"stuff-4-sale.org": 1,
"stuff-4-sale.us": 1,
"stuttgart.museum": 1,
"stv.ru": 1,
"sue.fukuoka.jp": 1,
"suedtirol.it": 1,
"suginami.tokyo.jp": 1,
"sugito.saitama.jp": 1,
"suifu.ibaraki.jp": 1,
"suisse.museum": 1,
"suita.osaka.jp": 1,
"sukagawa.fukushima.jp": 1,
"sukumo.kochi.jp": 1,
"sula.no": 1,
"suldal.no": 1,
"suli.hu": 1,
"sumida.tokyo.jp": 1,
"sumita.iwate.jp": 1,
"sumoto.hyogo.jp": 1,
"sumoto.kumamoto.jp": 1,
"sumy.ua": 1,
"sunagawa.hokkaido.jp": 1,
"sund.no": 1,
"sunndal.no": 1,
"surgeonshall.museum": 1,
"surgut.ru": 1,
"surnadal.no": 1,
"surrey.museum": 1,
"susaki.kochi.jp": 1,
"susono.shizuoka.jp": 1,
"suwa.nagano.jp": 1,
"suwalki.pl": 1,
"suzaka.nagano.jp": 1,
"suzu.ishikawa.jp": 1,
"suzuka.mie.jp": 1,
"sv": 2,
"sv.it": 1,
"svalbard.no": 1,
"sveio.no": 1,
"svelvik.no": 1,
"svizzera.museum": 1,
"sweden.museum": 1,
"swidnica.pl": 1,
"swiebodzin.pl": 1,
"swinoujscie.pl": 1,
"sx.cn": 1,
"sydney.museum": 1,
"sykkylven.no": 1,
"syzran.ru": 1,
"szczecin.pl": 1,
"szczytno.pl": 1,
"szex.hu": 1,
"szkola.pl": 1,
"s\u00e1lat.no": 1,
"s\u00e1l\u00e1t.no": 1,
"s\u00f8gne.no": 1,
"s\u00f8mna.no": 1,
"s\u00f8ndre-land.no": 1,
"s\u00f8r-aurdal.no": 1,
"s\u00f8r-fron.no": 1,
"s\u00f8r-odal.no": 1,
"s\u00f8r-varanger.no": 1,
"s\u00f8rfold.no": 1,
"s\u00f8rreisa.no": 1,
"s\u00f8rum.no": 1,
"t.bg": 1,
"t.se": 1,
"ta.it": 1,
"tabayama.yamanashi.jp": 1,
"tabuse.yamaguchi.jp": 1,
"tachiarai.fukuoka.jp": 1,
"tachikawa.tokyo.jp": 1,
"tadaoka.osaka.jp": 1,
"tado.mie.jp": 1,
"tadotsu.kagawa.jp": 1,
"tagajo.miyagi.jp": 1,
"tagami.niigata.jp": 1,
"tagawa.fukuoka.jp": 1,
"tahara.aichi.jp": 1,
"taiji.wakayama.jp": 1,
"taiki.hokkaido.jp": 1,
"taiki.mie.jp": 1,
"tainai.niigata.jp": 1,
"taira.toyama.jp": 1,
"taishi.hyogo.jp": 1,
"taishi.osaka.jp": 1,
"taishin.fukushima.jp": 1,
"taito.tokyo.jp": 1,
"taiwa.miyagi.jp": 1,
"tajimi.gifu.jp": 1,
"tajiri.osaka.jp": 1,
"taka.hyogo.jp": 1,
"takagi.nagano.jp": 1,
"takahagi.ibaraki.jp": 1,
"takahama.aichi.jp": 1,
"takahama.fukui.jp": 1,
"takaharu.miyazaki.jp": 1,
"takahashi.okayama.jp": 1,
"takahata.yamagata.jp": 1,
"takaishi.osaka.jp": 1,
"takamatsu.kagawa.jp": 1,
"takamori.kumamoto.jp": 1,
"takamori.nagano.jp": 1,
"takanabe.miyazaki.jp": 1,
"takanezawa.tochigi.jp": 1,
"takaoka.toyama.jp": 1,
"takarazuka.hyogo.jp": 1,
"takasago.hyogo.jp": 1,
"takasaki.gunma.jp": 1,
"takashima.shiga.jp": 1,
"takasu.hokkaido.jp": 1,
"takata.fukuoka.jp": 1,
"takatori.nara.jp": 1,
"takatsuki.osaka.jp": 1,
"takatsuki.shiga.jp": 1,
"takayama.gifu.jp": 1,
"takayama.gunma.jp": 1,
"takayama.nagano.jp": 1,
"takazaki.miyazaki.jp": 1,
"takehara.hiroshima.jp": 1,
"taketa.oita.jp": 1,
"taketomi.okinawa.jp": 1,
"taki.mie.jp": 1,
"takikawa.hokkaido.jp": 1,
"takino.hyogo.jp": 1,
"takinoue.hokkaido.jp": 1,
"takizawa.iwate.jp": 1,
"takko.aomori.jp": 1,
"tako.chiba.jp": 1,
"taku.saga.jp": 1,
"tama.tokyo.jp": 1,
"tamakawa.fukushima.jp": 1,
"tamaki.mie.jp": 1,
"tamamura.gunma.jp": 1,
"tamano.okayama.jp": 1,
"tamatsukuri.ibaraki.jp": 1,
"tamayu.shimane.jp": 1,
"tamba.hyogo.jp": 1,
"tambov.ru": 1,
"tana.no": 1,
"tanabe.kyoto.jp": 1,
"tanabe.wakayama.jp": 1,
"tanagura.fukushima.jp": 1,
"tananger.no": 1,
"tank.museum": 1,
"tanohata.iwate.jp": 1,
"tara.saga.jp": 1,
"tarama.okinawa.jp": 1,
"taranto.it": 1,
"targi.pl": 1,
"tarnobrzeg.pl": 1,
"tarui.gifu.jp": 1,
"tarumizu.kagoshima.jp": 1,
"tas.au": 1,
"tas.edu.au": 1,
"tas.gov.au": 1,
"tatarstan.ru": 1,
"tatebayashi.gunma.jp": 1,
"tateshina.nagano.jp": 1,
"tateyama.chiba.jp": 1,
"tateyama.toyama.jp": 1,
"tatsuno.hyogo.jp": 1,
"tatsuno.nagano.jp": 1,
"tawaramoto.nara.jp": 1,
"taxi.aero": 1,
"taxi.br": 1,
"tcm.museum": 1,
"te.it": 1,
"te.ua": 1,
"teaches-yoga.com": 1,
"technology.museum": 1,
"telekommunikation.museum": 1,
"television.museum": 1,
"tempio-olbia.it": 1,
"tempioolbia.it": 1,
"tendo.yamagata.jp": 1,
"tenei.fukushima.jp": 1,
"tenkawa.nara.jp": 1,
"tenri.nara.jp": 1,
"teo.br": 1,
"teramo.it": 1,
"terni.it": 1,
"ternopil.ua": 1,
"teshikaga.hokkaido.jp": 1,
"test.ru": 1,
"test.tj": 1,
"texas.museum": 1,
"textile.museum": 1,
"tgory.pl": 1,
"theater.museum": 1,
"thruhere.net": 1,
"time.museum": 1,
"time.no": 1,
"timekeeping.museum": 1,
"tingvoll.no": 1,
"tinn.no": 1,
"tj.cn": 1,
"tjeldsund.no": 1,
"tjome.no": 1,
"tj\u00f8me.no": 1,
"tm.fr": 1,
"tm.hu": 1,
"tm.km": 1,
"tm.mc": 1,
"tm.mg": 1,
"tm.no": 1,
"tm.pl": 1,
"tm.ro": 1,
"tm.se": 1,
"tmp.br": 1,
"tn.it": 1,
"tn.us": 1,
"to.it": 1,
"toba.mie.jp": 1,
"tobe.ehime.jp": 1,
"tobetsu.hokkaido.jp": 1,
"tobishima.aichi.jp": 1,
"tochigi.jp": 1,
"tochigi.tochigi.jp": 1,
"tochio.niigata.jp": 1,
"toda.saitama.jp": 1,
"toei.aichi.jp": 1,
"toga.toyama.jp": 1,
"togakushi.nagano.jp": 1,
"togane.chiba.jp": 1,
"togitsu.nagasaki.jp": 1,
"togo.aichi.jp": 1,
"togura.nagano.jp": 1,
"tohma.hokkaido.jp": 1,
"tohnosho.chiba.jp": 1,
"toho.fukuoka.jp": 1,
"tokai.aichi.jp": 1,
"tokai.ibaraki.jp": 1,
"tokamachi.niigata.jp": 1,
"tokashiki.okinawa.jp": 1,
"toki.gifu.jp": 1,
"tokigawa.saitama.jp": 1,
"tokke.no": 1,
"tokoname.aichi.jp": 1,
"tokorozawa.saitama.jp": 1,
"tokushima.jp": 1,
"tokushima.tokushima.jp": 1,
"tokuyama.yamaguchi.jp": 1,
"tokyo.jp": 1,
"tolga.no": 1,
"tom.ru": 1,
"tomakomai.hokkaido.jp": 1,
"tomari.hokkaido.jp": 1,
"tome.miyagi.jp": 1,
"tomi.nagano.jp": 1,
"tomigusuku.okinawa.jp": 1,
"tomika.gifu.jp": 1,
"tomioka.gunma.jp": 1,
"tomisato.chiba.jp": 1,
"tomiya.miyagi.jp": 1,
"tomobe.ibaraki.jp": 1,
"tomsk.ru": 1,
"tonaki.okinawa.jp": 1,
"tonami.toyama.jp": 1,
"tondabayashi.osaka.jp": 1,
"tone.ibaraki.jp": 1,
"tono.iwate.jp": 1,
"tonosho.kagawa.jp": 1,
"tonsberg.no": 1,
"toon.ehime.jp": 1,
"topology.museum": 1,
"torahime.shiga.jp": 1,
"toride.ibaraki.jp": 1,
"torino.it": 1,
"torino.museum": 1,
"torsken.no": 1,
"tosa.kochi.jp": 1,
"tosashimizu.kochi.jp": 1,
"toshima.tokyo.jp": 1,
"tosu.saga.jp": 1,
"tottori.jp": 1,
"tottori.tottori.jp": 1,
"touch.museum": 1,
"tourism.pl": 1,
"tourism.tn": 1,
"towada.aomori.jp": 1,
"town.museum": 1,
"toya.hokkaido.jp": 1,
"toyako.hokkaido.jp": 1,
"toyama.jp": 1,
"toyama.toyama.jp": 1,
"toyo.kochi.jp": 1,
"toyoake.aichi.jp": 1,
"toyohashi.aichi.jp": 1,
"toyokawa.aichi.jp": 1,
"toyonaka.osaka.jp": 1,
"toyone.aichi.jp": 1,
"toyono.osaka.jp": 1,
"toyooka.hyogo.jp": 1,
"toyosato.shiga.jp": 1,
"toyota.aichi.jp": 1,
"toyota.yamaguchi.jp": 1,
"toyotomi.hokkaido.jp": 1,
"toyotsu.fukuoka.jp": 1,
"toyoura.hokkaido.jp": 1,
"tozawa.yamagata.jp": 1,
"tozsde.hu": 1,
"tp.it": 1,
"tr": 2,
"tr.it": 1,
"tr.no": 1,
"tra.kp": 1,
"trader.aero": 1,
"trading.aero": 1,
"traeumtgerade.de": 1,
"trainer.aero": 1,
"trana.no": 1,
"tranby.no": 1,
"trani-andria-barletta.it": 1,
"trani-barletta-andria.it": 1,
"traniandriabarletta.it": 1,
"tranibarlettaandria.it": 1,
"tranoy.no": 1,
"transport.museum": 1,
"tran\u00f8y.no": 1,
"trapani.it": 1,
"travel.pl": 1,
"travel.tt": 1,
"trd.br": 1,
"tree.museum": 1,
"trentino.it": 1,
"trento.it": 1,
"treviso.it": 1,
"trieste.it": 1,
"troandin.no": 1,
"trogstad.no": 1,
"trolley.museum": 1,
"tromsa.no": 1,
"tromso.no": 1,
"troms\u00f8.no": 1,
"trondheim.no": 1,
"trust.museum": 1,
"trustee.museum": 1,
"trysil.no": 1,
"tr\u00e6na.no": 1,
"tr\u00f8gstad.no": 1,
"ts.it": 1,
"tsaritsyn.ru": 1,
"tsk.ru": 1,
"tsu.mie.jp": 1,
"tsubame.niigata.jp": 1,
"tsubata.ishikawa.jp": 1,
"tsubetsu.hokkaido.jp": 1,
"tsuchiura.ibaraki.jp": 1,
"tsuga.tochigi.jp": 1,
"tsugaru.aomori.jp": 1,
"tsuiki.fukuoka.jp": 1,
"tsukigata.hokkaido.jp": 1,
"tsukiyono.gunma.jp": 1,
"tsukuba.ibaraki.jp": 1,
"tsukui.kanagawa.jp": 1,
"tsukumi.oita.jp": 1,
"tsumagoi.gunma.jp": 1,
"tsunan.niigata.jp": 1,
"tsuno.kochi.jp": 1,
"tsuno.miyazaki.jp": 1,
"tsuru.yamanashi.jp": 1,
"tsuruga.fukui.jp": 1,
"tsurugashima.saitama.jp": 1,
"tsurugi.ishikawa.jp": 1,
"tsuruoka.yamagata.jp": 1,
"tsuruta.aomori.jp": 1,
"tsushima.aichi.jp": 1,
"tsushima.nagasaki.jp": 1,
"tsuwano.shimane.jp": 1,
"tsuyama.okayama.jp": 1,
"tula.ru": 1,
"tur.br": 1,
"turek.pl": 1,
"turen.tn": 1,
"turin.it": 1,
"turystyka.pl": 1,
"tuva.ru": 1,
"tv.bo": 1,
"tv.br": 1,
"tv.it": 1,
"tv.na": 1,
"tv.sd": 1,
"tvedestrand.no": 1,
"tver.ru": 1,
"tw.cn": 1,
"tx.us": 1,
"tychy.pl": 1,
"tydal.no": 1,
"tynset.no": 1,
"tysfjord.no": 1,
"tysnes.no": 1,
"tysvar.no": 1,
"tysv\u00e6r.no": 1,
"tyumen.ru": 1,
"t\u00f8nsberg.no": 1,
"u.bg": 1,
"u.se": 1,
"uba.ar": 0,
"ube.yamaguchi.jp": 1,
"uchihara.ibaraki.jp": 1,
"uchiko.ehime.jp": 1,
"uchinada.ishikawa.jp": 1,
"uchinomi.kagawa.jp": 1,
"ud.it": 1,
"uda.nara.jp": 1,
"udine.it": 1,
"udm.ru": 1,
"udmurtia.ru": 1,
"udono.mie.jp": 1,
"ueda.nagano.jp": 1,
"ueno.gunma.jp": 1,
"uenohara.yamanashi.jp": 1,
"ug.gov.pl": 1,
"uhren.museum": 1,
"uji.kyoto.jp": 1,
"ujiie.tochigi.jp": 1,
"ujitawara.kyoto.jp": 1,
"uk": 2,
"uk.com": 1,
"uk.net": 1,
"uki.kumamoto.jp": 1,
"ukiha.fukuoka.jp": 1,
"ulan-ude.ru": 1,
"ullensaker.no": 1,
"ullensvang.no": 1,
"ulm.museum": 1,
"ulsan.kr": 1,
"ulvik.no": 1,
"um.gov.pl": 1,
"umaji.kochi.jp": 1,
"umi.fukuoka.jp": 1,
"unazuki.toyama.jp": 1,
"unbi.ba": 1,
"undersea.museum": 1,
"union.aero": 1,
"univ.sn": 1,
"university.museum": 1,
"unjarga.no": 1,
"unj\u00e1rga.no": 1,
"unnan.shimane.jp": 1,
"unsa.ba": 1,
"unzen.nagasaki.jp": 1,
"uonuma.niigata.jp": 1,
"uozu.toyama.jp": 1,
"upow.gov.pl": 1,
"urakawa.hokkaido.jp": 1,
"urasoe.okinawa.jp": 1,
"urausu.hokkaido.jp": 1,
"urawa.saitama.jp": 1,
"urayasu.chiba.jp": 1,
"urbino-pesaro.it": 1,
"urbinopesaro.it": 1,
"ureshino.mie.jp": 1,
"uri.arpa": 1,
"urn.arpa": 1,
"uruma.okinawa.jp": 1,
"uryu.hokkaido.jp": 1,
"us.com": 1,
"us.na": 1,
"us.org": 1,
"usa.museum": 1,
"usa.oita.jp": 1,
"usantiques.museum": 1,
"usarts.museum": 1,
"uscountryestate.museum": 1,
"usculture.museum": 1,
"usdecorativearts.museum": 1,
"usenet.pl": 1,
"usgarden.museum": 1,
"ushiku.ibaraki.jp": 1,
"ushistory.museum": 1,
"ushuaia.museum": 1,
"uslivinghistory.museum": 1,
"ustka.pl": 1,
"usui.fukuoka.jp": 1,
"usuki.oita.jp": 1,
"ut.us": 1,
"utah.museum": 1,
"utashinai.hokkaido.jp": 1,
"utazas.hu": 1,
"utazu.kagawa.jp": 1,
"uto.kumamoto.jp": 1,
"utsira.no": 1,
"utsunomiya.tochigi.jp": 1,
"uvic.museum": 1,
"uw.gov.pl": 1,
"uwajima.ehime.jp": 1,
"uy.com": 1,
"uz.ua": 1,
"uzhgorod.ua": 1,
"v.bg": 1,
"va.it": 1,
"va.no": 1,
"va.us": 1,
"vaapste.no": 1,
"vadso.no": 1,
"vads\u00f8.no": 1,
"vaga.no": 1,
"vagan.no": 1,
"vagsoy.no": 1,
"vaksdal.no": 1,
"valer.hedmark.no": 1,
"valer.ostfold.no": 1,
"valle.no": 1,
"valley.museum": 1,
"vang.no": 1,
"vantaa.museum": 1,
"vanylven.no": 1,
"vardo.no": 1,
"vard\u00f8.no": 1,
"varese.it": 1,
"varggat.no": 1,
"varoy.no": 1,
"vb.it": 1,
"vc.it": 1,
"vdonsk.ru": 1,
"ve.it": 1,
"vefsn.no": 1,
"vega.no": 1,
"vegarshei.no": 1,
"veg\u00e5rshei.no": 1,
"venezia.it": 1,
"venice.it": 1,
"vennesla.no": 1,
"verbania.it": 1,
"vercelli.it": 1,
"verdal.no": 1,
"verona.it": 1,
"verran.no": 1,
"versailles.museum": 1,
"vestby.no": 1,
"vestnes.no": 1,
"vestre-slidre.no": 1,
"vestre-toten.no": 1,
"vestvagoy.no": 1,
"vestv\u00e5g\u00f8y.no": 1,
"vet.br": 1,
"veterinaire.fr": 1,
"veterinaire.km": 1,
"vevelstad.no": 1,
"vf.no": 1,
"vgs.no": 1,
"vi.it": 1,
"vi.us": 1,
"vibo-valentia.it": 1,
"vibovalentia.it": 1,
"vic.au": 1,
"vic.edu.au": 1,
"vic.gov.au": 1,
"vicenza.it": 1,
"video.hu": 1,
"vik.no": 1,
"viking.museum": 1,
"vikna.no": 1,
"village.museum": 1,
"vindafjord.no": 1,
"vinnica.ua": 1,
"vinnytsia.ua": 1,
"virginia.museum": 1,
"virtual.museum": 1,
"virtuel.museum": 1,
"viterbo.it": 1,
"vlaanderen.museum": 1,
"vladikavkaz.ru": 1,
"vladimir.ru": 1,
"vladivostok.ru": 1,
"vlog.br": 1,
"vn.ua": 1,
"voagat.no": 1,
"volda.no": 1,
"volgograd.ru": 1,
"volkenkunde.museum": 1,
"vologda.ru": 1,
"volyn.ua": 1,
"voronezh.ru": 1,
"voss.no": 1,
"vossevangen.no": 1,
"vr.it": 1,
"vrn.ru": 1,
"vs.it": 1,
"vt.it": 1,
"vt.us": 1,
"vv.it": 1,
"vyatka.ru": 1,
"v\u00e1rgg\u00e1t.no": 1,
"v\u00e5gan.no": 1,
"v\u00e5gs\u00f8y.no": 1,
"v\u00e5g\u00e5.no": 1,
"v\u00e5ler.hedmark.no": 1,
"v\u00e5ler.\u00f8stfold.no": 1,
"v\u00e6r\u00f8y.no": 1,
"w.bg": 1,
"w.se": 1,
"wa.au": 1,
"wa.edu.au": 1,
"wa.gov.au": 1,
"wa.us": 1,
"wada.nagano.jp": 1,
"wajiki.tokushima.jp": 1,
"wajima.ishikawa.jp": 1,
"wakasa.fukui.jp": 1,
"wakasa.tottori.jp": 1,
"wakayama.jp": 1,
"wakayama.wakayama.jp": 1,
"wake.okayama.jp": 1,
"wakkanai.hokkaido.jp": 1,
"wakuya.miyagi.jp": 1,
"walbrzych.pl": 1,
"wales.museum": 1,
"wallonie.museum": 1,
"wanouchi.gifu.jp": 1,
"war.museum": 1,
"warabi.saitama.jp": 1,
"warmia.pl": 1,
"warszawa.pl": 1,
"washingtondc.museum": 1,
"wassamu.hokkaido.jp": 1,
"watarai.mie.jp": 1,
"watari.miyagi.jp": 1,
"watch-and-clock.museum": 1,
"watchandclock.museum": 1,
"waw.pl": 1,
"wazuka.kyoto.jp": 1,
"web.co": 1,
"web.do": 1,
"web.id": 1,
"web.lk": 1,
"web.nf": 1,
"web.pk": 1,
"web.tj": 1,
"web.ve": 1,
"webhop.biz": 1,
"webhop.info": 1,
"webhop.net": 1,
"webhop.org": 1,
"wegrow.pl": 1,
"western.museum": 1,
"westfalen.museum": 1,
"whaling.museum": 1,
"wi.us": 1,
"wielun.pl": 1,
"wiki.br": 1,
"wildlife.museum": 1,
"williamsburg.museum": 1,
"windmill.museum": 1,
"wlocl.pl": 1,
"wloclawek.pl": 1,
"wodzislaw.pl": 1,
"wolomin.pl": 1,
"workinggroup.aero": 1,
"works.aero": 1,
"workshop.museum": 1,
"worse-than.tv": 1,
"writesthisblog.com": 1,
"wroc.pl": 1,
"wroclaw.pl": 1,
"ws.na": 1,
"wv.us": 1,
"www.ck": 0,
"www.gt": 0,
"www.ro": 1,
"wy.us": 1,
"x.bg": 1,
"x.se": 1,
"xj.cn": 1,
"xz.cn": 1,
"y.bg": 1,
"y.se": 1,
"yabu.hyogo.jp": 1,
"yabuki.fukushima.jp": 1,
"yachimata.chiba.jp": 1,
"yachiyo.chiba.jp": 1,
"yachiyo.ibaraki.jp": 1,
"yaese.okinawa.jp": 1,
"yahaba.iwate.jp": 1,
"yahiko.niigata.jp": 1,
"yaita.tochigi.jp": 1,
"yaizu.shizuoka.jp": 1,
"yakage.okayama.jp": 1,
"yakumo.hokkaido.jp": 1,
"yakumo.shimane.jp": 1,
"yakutia.ru": 1,
"yalta.ua": 1,
"yamada.fukuoka.jp": 1,
"yamada.iwate.jp": 1,
"yamada.toyama.jp": 1,
"yamaga.kumamoto.jp": 1,
"yamagata.gifu.jp": 1,
"yamagata.ibaraki.jp": 1,
"yamagata.jp": 1,
"yamagata.nagano.jp": 1,
"yamagata.yamagata.jp": 1,
"yamaguchi.jp": 1,
"yamakita.kanagawa.jp": 1,
"yamal.ru": 1,
"yamamoto.miyagi.jp": 1,
"yamanakako.yamanashi.jp": 1,
"yamanashi.jp": 1,
"yamanashi.yamanashi.jp": 1,
"yamanobe.yamagata.jp": 1,
"yamanouchi.nagano.jp": 1,
"yamashina.kyoto.jp": 1,
"yamato.fukushima.jp": 1,
"yamato.kanagawa.jp": 1,
"yamato.kumamoto.jp": 1,
"yamatokoriyama.nara.jp": 1,
"yamatotakada.nara.jp": 1,
"yamatsuri.fukushima.jp": 1,
"yamazoe.nara.jp": 1,
"yame.fukuoka.jp": 1,
"yanagawa.fukuoka.jp": 1,
"yanaizu.fukushima.jp": 1,
"yao.osaka.jp": 1,
"yaotsu.gifu.jp": 1,
"yaroslavl.ru": 1,
"yasaka.nagano.jp": 1,
"yashio.saitama.jp": 1,
"yashiro.hyogo.jp": 1,
"yasu.shiga.jp": 1,
"yasuda.kochi.jp": 1,
"yasugi.shimane.jp": 1,
"yasuoka.nagano.jp": 1,
"yatomi.aichi.jp": 1,
"yatsuka.shimane.jp": 1,
"yatsushiro.kumamoto.jp": 1,
"yawara.ibaraki.jp": 1,
"yawata.kyoto.jp": 1,
"yawatahama.ehime.jp": 1,
"yazu.tottori.jp": 1,
"ye": 2,
"yekaterinburg.ru": 1,
"yk.ca": 1,
"yn.cn": 1,
"yoichi.hokkaido.jp": 1,
"yoita.niigata.jp": 1,
"yoka.hyogo.jp": 1,
"yokaichiba.chiba.jp": 1,
"yokawa.hyogo.jp": 1,
"yokkaichi.mie.jp": 1,
"yokohama.jp": 2,
"yokoshibahikari.chiba.jp": 1,
"yokosuka.kanagawa.jp": 1,
"yokote.akita.jp": 1,
"yokoze.saitama.jp": 1,
"yomitan.okinawa.jp": 1,
"yonabaru.okinawa.jp": 1,
"yonago.tottori.jp": 1,
"yonaguni.okinawa.jp": 1,
"yonezawa.yamagata.jp": 1,
"yono.saitama.jp": 1,
"yorii.saitama.jp": 1,
"york.museum": 1,
"yorkshire.museum": 1,
"yoro.gifu.jp": 1,
"yosemite.museum": 1,
"yoshida.saitama.jp": 1,
"yoshida.shizuoka.jp": 1,
"yoshikawa.saitama.jp": 1,
"yoshimi.saitama.jp": 1,
"yoshino.nara.jp": 1,
"yoshinogari.saga.jp": 1,
"yoshioka.gunma.jp": 1,
"yotsukaido.chiba.jp": 1,
"youth.museum": 1,
"yuasa.wakayama.jp": 1,
"yufu.oita.jp": 1,
"yugawa.fukushima.jp": 1,
"yugawara.kanagawa.jp": 1,
"yuki.ibaraki.jp": 1,
"yukuhashi.fukuoka.jp": 1,
"yura.wakayama.jp": 1,
"yurihonjo.akita.jp": 1,
"yusuhara.kochi.jp": 1,
"yusui.kagoshima.jp": 1,
"yuu.yamaguchi.jp": 1,
"yuza.yamagata.jp": 1,
"yuzawa.niigata.jp": 1,
"yuzhno-sakhalinsk.ru": 1,
"z.bg": 1,
"z.se": 1,
"za": 2,
"za.com": 1,
"za.net": 1,
"za.org": 1,
"zachpomor.pl": 1,
"zagan.pl": 1,
"zakopane.pl": 1,
"zama.kanagawa.jp": 1,
"zamami.okinawa.jp": 1,
"zao.miyagi.jp": 1,
"zaporizhzhe.ua": 1,
"zaporizhzhia.ua": 1,
"zarow.pl": 1,
"zentsuji.kagawa.jp": 1,
"zgora.pl": 1,
"zgorzelec.pl": 1,
"zgrad.ru": 1,
"zhitomir.ua": 1,
"zhytomyr.ua": 1,
"zj.cn": 1,
"zlg.br": 1,
"zm": 2,
"zoological.museum": 1,
"zoology.museum": 1,
"zp.ua": 1,
"zt.ua": 1,
"zushi.kanagawa.jp": 1,
"zw": 2,
"\u00e1k\u014boluokta.no": 1,
"\u00e1laheadju.no": 1,
"\u00e1lt\u00e1.no": 1,
"\u00e5fjord.no": 1,
"\u00e5krehamn.no": 1,
"\u00e5l.no": 1,
"\u00e5lesund.no": 1,
"\u00e5lg\u00e5rd.no": 1,
"\u00e5mli.no": 1,
"\u00e5mot.no": 1,
"\u00e5rdal.no": 1,
"\u00e5s.no": 1,
"\u00e5seral.no": 1,
"\u00e5snes.no": 1,
"\u00f8ksnes.no": 1,
"\u00f8rland.no": 1,
"\u00f8rskog.no": 1,
"\u00f8rsta.no": 1,
"\u00f8stre-toten.no": 1,
"\u00f8vre-eiker.no": 1,
"\u00f8yer.no": 1,
"\u00f8ygarden.no": 1,
"\u00f8ystre-slidre.no": 1,
"\u010d\u00e1hcesuolo.no": 1,
"\u0438\u043a\u043e\u043c.museum": 1,
"\u05d9\u05e8\u05d5\u05e9\u05dc\u05d9\u05dd.museum": 1,
"\u0627\u064a\u0631\u0627\u0646.ir": 1,
"\u0627\u06cc\u0631\u0627\u0646.ir": 1,
"\u4e2a\u4eba.hk": 1,
"\u500b\u4eba.hk": 1,
"\u516c\u53f8.cn": 1,
"\u516c\u53f8.hk": 1,
"\u5546\u696d.tw": 1,
"\u653f\u5e9c.hk": 1,
"\u654e\u80b2.hk": 1,
"\u6559\u80b2.hk": 1,
"\u7b87\u4eba.hk": 1,
"\u7d44\u7e54.hk": 1,
"\u7d44\u7e54.tw": 1,
"\u7d44\u7ec7.hk": 1,
"\u7db2\u7d61.cn": 1,
"\u7db2\u7d61.hk": 1,
"\u7db2\u7edc.hk": 1,
"\u7db2\u8def.tw": 1,
"\u7ec4\u7e54.hk": 1,
"\u7ec4\u7ec7.hk": 1,
"\u7f51\u7d61.hk": 1,
"\u7f51\u7edc.cn": 1,
"\u7f51\u7edc.hk": 1
};
/*!
* Parts of original code from ipv6.js <https://github.com/beaugunderson/javascript-ipv6>
* Copyright 2011 Beau Gunderson
* Available under MIT license <http://mths.be/mit>
*/
var RE_V4 = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|0x[0-9a-f][0-9a-f]?|0[0-7]{3})\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|0x[0-9a-f][0-9a-f]?|0[0-7]{3})$/i;
var RE_V4_HEX = /^0x([0-9a-f]{8})$/i;
var RE_V4_NUMERIC = /^[0-9]+$/;
var RE_V4inV6 = /(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
var RE_BAD_CHARACTERS = /([^0-9a-f:])/i;
var RE_BAD_ADDRESS = /([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]$)/i;
function isIPv4(address)
{
if (RE_V4.test(address))
return true;
if (RE_V4_HEX.test(address))
return true;
if (RE_V4_NUMERIC.test(address))
return true;
return false;
}
function isIPv6(address)
{
var a4addon = 0;
var address4 = address.match(RE_V4inV6);
if (address4)
{
var temp4 = address4[0].split('.');
for (var i = 0; i < 4; i++)
{
if (/^0[0-9]+/.test(temp4[i]))
return false;
}
address = address.replace(RE_V4inV6, '');
if (/[0-9]$/.test(address))
return false;
address = address + temp4.join(':');
a4addon = 2;
}
if (RE_BAD_CHARACTERS.test(address))
return false;
if (RE_BAD_ADDRESS.test(address))
return false;
function count(string, substring)
{
return (string.length - string.replace(new RegExp(substring,"g"), '').length) / substring.length;
}
var halves = count(address, '::');
if (halves == 1 && count(address, ':') <= 6 + 2 + a4addon)
return true;
if (halves == 0 && count(address, ':') == 7 + a4addon)
return true;
return false;
}
/**
* Returns base domain for specified host based on Public Suffix List.
*/
function getBaseDomain(/**String*/ hostname) /**String*/
{
// remove trailing dot(s)
hostname = hostname.replace(/\.+$/, '');
// return IP address untouched
if (isIPv6(hostname) || isIPv4(hostname))
return hostname;
// decode punycode if exists
//if (hostname.indexOf('xn--') >= 0)
//{
// hostname = punycode.toUnicode(hostname);
//}
// search through PSL
var prevDomains = [];
var curDomain = hostname;
var nextDot = curDomain.indexOf('.');
var tld = 0;
while (true)
{
var suffix = publicSuffixes[curDomain];
if (typeof(suffix) != 'undefined')
{
tld = suffix;
break;
}
if (nextDot < 0)
{
tld = 1;
break;
}
prevDomains.push(curDomain.substring(0,nextDot));
curDomain = curDomain.substring(nextDot+1);
nextDot = curDomain.indexOf('.');
}
while (tld > 0 && prevDomains.length > 0)
{
curDomain = prevDomains.pop() + '.' + curDomain;
tld--;
}
return curDomain;
}
/**
* Checks whether a request is third party for the given document, uses
* information from the public suffix list to determine the effective domain
* name for the document.
*/
function isThirdParty(/**String*/ requestHost, /**String*/ documentHost)
{
// Remove trailing dots
requestHost = requestHost.replace(/\.+$/, "");
documentHost = documentHost.replace(/\.+$/, "");
// Extract domain name - leave IP addresses unchanged, otherwise leave only base domain
var documentDomain = getBaseDomain(documentHost);
if (requestHost.length > documentDomain.length)
return (requestHost.substr(requestHost.length - documentDomain.length - 1) != "." + documentDomain);
else
return (requestHost != documentDomain);
}
/**
* Extracts host name from a URL.
*/
function extractHostFromURL(/**String*/ url)
{
if (url && extractHostFromURL._lastURL == url)
return extractHostFromURL._lastDomain;
var host = "";
try
{
host = new URI(url).host;
}
catch (e)
{
// Keep the empty string for invalid URIs.
}
extractHostFromURL._lastURL = url;
extractHostFromURL._lastDomain = host;
return host;
}
/**
* Parses URLs and provides an interface similar to nsIURI in Gecko, see
* https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIURI.
* TODO: Make sure the parsing actually works the same as nsStandardURL.
* @constructor
*/
function URI(/**String*/ spec)
{
this.spec = spec;
this._schemeEnd = spec.indexOf(":");
if (this._schemeEnd < 0)
throw new Error("Invalid URI scheme");
if (spec.substr(this._schemeEnd + 1, 2) != "//")
throw new Error("Unexpected URI structure");
this._hostPortStart = this._schemeEnd + 3;
this._hostPortEnd = spec.indexOf("/", this._hostPortStart);
if (this._hostPortEnd < 0)
throw new Error("Invalid URI host");
var authEnd = spec.indexOf("@", this._hostPortStart);
if (authEnd >= 0 && authEnd < this._hostPortEnd)
this._hostPortStart = authEnd + 1;
this._portStart = -1;
this._hostEnd = spec.indexOf("]", this._hostPortStart + 1);
if (spec[this._hostPortStart] == "[" && this._hostEnd >= 0 && this._hostEnd < this._hostPortEnd)
{
// The host is an IPv6 literal
this._hostStart = this._hostPortStart + 1;
if (spec[this._hostEnd + 1] == ":")
this._portStart = this._hostEnd + 2;
}
else
{
this._hostStart = this._hostPortStart;
this._hostEnd = spec.indexOf(":", this._hostStart);
if (this._hostEnd >= 0 && this._hostEnd < this._hostPortEnd)
this._portStart = this._hostEnd + 1;
else
this._hostEnd = this._hostPortEnd;
}
}
URI.prototype =
{
spec: null,
get scheme()
{
return this.spec.substring(0, this._schemeEnd).toLowerCase();
},
get host()
{
return this.spec.substring(this._hostStart, this._hostEnd);
},
get asciiHost()
{
var host = this.host;
//if (/^[\x00-\x7F]+$/.test(host))
return host;
//else
// return punycode.toASCII(host);
},
get hostPort()
{
return this.spec.substring(this._hostPortStart, this._hostPortEnd);
},
get port()
{
if (this._portStart < 0)
return -1;
else
return parseInt(this.spec.substring(this._portStart, this._hostPortEnd), 10);
},
get path()
{
return this.spec.substring(this._hostPortEnd);
},
get prePath()
{
return this.spec.substring(0, this._hostPortEnd);
}
};
var RuleList = function( parentObj ) {
this._parentObj = parentObj;
// Runtime Rule object storage collection
this._collection = [];
this.createRule = function(rule, options) {
rule += ""; // force rule argument to be a string
// strip leading/trailing whitespace from rule
rule = rule.replace(/\s*$/,''); // rtrim
rule = rule.replace(/^\s*/,''); // ltrim
if(rule === "") {
return { 'id': 0, 'rule': null };
}
var ruleId = Math.floor( Math.random() * 1e15 );
// Sanitize options, if any
options = options || {};
var opts = {
'includeDomains': options.includeDomains || [],
'excludeDomains': options.excludeDomains || [],
'resources': options.resources || 0xFFFFFFFF,
'thirdParty': options.thirdParty !== undefined ? options.thirdParty : null
};
// Process options and append to rule argument
var filterOptions = [];
var includeDomainsStr = "";
var excludeDomainsStr = "";
if(opts.includeDomains && opts.includeDomains.length > 0) {
for(var i = 0, l = opts.includeDomains.length; i < l; i++) {
if(includeDomainsStr.length > 0) includeDomainsStr += "|"; // add domain seperator (pipe)
includeDomainsStr += opts.includeDomains[i];
}
}
if(opts.excludeDomains && opts.excludeDomains.length > 0) {
for(var i = 0, l = opts.excludeDomains.length; i < l; i++) {
if(excludeDomainsStr.length > 0 || includeDomainsStr.length > 0) excludeDomainsStr += "|"; // add domain seperator (pipe)
excludeDomainsStr += "~" + opts.excludeDomains[i];
}
}
if(includeDomainsStr.length > 0 || excludeDomainsStr.length > 0) {
var domainsStr = "domain=" + includeDomainsStr + excludeDomainsStr;
filterOptions.push(domainsStr);
}
if(opts.resources && opts.resources !== 0xFFFFFFFF) {
var typeMap = {
1: "other",
2: "script",
4: "image",
8: "stylesheet",
16: "object",
32: "subdocument",
64: "document",
128: "refresh",
2048: "xmlhttprequest",
4096: "object_subrequest",
16384: "media",
32768: "font"
};
var resourcesListStr = "";
for(var i = 0, l = 31; i < l; i ++) {
if(((opts.resources >> i) % 2 != 0) === true) {
var typeStr = typeMap[ Math.pow(2, i) ];
if(typeStr) {
if(resourcesListStr.length > 0) resourcesListStr += ",";
resourcesListStr += typeStr;
}
}
}
if(resourcesListStr.length > 0) {
filterOptions.push(resourcesListStr);
}
}
if(opts.thirdParty === true) {
filterOptions.push("third-party");
} else if (opts.thirdParty === false) {
filterOptions.push("~third-party");
}
if(filterOptions.length > 0) {
rule += "$";
for(var i = 0, l = filterOptions.length; i < l; i++) {
if(i !== 0) rule += ","; // add filter options seperator (comma)
rule += filterOptions[i];
}
}
return { 'id': ruleId, 'rule': rule };
}
this.addRule = function( ruleObj ) {
// Parse rule to a Filter object
var filter = this._parentObj.Filter.fromText( ruleObj['rule'] );
// Add rule's filter object to AdBlock FilterStorage
this._parentObj.FilterStorage.addFilter(filter);
// Add rule to current RuleList collection
this._collection.push({
'id': ruleObj['id'],
'filter': filter
});
}
this.removeRule = function( ruleId ) {
for(var i = 0, l = this._collection.length; i < l; i++) {
if( this._collection[i]['id'] && this._collection[i]['id'] == ruleId ) {
// Remove rule's filter object from AdBlock FilterStorage
this._parentObj.FilterStorage.removeFilter(this._collection[i]['filter']);
// Remove rule from current RuleList collection
this._collection.splice(i);
break;
}
}
}
};
RuleList.prototype.add = function( rule, options ) {
var ruleObj = this.createRule(rule, options);
if(ruleObj['rule'] !== null) {
this.addRule(ruleObj);
}
return ruleObj['id'];
};
RuleList.prototype.remove = function( ruleId ) {
this.removeRule( ruleId );
};
var BlockRuleList = function( parentObj ) {
RuleList.call(this, parentObj);
};
BlockRuleList.prototype = Object.create( RuleList.prototype );
var AllowRuleList = function( parentObj ) {
RuleList.call(this, parentObj);
};
AllowRuleList.prototype = Object.create( RuleList.prototype );
AllowRuleList.prototype.add = function( rule, options ) {
var ruleObj = this.createRule(rule, options);
if(ruleObj['rule'] !== null) {
// Add exclude pattern to rule (@@)
ruleObj['rule'] = "@@" + ruleObj['rule'];
this.addRule(ruleObj);
}
return ruleObj['id'];
};
var UrlFilterManager = function() {
OEventTarget.call(this);
// Add rule list management stubs
this.block = new BlockRuleList( this );
this.allow = new AllowRuleList( this );
// event queue manager
this.eventQueue = {
/*
tabId: [
'ready': false,
'contentblocked': [ { eventdetails }, { eventDetails }, { eventDetails } ],
'contentunblocked': [ { eventdetails }, { eventDetails }, { eventDetails } ],
'contentallowed': [ { eventdetails }, { eventDetails }, { eventDetails } ]
],
...
*/
};
// https://github.com/adblockplus/adblockpluschrome/blob/master/background.js
with(require("filterClasses")) {
this.Filter = Filter;
this.RegExpFilter = RegExpFilter;
this.BlockingFilter = BlockingFilter;
this.WhitelistFilter = WhitelistFilter;
}
with(require("subscriptionClasses")) {
this.Subscription = Subscription;
//this.DownloadableSubscription = DownloadableSubscription;
}
this.FilterStorage = require("filterStorage").FilterStorage;
this.defaultMatcher = require("matcher").defaultMatcher;
// https://github.com/adblockplus/adblockpluschrome/blob/master/webrequest.js
var self = this;
var frames = {};
function recordFrame(tabId, frameId, parentFrameId, frameUrl) {
if (!(tabId in frames))
frames[tabId] = {};
frames[tabId][frameId] = {url: frameUrl, parent: parentFrameId};
}
function getFrameData(tabId, frameId) {
if (tabId in frames && frameId in frames[tabId])
return frames[tabId][frameId];
else if (frameId > 0 && tabId in frames && 0 in frames[tabId])
{
// We don't know anything about javascript: or data: frames, use top frame
return frames[tabId][0];
}
return null;
}
function getFrameUrl(tabId, frameId) {
var frameData = getFrameData(tabId, frameId);
return (frameData ? frameData.url : null);
}
function forgetTab(tabId) {
delete frames[tabId];
}
function checkRequest(type, tabId, url, frameId) {
if (isFrameWhitelisted(tabId, frameId))
return false;
var documentUrl = getFrameUrl(tabId, frameId);
if (!documentUrl)
return false;
var requestHost = extractHostFromURL(url);
var documentHost = extractHostFromURL(documentUrl);
var thirdParty = isThirdParty(requestHost, documentHost);
return self.defaultMatcher.matchesAny(url, type, documentHost, thirdParty);
}
function isFrameWhitelisted(tabId, frameId, type) {
var parent = frameId;
var parentData = getFrameData(tabId, parent);
while (parentData)
{
var frame = parent;
var frameData = parentData;
parent = frameData.parent;
parentData = getFrameData(tabId, parent);
var frameUrl = frameData.url;
var parentUrl = (parentData ? parentData.url : frameUrl);
if ("keyException" in frameData || isWhitelisted(frameUrl, parentUrl, type))
return true;
}
return false;
}
function isWhitelisted(url, parentUrl, type)
{
// Ignore fragment identifier
var index = url.indexOf("#");
if (index >= 0)
url = url.substring(0, index);
var result = self.defaultMatcher.matchesAny(url, type || "DOCUMENT", extractHostFromURL(parentUrl || url), false);
return (result instanceof self.WhitelistFilter ? result : null);
}
// Parse a single web request url and decide whether we should block or not
function onBeforeRequest(details) {
if (details.tabId == -1) {
return {};
}
var type = details.type;
if (type == "main_frame" || type == "sub_frame") {
recordFrame(details.tabId, details.frameId, details.parentFrameId, details.url);
}
// Type names match Mozilla's with main_frame and sub_frame being the only exceptions.
if (type == "sub_frame") {
type = "SUBDOCUMENT";
} else if (type == "main_frame") {
type = "DOCUMENT";
} else {
type = (type + "").toUpperCase();
}
var frame = (type != "SUBDOCUMENT" ? details.frameId : details.parentFrameId);
var filter = checkRequest(type, details.tabId, details.url, frame);
if (filter instanceof self.BlockingFilter) {
var msgData = {
"action": "___O_urlfilter_contentblocked",
"data": {
// send enough data so that we can fire the event in the injected script
"url": details.url
}
};
// Broadcast contentblocked event control message (i.e. beginning with '___O_')
// towards the tab matching the details.tabId value
// (but delay it until the content script is loaded!)
if(self.eventQueue[details.tabId] !== undefined && self.eventQueue[details.tabId].ready === true) {
// tab is already online so send contentblocked messages
chrome.tabs.sendMessage(
details.tabId,
msgData,
function() {}
);
} else {
// queue up this event
if(self.eventQueue[details.tabId] === undefined) {
self.eventQueue[details.tabId] = { 'ready': false, 'contentblocked': [], 'contentunblocked': [], 'contentallowed': [] };
}
self.eventQueue[details.tabId]['contentblocked'].push( msgData );
}
return { cancel: true };
} else if (filter instanceof self.WhitelistFilter) {
var msgData = {
"action": "___O_urlfilter_contentunblocked",
"data": {
// send enough data so that we can fire the event in the injected script
"url": details.url
}
};
// Broadcast contentblocked event control message (i.e. beginning with '___O_')
// towards the tab matching the details.tabId value
// (but delay it until the content script is loaded!)
if(self.eventQueue[details.tabId] !== undefined && self.eventQueue[details.tabId].ready === true) {
// tab is already online so send contentblocked messages
chrome.tabs.sendMessage(
details.tabId,
msgData,
function() {}
);
} else {
// queue up this event
if(self.eventQueue[details.tabId] === undefined) {
self.eventQueue[details.tabId] = { 'ready': false, 'contentblocked': [], 'contentunblocked': [], 'contentallowed': [] };
}
self.eventQueue[details.tabId]['contentunblocked'].push( msgData );
}
return {};
} else {
var msgData = {
"action": "___O_urlfilter_contentallowed",
"data": {
// send enough data so that we can fire the event in the injected script
"url": details.url
}
};
// Broadcast contentblocked event control message (i.e. beginning with '___O_')
// towards the tab matching the details.tabId value
// (but delay it until the content script is loaded!)
if(self.eventQueue[details.tabId] !== undefined && self.eventQueue[details.tabId].ready === true) {
// tab is already online so send contentblocked messages
chrome.tabs.sendMessage(
details.tabId,
msgData,
function() {}
);
} else {
// queue up this event
if(self.eventQueue[details.tabId] === undefined) {
self.eventQueue[details.tabId] = { 'ready': false, 'contentblocked': [], 'contentunblocked': [], 'contentallowed': [] };
}
self.eventQueue[details.tabId]['contentallowed'].push( msgData );
}
return {};
}
}
// Listen for webRequest beforeRequest events and block
// if a rule matches in the associated block RuleList
chrome.webRequest.onBeforeRequest.addListener(onBeforeRequest, { urls: [ "http://*/*", "https://*/*" ] }, [ "blocking" ]);
// Wait for tab to add event listeners for urlfilter and then drain queued up events to that tab
OEX.addEventListener('controlmessage', function( msg ) {
if( !msg.data || !msg.data.action ) {
return;
}
if( msg.data.action != '___O_urlfilter_DRAINQUEUE' || !msg.data.eventType ) {
return;
}
// Drain queued events belonging to this tab
var tabId = msg.source.tabId;
if( self.eventQueue[tabId] !== undefined ) {
self.eventQueue[tabId].ready = true; // set to resolved (true)
var eventQueue = self.eventQueue[tabId][ msg.data.eventType ];
for(var i = 0, l = eventQueue.length; i < l; i++) {
msg.source.postMessage(eventQueue[i]);
}
self.eventQueue[tabId][ msg.data.eventType ] = []; // reset event queue
}
});
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
switch(changeInfo.status) {
case 'loading':
// kill previous events queue
if(self.eventQueue[tabId] === undefined) {
self.eventQueue[tabId] = { 'ready': false, 'contentblocked': [], 'contentunblocked': [], 'contentallowed': [] };
} else {
self.eventQueue[tabId].ready = false;
}
break;
case 'complete':
if(self.eventQueue[tabId] !== undefined && self.eventQueue[tabId].ready !== undefined ) {
self.eventQueue[tabId].ready = true;
}
break;
}
});
};
UrlFilterManager.prototype = Object.create( OEventTarget.prototype );
// URL Filter Resource Types (bit-mask values)
UrlFilterManager.prototype.RESOURCE_OTHER = 0x00000001; // 1
UrlFilterManager.prototype.RESOURCE_SCRIPT = 0x00000002; // 2
UrlFilterManager.prototype.RESOURCE_IMAGE = 0x00000004; // 4
UrlFilterManager.prototype.RESOURCE_STYLESHEET = 0x00000008; // 8
UrlFilterManager.prototype.RESOURCE_OBJECT = 0x00000010; // 16
UrlFilterManager.prototype.RESOURCE_SUBDOCUMENT = 0x00000020; // 32
UrlFilterManager.prototype.RESOURCE_DOCUMENT = 0x00000040; // 64
UrlFilterManager.prototype.RESOURCE_REFRESH = 0x00000080; // 128
UrlFilterManager.prototype.RESOURCE_XMLHTTPREQUEST = 0x00000800; // 2048
UrlFilterManager.prototype.RESOURCE_OBJECT_SUBREQUEST = 0x00001000; // 4096
UrlFilterManager.prototype.RESOURCE_MEDIA = 0x00004000; // 16384
UrlFilterManager.prototype.RESOURCE_FONT = 0x00008000; // 32768
if(manifest && manifest.permissions && manifest.permissions.indexOf('webRequest') != -1 && manifest.permissions.indexOf('webRequestBlocking') != -1 ) {
OEX.urlfilter = OEX.urlfilter || new UrlFilterManager();
}
if (isOEX) {
isReady = true;
// Make scripts also work in Opera <= version 12
opera.isReady = function(fn) {
fn.call(global);
// Run delayed events (if any)
for(var i = 0, l = _delayedExecuteEvents.length; i < l; i++) {
var o = _delayedExecuteEvents[i];
o.target[o.methodName].apply(o.target, o.args);
}
_delayedExecuteEvents = [];
};
} else {
opr.isReady = (function() {
var fns = {
"isready": [],
"readystatechange": [],
"domcontentloaded": [],
"load": []
};
var hasFired_DOMContentLoaded = false,
hasFired_Load = false;
// If we already missed DOMContentLoaded or Load events firing, record that now...
if(global.document.readyState === "interactive") {
hasFired_DOMContentLoaded = true;
}
if(global.document.readyState === "complete") {
hasFired_DOMContentLoaded = true;
hasFired_Load = true;
}
// ...otherwise catch DOMContentLoaded and Load events when they happen and set the same flag.
global.document.addEventListener("DOMContentLoaded", function handle_DomContentLoaded() {
hasFired_DOMContentLoaded = true;
global.document.removeEventListener("DOMContentLoaded", handle_DomContentLoaded, true);
}, true);
global.addEventListener("load", function handle_Load() {
hasFired_Load = true;
global.removeEventListener("load", handle_Load, true);
}, true);
// Catch and fire readystatechange events when they happen
global.document.addEventListener("readystatechange", function(event) {
event.stopImmediatePropagation();
event.stopPropagation();
if( global.document.readyState !== 'interactive' && global.document.readyState !== 'complete' ) {
fireEvent('readystatechange', global.document);
} else {
global.document.readyState = 'loading';
}
}, true);
// Take over handling of document.readyState via our own load bootstrap code below
var _readyState = (hasFired_DOMContentLoaded || hasFired_Load) ? global.document.readyState : "loading";
global.document.__defineSetter__('readyState', function(val) { _readyState = val; });
global.document.__defineGetter__('readyState', function() { return _readyState; });
function interceptAddEventListener(target, _name) {
var _target = target.addEventListener;
// Replace addEventListener for given target
target.addEventListener = function(name, fn, usecapture) {
name = name + ""; // force event name to type string
if (name.toLowerCase() === _name.toLowerCase()) {
if (fn === undefined || fn === null ||
Object.prototype.toString.call(fn) !== "[object Function]") {
return;
}
if ((name.toLowerCase() === 'domcontentloaded' && !hasFired_DOMContentLoaded) ||
(name.toLowerCase() === 'load' && !hasFired_Load) ||
!isReady) {
fns[_name.toLowerCase()].push(fn);
} else {
fn.call(global);
}
} else {
// call standard addEventListener method on target
_target.call(target, name, fn, usecapture);
}
};
// Replace target.on[_name] with custom setter function
target.__defineSetter__("on" + _name.toLowerCase(), function( fn ) {
// call code block just created above...
target.addEventListener(_name.toLowerCase(), fn, false);
});
}
interceptAddEventListener(global, 'load');
interceptAddEventListener(global.document, 'domcontentloaded');
interceptAddEventListener(global, 'domcontentloaded'); // handled bubbled DOMContentLoaded events
interceptAddEventListener(global.document, 'readystatechange');
function fireEvent(name, target, props) {
var evtName = name.toLowerCase();
// Roll a standard object as the Event since we really need
// to set the target + other unsettable properties on the
// isReady events
var evt = props || {};
evt.type = name;
if(!evt.target) evt.target = target || global;
if(!evt.currentTarget) evt.currentTarget = evt.target;
if(!evt.srcElement) evt.srcElement = evt.target;
if(evt.bubbles !== true) evt.bubbles = false;
if(evt.cancelable !== true) evt.cancelable = false;
if(!evt.timeStamp) evt.timeStamp = 0;
for (var i = 0, len = fns[evtName].length; i < len; i++) {
fns[evtName][i].call(target, evt);
}
}
function ready() {
global.setTimeout(function() {
if (isReady) {
return;
}
// Handle queued opera 'isReady' event functions
for (var i = 0, len = fns['isready'].length; i < len; i++) {
fns['isready'][i].call(global);
}
fns['isready'] = []; // clear
var domContentLoadedTimeoutOverride = new Date().getTime() + 120000;
// Synthesize and fire the document domcontentloaded event
(function fireDOMContentLoaded() {
var currentTime = new Date().getTime();
// Check for hadFired_Load in case we missed DOMContentLoaded
// event, in which case, we syntesize DOMContentLoaded here
// (always synthesized in Chromium Content Scripts)
if (hasFired_DOMContentLoaded || hasFired_Load || currentTime >= domContentLoadedTimeoutOverride) {
global.document.readyState = 'interactive';
fireEvent('readystatechange', global.document);
fireEvent('domcontentloaded', global.document, { bubbles: true }); // indicate that event bubbles
if(currentTime >= domContentLoadedTimeoutOverride) {
console.warn('document.domcontentloaded event fired on check timeout');
}
var loadTimeoutOverride = new Date().getTime() + 120000;
// Synthesize and fire the window load event
// after the domcontentloaded event has been
// fired
(function fireLoad() {
var currentTime = new Date().getTime();
if (hasFired_Load || currentTime >= loadTimeoutOverride) {
global.document.readyState = 'complete';
fireEvent('readystatechange', global.document);
fireEvent('load', global);
if(currentTime >= loadTimeoutOverride) {
console.warn('window.load event fired on check timeout');
}
// Run delayed events (if any)
for(var i = 0, l = _delayedExecuteEvents.length; i < l; i++) {
var o = _delayedExecuteEvents[i];
o.target[o.methodName].apply(o.target, o.args);
}
_delayedExecuteEvents = [];
} else {
global.setTimeout(function() {
fireLoad();
}, 50);
}
})();
} else {
global.setTimeout(function() {
fireDOMContentLoaded();
}, 50);
}
})();
isReady = true;
}, 0);
}
var holdTimeoutOverride = new Date().getTime() + 240000;
(function holdReady() {
var currentTime = new Date().getTime();
if (currentTime >= holdTimeoutOverride) {
// All scripts now ready to be executed: TIMEOUT override
console.warn('opera.isReady check timed out');
hasFired_Load = true; // override
ready();
return;
}
for (var i in deferredComponentsLoadStatus) {
if (deferredComponentsLoadStatus[i] !== true) {
// spin the loop until everything is working
// or we receive a timeout override (handled
// in next loop, above)
global.setTimeout(function() {
holdReady();
}, 20);
return;
}
}
// All scripts now ready to be executed
ready();
})();
return function(fn) {
// if the Library is already ready,
// execute the function immediately.
// otherwise, queue it up until isReady
if (isReady) {
fn.call(global);
} else {
fns['isready'].push(fn);
}
}
})();
}
// Make API available on the window DOM object
if(!isOEX) {
global.opera = opr;
}
opera.isReady(function() {
// Rewrite in-line event handlers (eg. <input ... onclick=""> for a sub-set of common standard events)
document.addEventListener('DOMContentLoaded', function(e) {
var selectors = ['load', 'beforeunload', 'unload', 'click', 'dblclick', 'mouseover', 'mousemove',
'mousedown', 'mouseup', 'mouseout', 'keydown', 'keypress', 'keyup', 'blur', 'focus'];
for(var i = 0, l = selectors.length; i < l; i++) {
var els = document.querySelectorAll('[on' + selectors[i] + ']');
for(var j = 0, k = els.length; j < k; j++) {
var fn = new Function('e', els[j].getAttribute('on' + selectors[i]));
var target = els[j];
if(selectors[i].indexOf('load') > -1 && els[j] === document.body) {
target = window;
}
els[j].removeAttribute('on' + selectors[i]);
target.addEventListener(selectors[i], fn, true);
}
}
}, false);
});
})( window ); | 1974kpkpkp/operaextensions.js | tests/WindowsTabs/BrowserTabManager/020/operaextensions_background.js | JavaScript | mit | 391,085 |
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var i;"undefined"!=typeof window?i=window:"undefined"!=typeof global?i=global:"undefined"!=typeof self&&(i=self),i.YASQE=e()}}(function(){var e;return function i(e,r,n){function o(s,a){if(!r[s]){if(!e[s]){var p="function"==typeof require&&require;if(!a&&p)return p(s,!0);if(t)return t(s,!0);var E=new Error("Cannot find module '"+s+"'");throw E.code="MODULE_NOT_FOUND",E}var l=r[s]={exports:{}};e[s][0].call(l.exports,function(i){var r=e[s][1][i];return o(r?r:i)},l,l.exports,i,e,r,n)}return r[s].exports}for(var t="function"==typeof require&&require,s=0;s<n.length;s++)o(n[s]);return o}({1:[function(e,i){"use strict";window.console=window.console||{log:function(){}};var r=function(){try{return e("jquery")}catch(i){return window.jQuery}}(),n=function(){try{return e("codemirror")}catch(i){return window.CodeMirror}}(),o=(e("./sparql.js"),e("./utils.js")),t=e("yasgui-utils"),s=e("./imgs.js");e("../lib/deparam.js"),e("codemirror/addon/hint/show-hint.js"),e("codemirror/addon/search/searchcursor.js"),e("codemirror/addon/edit/matchbrackets.js"),e("codemirror/addon/runmode/runmode.js"),e("codemirror/addon/display/fullscreen.js"),e("../lib/flint.js");var a=i.exports=function(e,i){i=p(i);var r=E(n(e,i));return c(r),r},p=function(e){var i=r.extend(!0,{},a.defaults,e);return i},E=function(i){return r(i.getWrapperElement()).addClass("yasqe"),i.autocompleters=e("./autocompleters/autocompleterBase.js")(i),i.options.autocompleters&&i.options.autocompleters.forEach(function(e){a.Autocompleters[e]&&i.autocompleters.init(e,a.Autocompleters[e])}),i.getCompleteToken=function(r,n){return e("./tokenUtils.js").getCompleteToken(i,r,n)},i.getPreviousNonWsToken=function(r,n){return e("./tokenUtils.js").getPreviousNonWsToken(i,r,n)},i.getNextNonWsToken=function(r,n){return e("./tokenUtils.js").getNextNonWsToken(i,r,n)},i.query=function(e){a.executeQuery(i,e)},i.getPrefixesFromQuery=function(){return e("./prefixUtils.js").getPrefixesFromQuery(i)},i.addPrefixes=function(r){return e("./prefixUtils.js").addPrefixes(i,r)},i.removePrefixes=function(r){return e("./prefixUtils.js").removePrefixes(i,r)},i.getQueryType=function(){return i.queryType},i.getQueryMode=function(){var e=i.getQueryType();return"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e?"update":"query"},i.setCheckSyntaxErrors=function(e){i.options.syntaxErrorCheck=e,I(i)},i.enableCompleter=function(e){l(i.options,e),YASQE.Autocompleters[e]&&i.autocompleters.init(e,YASQE.Autocompleters[e])},i.disableCompleter=function(e){u(i.options,e)},i},l=function(e,i){e.autocompleters||(e.autocompleters=[]),e.autocompleters.push(i)},u=function(e,i){if("object"==typeof e.autocompleters){var n=r.inArray(i,e.autocompleters);n>=0&&(e.autocompleters.splice(n,1),u(e,i))}},c=function(e){var i=o.getPersistencyId(e,e.options.persistent);if(i){var n=t.storage.get(i);n&&e.setValue(n)}if(a.drawButtons(e),e.on("blur",function(e){a.storeQuery(e)}),e.on("change",function(e){I(e),a.updateQueryButton(e),a.positionButtons(e)}),e.on("cursorActivity",function(e){d(e)}),e.prevQueryValid=!1,I(e),a.positionButtons(e),e.options.consumeShareLink){var s=r.deparam(window.location.search.substring(1));e.options.consumeShareLink(e,s)}},d=function(e){e.cursor=r(".CodeMirror-cursor"),e.buttons&&e.buttons.is(":visible")&&e.cursor.length>0&&(o.elementsOverlap(e.cursor,e.buttons)?e.buttons.find("svg").attr("opacity","0.2"):e.buttons.find("svg").attr("opacity","1.0"))},N=null,I=function(i,n){i.queryValid=!0,N&&(N(),N=null),i.clearGutter("gutterErrorBar");for(var o=null,a=0;a<i.lineCount();++a){var p=!1;i.prevQueryValid||(p=!0);var E=i.getTokenAt({line:a,ch:i.getLine(a).length},p),o=E.state;if(i.queryType=o.queryType,0==o.OK){if(!i.options.syntaxErrorCheck)return void r(i.getWrapperElement).find(".sp-error").css("color","black");var l=t.svg.getElement(s.warning,{width:"15px",height:"15px"});o.possibleCurrent&&o.possibleCurrent.length>0&&(l.style.zIndex="99999999",e("./tooltip")(i,l,function(){var e=[];return o.possibleCurrent.forEach(function(i){e.push("<strong style='text-decoration:underline'>"+r("<div/>").text(i).html()+"</strong>")}),"This line is invalid. Expected: "+e.join(", ")})),l.style.marginTop="2px",l.style.marginLeft="2px",i.setGutterMarker(a,"gutterErrorBar",l),N=function(){i.markText({line:a,ch:o.errorStartPos},{line:a,ch:o.errorEndPos},"sp-error")},i.queryValid=!1;break}}if(i.prevQueryValid=i.queryValid,n&&null!=o&&void 0!=o.stack){var u=o.stack,c=o.stack.length;c>1?i.queryValid=!1:1==c&&"solutionModifier"!=u[0]&&"?limitOffsetClauses"!=u[0]&&"?offsetClause"!=u[0]&&(i.queryValid=!1)}};r.extend(a,n),a.Autocompleters={},a.registerAutocompleter=function(e,i){a.Autocompleters[e]=i,l(a.defaults,e)},a.autoComplete=function(e){e.autocompleters.autoComplete(!1)},a.registerAutocompleter("prefixes",e("./autocompleters/prefixes.js")),a.registerAutocompleter("properties",e("./autocompleters/properties.js")),a.registerAutocompleter("classes",e("./autocompleters/classes.js")),a.registerAutocompleter("variables",e("./autocompleters/variables.js")),a.positionButtons=function(e){var i=r(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),n=0;i.is(":visible")&&(n=i.outerWidth()),e.buttons.is(":visible")&&e.buttons.css("right",n)},a.createShareLink=function(e){return{query:e.getValue()}},a.consumeShareLink=function(e,i){i.query&&e.setValue(i.query)},a.drawButtons=function(e){if(e.buttons=r("<div class='yasqe_buttons'></div>").appendTo(r(e.getWrapperElement())),e.options.createShareLink){var i=r(t.svg.getElement(s.share,{width:"30px",height:"30px"}));i.click(function(n){n.stopPropagation();var o=r("<div class='yasqe_sharePopup'></div>").appendTo(e.buttons);r("html").click(function(){o&&o.remove()}),o.click(function(e){e.stopPropagation()});var t=r("<textarea></textarea>").val(location.protocol+"//"+location.host+location.pathname+"?"+r.param(e.options.createShareLink(e)));t.focus(function(){var e=r(this);e.select(),e.mouseup(function(){return e.unbind("mouseup"),!1})}),o.empty().append(t);var s=i.position();o.css("top",s.top+i.outerHeight()+"px").css("left",s.left+i.outerWidth()-o.outerWidth()+"px")}).addClass("yasqe_share").attr("title","Share your query").appendTo(e.buttons)}if(e.options.sparql.showQueryButton){var n=40,o=40;r("<div class='yasqe_queryButton'></div>").click(function(){r(this).hasClass("query_busy")?(e.xhr&&e.xhr.abort(),a.updateQueryButton(e)):e.query()}).height(n).width(o).appendTo(e.buttons),a.updateQueryButton(e)}};var x={busy:"loader",valid:"query",error:"queryInvalid"};a.updateQueryButton=function(e,i){var n=r(e.getWrapperElement()).find(".yasqe_queryButton");0!=n.length&&(i||(i="valid",e.queryValid===!1&&(i="error")),i==e.queryStatus||"busy"!=i&&"valid"!=i&&"error"!=i||(n.empty().removeClass(function(e,i){return i.split(" ").filter(function(e){return 0==e.indexOf("query_")}).join(" ")}).addClass("query_"+i).append(t.svg.getElement(s[x[i]],{width:"100%",height:"100%"})),e.queryStatus=i))},a.fromTextArea=function(e,i){i=p(i);var r=E(n.fromTextArea(e,i));return c(r),r},a.storeQuery=function(e){var i=o.getPersistencyId(e,e.options.persistent);i&&t.storage.set(i,e.getValue(),"month")},a.commentLines=function(e){for(var i=e.getCursor(!0).line,r=e.getCursor(!1).line,n=Math.min(i,r),o=Math.max(i,r),t=!0,s=n;o>=s;s++){var a=e.getLine(s);if(0==a.length||"#"!=a.substring(0,1)){t=!1;break}}for(var s=n;o>=s;s++)t?e.replaceRange("",{line:s,ch:0},{line:s,ch:1}):e.replaceRange("#",{line:s,ch:0})},a.copyLineUp=function(e){var i=e.getCursor(),r=e.lineCount();e.replaceRange("\n",{line:r-1,ch:e.getLine(r-1).length});for(var n=r;n>i.line;n--){var o=e.getLine(n-1);e.replaceRange(o,{line:n,ch:0},{line:n,ch:e.getLine(n).length})}},a.copyLineDown=function(e){a.copyLineUp(e);var i=e.getCursor();i.line++,e.setCursor(i)},a.doAutoFormat=function(e){if(e.somethingSelected()){var i={line:e.getCursor(!1).line,ch:e.getSelection().length};L(e,e.getCursor(!0),i)}else{var r=e.lineCount(),n=e.getTextArea().value.length;L(e,{line:0,ch:0},{line:r,ch:n})}};var L=function(e,i,r){var n=e.indexFromPos(i),o=e.indexFromPos(r),t=T(e.getValue(),n,o);e.operation(function(){e.replaceRange(t,i,r);for(var o=e.posFromIndex(n).line,s=e.posFromIndex(n+t.length).line,a=o;s>=a;a++)e.indentLine(a,"smart")})},T=function(e,i,o){e=e.substring(i,o);var t=[["keyword","ws","prefixed","ws","uri"],["keyword","ws","uri"]],s=["{",".",";"],a=["}"],p=function(e){for(var i=0;i<t.length;i++)if(u.valueOf().toString()==t[i].valueOf().toString())return 1;for(var i=0;i<s.length;i++)if(e==s[i])return 1;for(var i=0;i<a.length;i++)if(""!=r.trim(l)&&e==a[i])return-1;return 0},E="",l="",u=[];return n.runMode(e,"sparql11",function(e,i){u.push(i);var r=p(e,i);0!=r?(1==r?(E+=e+"\n",l=""):(E+="\n"+e,l=e),u=[]):(l+=e,E+=e),1==u.length&&"sp-ws"==u[0]&&(u=[])}),r.trim(E.replace(/\n\s*\n/g,"\n"))};e("./sparql.js").use(a),e("./defaults.js").use(a),a.version={CodeMirror:n.version,YASQE:e("../package.json").version,jquery:r.fn.jquery,"yasgui-utils":t.version}},{"../lib/deparam.js":2,"../lib/flint.js":3,"../package.json":15,"./autocompleters/autocompleterBase.js":16,"./autocompleters/classes.js":17,"./autocompleters/prefixes.js":18,"./autocompleters/properties.js":19,"./autocompleters/variables.js":21,"./defaults.js":22,"./imgs.js":23,"./prefixUtils.js":24,"./sparql.js":25,"./tokenUtils.js":26,"./tooltip":27,"./utils.js":28,codemirror:void 0,"codemirror/addon/display/fullscreen.js":5,"codemirror/addon/edit/matchbrackets.js":6,"codemirror/addon/hint/show-hint.js":7,"codemirror/addon/runmode/runmode.js":8,"codemirror/addon/search/searchcursor.js":9,jquery:void 0,"yasgui-utils":12}],2:[function(e){var i=function(){try{return e("jquery")}catch(i){return window.jQuery}}();i.deparam=function(e,r){var n={},o={"true":!0,"false":!1,"null":null};return i.each(e.replace(/\+/g," ").split("&"),function(e,t){var s,a=t.split("="),p=decodeURIComponent(a[0]),E=n,l=0,u=p.split("]["),c=u.length-1;if(/\[/.test(u[0])&&/\]$/.test(u[c])?(u[c]=u[c].replace(/\]$/,""),u=u.shift().split("[").concat(u),c=u.length-1):c=0,2===a.length)if(s=decodeURIComponent(a[1]),r&&(s=s&&!isNaN(s)?+s:"undefined"===s?void 0:void 0!==o[s]?o[s]:s),c)for(;c>=l;l++)p=""===u[l]?E.length:u[l],E=E[p]=c>l?E[p]||(u[l+1]&&isNaN(u[l+1])?{}:[]):s;else i.isArray(n[p])?n[p].push(s):n[p]=void 0!==n[p]?[n[p],s]:s;else p&&(n[p]=r?void 0:"")}),n}},{jquery:void 0}],3:[function(i,r,n){!function(o){"object"==typeof n&&"object"==typeof r?o(function(){try{return i("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["codemirror"],o):o(CodeMirror)}(function(e){"use strict";e.defineMode("sparql11",function(e){function i(){var e,i,r="<[^<>\"'|{}^\\\x00- ]*>",n="[A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]",o=n+"|_",t="("+o+"|-|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])",s="("+o+"|[0-9])("+o+"|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])*",a="\\?"+s,p="\\$"+s,l="("+n+")((("+t+")|\\.)*("+t+"))?",u="[0-9A-Fa-f]",c="(%"+u+u+")",d="(\\\\[_~\\.\\-!\\$&'\\(\\)\\*\\+,;=/\\?#@%])",N="("+c+"|"+d+")";"sparql11"==E?(e="("+o+"|:|[0-9]|"+N+")(("+t+"|\\.|:|"+N+")*("+t+"|:|"+N+"))?",i="_:("+o+"|[0-9])(("+t+"|\\.)*"+t+")?"):(e="("+o+"|[0-9])((("+t+")|\\.)*("+t+"))?",i="_:"+e);var I="("+l+")?:",x=I+e,L="@[a-zA-Z]+(-[a-zA-Z0-9]+)*",T="[eE][\\+-]?[0-9]+",m="[0-9]+",A="(([0-9]+\\.[0-9]*)|(\\.[0-9]+))",S="(([0-9]+\\.[0-9]*"+T+")|(\\.[0-9]+"+T+")|([0-9]+"+T+"))",R="\\+"+m,g="\\+"+A,v="\\+"+S,C="-"+m,h="-"+A,O="-"+S,P="\\\\[tbnrf\\\\\"']",y="'(([^\\x27\\x5C\\x0A\\x0D])|"+P+")*'",f='"(([^\\x22\\x5C\\x0A\\x0D])|'+P+')*"',_="'''(('|'')?([^'\\\\]|"+P+"))*'''",D='"""(("|"")?([^"\\\\]|'+P+'))*"""',G="[\\x20\\x09\\x0D\\x0A]",b="#([^\\n\\r]*[\\n\\r]|[^\\n\\r]*$)",M="("+G+"|("+b+"))*",U="\\("+M+"\\)",V="\\["+M+"\\]",B={terminal:[{name:"WS",regex:new RegExp("^"+G+"+"),style:"ws"},{name:"COMMENT",regex:new RegExp("^"+b),style:"comment"},{name:"IRI_REF",regex:new RegExp("^"+r),style:"variable-3"},{name:"VAR1",regex:new RegExp("^"+a),style:"atom"},{name:"VAR2",regex:new RegExp("^"+p),style:"atom"},{name:"LANGTAG",regex:new RegExp("^"+L),style:"meta"},{name:"DOUBLE",regex:new RegExp("^"+S),style:"number"},{name:"DECIMAL",regex:new RegExp("^"+A),style:"number"},{name:"INTEGER",regex:new RegExp("^"+m),style:"number"},{name:"DOUBLE_POSITIVE",regex:new RegExp("^"+v),style:"number"},{name:"DECIMAL_POSITIVE",regex:new RegExp("^"+g),style:"number"},{name:"INTEGER_POSITIVE",regex:new RegExp("^"+R),style:"number"},{name:"DOUBLE_NEGATIVE",regex:new RegExp("^"+O),style:"number"},{name:"DECIMAL_NEGATIVE",regex:new RegExp("^"+h),style:"number"},{name:"INTEGER_NEGATIVE",regex:new RegExp("^"+C),style:"number"},{name:"STRING_LITERAL_LONG1",regex:new RegExp("^"+_),style:"string"},{name:"STRING_LITERAL_LONG2",regex:new RegExp("^"+D),style:"string"},{name:"STRING_LITERAL1",regex:new RegExp("^"+y),style:"string"},{name:"STRING_LITERAL2",regex:new RegExp("^"+f),style:"string"},{name:"NIL",regex:new RegExp("^"+U),style:"punc"},{name:"ANON",regex:new RegExp("^"+V),style:"punc"},{name:"PNAME_LN",regex:new RegExp("^"+x),style:"string-2"},{name:"PNAME_NS",regex:new RegExp("^"+I),style:"string-2"},{name:"BLANK_NODE_LABEL",regex:new RegExp("^"+i),style:"string-2"}]};return B}function r(e){var i=[],r=t[e];if(void 0!=r)for(var n in r)i.push(n.toString());else i.push(e);return i}function n(e,i){function n(){for(var i=null,r=0;r<d.length;++r)if(i=e.match(d[r].regex,!0,!1))return{cat:d[r].name,style:d[r].style,text:i[0]};return(i=e.match(s,!0,!1))?{cat:e.current().toUpperCase(),style:"keyword",text:i[0]}:(i=e.match(a,!0,!1))?{cat:e.current(),style:"punc",text:i[0]}:(i=e.match(/^.[A-Za-z0-9]*/,!0,!1),{cat:"<invalid_token>",style:"error",text:i[0]})}function o(){var r=e.column();i.errorStartPos=r,i.errorEndPos=r+u.text.length}function p(e){null==i.queryType&&("SELECT"==e||"CONSTRUCT"==e||"ASK"==e||"DESCRIBE"==e||"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e)&&(i.queryType=e)}function E(e){"disallowVars"==e?i.allowVars=!1:"allowVars"==e?i.allowVars=!0:"disallowBnodes"==e?i.allowBnodes=!1:"allowBnodes"==e?i.allowBnodes=!0:"storeProperty"==e&&(i.storeProperty=!0)}function l(e){return(i.allowVars||"var"!=e)&&(i.allowBnodes||"blankNode"!=e&&"blankNodePropertyList"!=e&&"blankNodePropertyListPath"!=e)}0==e.pos&&(i.possibleCurrent=i.possibleNext);var u=n();if("<invalid_token>"==u.cat)return 1==i.OK&&(i.OK=!1,o()),i.complete=!1,u.style;if("WS"==u.cat||"COMMENT"==u.cat)return i.possibleCurrent=i.possibleNext,u.style;for(var c,N=!1,I=u.cat;i.stack.length>0&&I&&i.OK&&!N;)if(c=i.stack.pop(),t[c]){var x=t[c][I];if(void 0!=x&&l(c)){for(var L=x.length-1;L>=0;--L)i.stack.push(x[L]);E(c)}else i.OK=!1,i.complete=!1,o(),i.stack.push(c)}else if(c==I){N=!0,p(c);for(var T=!0,m=i.stack.length;m>0;--m){var A=t[i.stack[m-1]];A&&A.$||(T=!1)}i.complete=T,i.storeProperty&&"punc"!=I.cat&&(i.lastProperty=u.text,i.storeProperty=!1)}else i.OK=!1,i.complete=!1,o();return!N&&i.OK&&(i.OK=!1,i.complete=!1,o()),i.possibleCurrent=i.possibleNext,i.possibleNext=r(i.stack[i.stack.length-1]),u.style}function o(i,r){var n=0,o=i.stack.length-1;if(/^[\}\]\)]/.test(r)){for(var t=r.substr(0,1);o>=0;--o)if(i.stack[o]==t){--o;break}}else{var s=N[i.stack[o]];s&&(n+=s,--o)}for(;o>=0;--o){var s=I[i.stack[o]];s&&(n+=s)}return n*e.indentUnit}var t=(e.indentUnit,{"*[&&,valueLogical]":{"&&":["[&&,valueLogical]","*[&&,valueLogical]"],AS:[],")":[],",":[],"||":[],";":[]},"*[,,expression]":{",":["[,,expression]","*[,,expression]"],")":[]},"*[,,objectPath]":{",":["[,,objectPath]","*[,,objectPath]"],".":[],";":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[,,object]":{",":["[,,object]","*[,,object]"],".":[],";":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[/,pathEltOrInverse]":{"/":["[/,pathEltOrInverse]","*[/,pathEltOrInverse]"],"|":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[;,?[or([verbPath,verbSimple]),objectList]]":{";":["[;,?[or([verbPath,verbSimple]),objectList]]","*[;,?[or([verbPath,verbSimple]),objectList]]"],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[;,?[verb,objectList]]":{";":["[;,?[verb,objectList]]","*[;,?[verb,objectList]]"],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[UNION,groupGraphPattern]":{UNION:["[UNION,groupGraphPattern]","*[UNION,groupGraphPattern]"],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[graphPatternNotTriples,?.,?triplesBlock]":{"{":["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":[]},"*[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["[quadsNotTriples,?.,?triplesTemplate]","*[quadsNotTriples,?.,?triplesTemplate]"],"}":[]},"*[|,pathOneInPropertySet]":{"|":["[|,pathOneInPropertySet]","*[|,pathOneInPropertySet]"],")":[]},"*[|,pathSequence]":{"|":["[|,pathSequence]","*[|,pathSequence]"],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[||,conditionalAndExpression]":{"||":["[||,conditionalAndExpression]","*[||,conditionalAndExpression]"],AS:[],")":[],",":[],";":[]},"*dataBlockValue":{UNDEF:["dataBlockValue","*dataBlockValue"],IRI_REF:["dataBlockValue","*dataBlockValue"],TRUE:["dataBlockValue","*dataBlockValue"],FALSE:["dataBlockValue","*dataBlockValue"],PNAME_LN:["dataBlockValue","*dataBlockValue"],PNAME_NS:["dataBlockValue","*dataBlockValue"],STRING_LITERAL1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL2:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG2:["dataBlockValue","*dataBlockValue"],INTEGER:["dataBlockValue","*dataBlockValue"],DECIMAL:["dataBlockValue","*dataBlockValue"],DOUBLE:["dataBlockValue","*dataBlockValue"],INTEGER_POSITIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_POSITIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_POSITIVE:["dataBlockValue","*dataBlockValue"],INTEGER_NEGATIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_NEGATIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_NEGATIVE:["dataBlockValue","*dataBlockValue"],"}":[],")":[]},"*datasetClause":{FROM:["datasetClause","*datasetClause"],WHERE:[],"{":[]},"*describeDatasetClause":{FROM:["describeDatasetClause","*describeDatasetClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],VALUES:[],$:[]},"*graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"],")":[]},"*graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"],")":[]},"*groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"*havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"*or([[ (,*dataBlockValue,)],NIL])":{"(":["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],NIL:["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],"}":[]},"*or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],";":[]},"*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"*or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],WHERE:[],"{":[],FROM:[]},"*orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"*prefixDecl":{PREFIX:["prefixDecl","*prefixDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[]},"*usingClause":{USING:["usingClause","*usingClause"],WHERE:[]},"*var":{VAR1:["var","*var"],VAR2:["var","*var"],")":[]},"*varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],FROM:[],VALUES:[],$:[]},"+graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"]},"+graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"]},"+groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"]},"+havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"]},"+or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"]},"+orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"]},"+varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"]},"?.":{".":["."],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?DISTINCT":{DISTINCT:["DISTINCT"],"!":[],"+":[],"-":[],VAR1:[],VAR2:[],"(":[],STR:[],LANG:[],LANGMATCHES:[],DATATYPE:[],BOUND:[],IRI:[],URI:[],BNODE:[],RAND:[],ABS:[],CEIL:[],FLOOR:[],ROUND:[],CONCAT:[],STRLEN:[],UCASE:[],LCASE:[],ENCODE_FOR_URI:[],CONTAINS:[],STRSTARTS:[],STRENDS:[],STRBEFORE:[],STRAFTER:[],YEAR:[],MONTH:[],DAY:[],HOURS:[],MINUTES:[],SECONDS:[],TIMEZONE:[],TZ:[],NOW:[],UUID:[],STRUUID:[],MD5:[],SHA1:[],SHA256:[],SHA384:[],SHA512:[],COALESCE:[],IF:[],STRLANG:[],STRDT:[],SAMETERM:[],ISIRI:[],ISURI:[],ISBLANK:[],ISLITERAL:[],ISNUMERIC:[],TRUE:[],FALSE:[],COUNT:[],SUM:[],MIN:[],MAX:[],AVG:[],SAMPLE:[],GROUP_CONCAT:[],SUBSTR:[],REPLACE:[],REGEX:[],EXISTS:[],NOT:[],IRI_REF:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],PNAME_LN:[],PNAME_NS:[],"*":[]},"?GRAPH":{GRAPH:["GRAPH"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT":{SILENT:["SILENT"],VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_1":{SILENT:["SILENT"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_2":{SILENT:["SILENT"],GRAPH:[],DEFAULT:[],NAMED:[],ALL:[]},"?SILENT_3":{SILENT:["SILENT"],GRAPH:[]},"?SILENT_4":{SILENT:["SILENT"],DEFAULT:[],GRAPH:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?WHERE":{WHERE:["WHERE"],"{":[]},"?[,,expression]":{",":["[,,expression]"],")":[]},"?[.,?constructTriples]":{".":["[.,?constructTriples]"],"}":[]},"?[.,?triplesBlock]":{".":["[.,?triplesBlock]"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[.,?triplesTemplate]":{".":["[.,?triplesTemplate]"],"}":[],GRAPH:[]},"?[;,SEPARATOR,=,string]":{";":["[;,SEPARATOR,=,string]"],")":[]},"?[;,update]":{";":["[;,update]"],$:[]},"?[AS,var]":{AS:["[AS,var]"],")":[]},"?[INTO,graphRef]":{INTO:["[INTO,graphRef]"],";":[],$:[]},"?[or([verbPath,verbSimple]),objectList]":{VAR1:["[or([verbPath,verbSimple]),objectList]"],VAR2:["[or([verbPath,verbSimple]),objectList]"],"^":["[or([verbPath,verbSimple]),objectList]"],a:["[or([verbPath,verbSimple]),objectList]"],"!":["[or([verbPath,verbSimple]),objectList]"],"(":["[or([verbPath,verbSimple]),objectList]"],IRI_REF:["[or([verbPath,verbSimple]),objectList]"],PNAME_LN:["[or([verbPath,verbSimple]),objectList]"],PNAME_NS:["[or([verbPath,verbSimple]),objectList]"],";":[],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],"^":["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],IRI_REF:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_LN:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_NS:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],")":[]},"?[update1,?[;,update]]":{INSERT:["[update1,?[;,update]]"],DELETE:["[update1,?[;,update]]"],LOAD:["[update1,?[;,update]]"],CLEAR:["[update1,?[;,update]]"],DROP:["[update1,?[;,update]]"],ADD:["[update1,?[;,update]]"],MOVE:["[update1,?[;,update]]"],COPY:["[update1,?[;,update]]"],CREATE:["[update1,?[;,update]]"],WITH:["[update1,?[;,update]]"],$:[]},"?[verb,objectList]":{a:["[verb,objectList]"],VAR1:["[verb,objectList]"],VAR2:["[verb,objectList]"],IRI_REF:["[verb,objectList]"],PNAME_LN:["[verb,objectList]"],PNAME_NS:["[verb,objectList]"],";":[],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?argList":{NIL:["argList"],"(":["argList"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],"*":[],"/":[],";":[]},"?baseDecl":{BASE:["baseDecl"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[],PREFIX:[]},"?constructTriples":{VAR1:["constructTriples"],VAR2:["constructTriples"],NIL:["constructTriples"],"(":["constructTriples"],"[":["constructTriples"],IRI_REF:["constructTriples"],TRUE:["constructTriples"],FALSE:["constructTriples"],BLANK_NODE_LABEL:["constructTriples"],ANON:["constructTriples"],PNAME_LN:["constructTriples"],PNAME_NS:["constructTriples"],STRING_LITERAL1:["constructTriples"],STRING_LITERAL2:["constructTriples"],STRING_LITERAL_LONG1:["constructTriples"],STRING_LITERAL_LONG2:["constructTriples"],INTEGER:["constructTriples"],DECIMAL:["constructTriples"],DOUBLE:["constructTriples"],INTEGER_POSITIVE:["constructTriples"],DECIMAL_POSITIVE:["constructTriples"],DOUBLE_POSITIVE:["constructTriples"],INTEGER_NEGATIVE:["constructTriples"],DECIMAL_NEGATIVE:["constructTriples"],DOUBLE_NEGATIVE:["constructTriples"],"}":[]},"?groupClause":{GROUP:["groupClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"?havingClause":{HAVING:["havingClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"?insertClause":{INSERT:["insertClause"],WHERE:[],USING:[]},"?limitClause":{LIMIT:["limitClause"],VALUES:[],$:[],"}":[]},"?limitOffsetClauses":{LIMIT:["limitOffsetClauses"],OFFSET:["limitOffsetClauses"],VALUES:[],$:[],"}":[]},"?offsetClause":{OFFSET:["offsetClause"],VALUES:[],$:[],"}":[]},"?or([DISTINCT,REDUCED])":{DISTINCT:["or([DISTINCT,REDUCED])"],REDUCED:["or([DISTINCT,REDUCED])"],"*":[],"(":[],VAR1:[],VAR2:[]},"?or([LANGTAG,[^^,iriRef]])":{LANGTAG:["or([LANGTAG,[^^,iriRef]])"],"^^":["or([LANGTAG,[^^,iriRef]])"],UNDEF:[],IRI_REF:[],TRUE:[],FALSE:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],a:[],VAR1:[],VAR2:[],"^":[],"!":[],"(":[],".":[],";":[],",":[],AS:[],")":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],"*":[],"/":[],"}":[],"[":[],NIL:[],BLANK_NODE_LABEL:[],ANON:[],"]":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])"],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"!=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IN:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AS:[],")":[],",":[],"||":[],"&&":[],";":[]},"?orderClause":{ORDER:["orderClause"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"?pathMod":{"*":["pathMod"],"?":["pathMod"],"+":["pathMod"],"{":["pathMod"],"|":[],"/":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"?triplesBlock":{VAR1:["triplesBlock"],VAR2:["triplesBlock"],NIL:["triplesBlock"],"(":["triplesBlock"],"[":["triplesBlock"],IRI_REF:["triplesBlock"],TRUE:["triplesBlock"],FALSE:["triplesBlock"],BLANK_NODE_LABEL:["triplesBlock"],ANON:["triplesBlock"],PNAME_LN:["triplesBlock"],PNAME_NS:["triplesBlock"],STRING_LITERAL1:["triplesBlock"],STRING_LITERAL2:["triplesBlock"],STRING_LITERAL_LONG1:["triplesBlock"],STRING_LITERAL_LONG2:["triplesBlock"],INTEGER:["triplesBlock"],DECIMAL:["triplesBlock"],DOUBLE:["triplesBlock"],INTEGER_POSITIVE:["triplesBlock"],DECIMAL_POSITIVE:["triplesBlock"],DOUBLE_POSITIVE:["triplesBlock"],INTEGER_NEGATIVE:["triplesBlock"],DECIMAL_NEGATIVE:["triplesBlock"],DOUBLE_NEGATIVE:["triplesBlock"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?triplesTemplate":{VAR1:["triplesTemplate"],VAR2:["triplesTemplate"],NIL:["triplesTemplate"],"(":["triplesTemplate"],"[":["triplesTemplate"],IRI_REF:["triplesTemplate"],TRUE:["triplesTemplate"],FALSE:["triplesTemplate"],BLANK_NODE_LABEL:["triplesTemplate"],ANON:["triplesTemplate"],PNAME_LN:["triplesTemplate"],PNAME_NS:["triplesTemplate"],STRING_LITERAL1:["triplesTemplate"],STRING_LITERAL2:["triplesTemplate"],STRING_LITERAL_LONG1:["triplesTemplate"],STRING_LITERAL_LONG2:["triplesTemplate"],INTEGER:["triplesTemplate"],DECIMAL:["triplesTemplate"],DOUBLE:["triplesTemplate"],INTEGER_POSITIVE:["triplesTemplate"],DECIMAL_POSITIVE:["triplesTemplate"],DOUBLE_POSITIVE:["triplesTemplate"],INTEGER_NEGATIVE:["triplesTemplate"],DECIMAL_NEGATIVE:["triplesTemplate"],DOUBLE_NEGATIVE:["triplesTemplate"],"}":[],GRAPH:[]},"?whereClause":{WHERE:["whereClause"],"{":["whereClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],VALUES:[],$:[]},"[ (,*dataBlockValue,)]":{"(":["(","*dataBlockValue",")"]},"[ (,*var,)]":{"(":["(","*var",")"]},"[ (,expression,)]":{"(":["(","expression",")"]},"[ (,expression,AS,var,)]":{"(":["(","expression","AS","var",")"]},"[!=,numericExpression]":{"!=":["!=","numericExpression"]},"[&&,valueLogical]":{"&&":["&&","valueLogical"]},"[*,unaryExpression]":{"*":["*","unaryExpression"]},"[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]":{WHERE:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"],FROM:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"]},"[+,multiplicativeExpression]":{"+":["+","multiplicativeExpression"]},"[,,expression]":{",":[",","expression"]},"[,,integer,}]":{",":[",","integer","}"]},"[,,objectPath]":{",":[",","objectPath"]},"[,,object]":{",":[",","object"]},"[,,or([},[integer,}]])]":{",":[",","or([},[integer,}]])"]},"[-,multiplicativeExpression]":{"-":["-","multiplicativeExpression"]},"[.,?constructTriples]":{".":[".","?constructTriples"]},"[.,?triplesBlock]":{".":[".","?triplesBlock"]},"[.,?triplesTemplate]":{".":[".","?triplesTemplate"]},"[/,pathEltOrInverse]":{"/":["/","pathEltOrInverse"]},"[/,unaryExpression]":{"/":["/","unaryExpression"]},"[;,?[or([verbPath,verbSimple]),objectList]]":{";":[";","?[or([verbPath,verbSimple]),objectList]"]},"[;,?[verb,objectList]]":{";":[";","?[verb,objectList]"]},"[;,SEPARATOR,=,string]":{";":[";","SEPARATOR","=","string"]},"[;,update]":{";":[";","update"]},"[<,numericExpression]":{"<":["<","numericExpression"]},"[<=,numericExpression]":{"<=":["<=","numericExpression"]},"[=,numericExpression]":{"=":["=","numericExpression"]},"[>,numericExpression]":{">":[">","numericExpression"]},"[>=,numericExpression]":{">=":[">=","numericExpression"]},"[AS,var]":{AS:["AS","var"]},"[IN,expressionList]":{IN:["IN","expressionList"]},"[INTO,graphRef]":{INTO:["INTO","graphRef"]},"[NAMED,iriRef]":{NAMED:["NAMED","iriRef"]},"[NOT,IN,expressionList]":{NOT:["NOT","IN","expressionList"]},"[UNION,groupGraphPattern]":{UNION:["UNION","groupGraphPattern"]},"[^^,iriRef]":{"^^":["^^","iriRef"]},"[constructTemplate,*datasetClause,whereClause,solutionModifier]":{"{":["constructTemplate","*datasetClause","whereClause","solutionModifier"]},"[deleteClause,?insertClause]":{DELETE:["deleteClause","?insertClause"]},"[graphPatternNotTriples,?.,?triplesBlock]":{"{":["graphPatternNotTriples","?.","?triplesBlock"],OPTIONAL:["graphPatternNotTriples","?.","?triplesBlock"],MINUS:["graphPatternNotTriples","?.","?triplesBlock"],GRAPH:["graphPatternNotTriples","?.","?triplesBlock"],SERVICE:["graphPatternNotTriples","?.","?triplesBlock"],FILTER:["graphPatternNotTriples","?.","?triplesBlock"],BIND:["graphPatternNotTriples","?.","?triplesBlock"],VALUES:["graphPatternNotTriples","?.","?triplesBlock"]},"[integer,or([[,,or([},[integer,}]])],}])]":{INTEGER:["integer","or([[,,or([},[integer,}]])],}])"]},"[integer,}]":{INTEGER:["integer","}"]},"[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]":{INTEGER_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"]},"[or([verbPath,verbSimple]),objectList]":{VAR1:["or([verbPath,verbSimple])","objectList"],VAR2:["or([verbPath,verbSimple])","objectList"],"^":["or([verbPath,verbSimple])","objectList"],a:["or([verbPath,verbSimple])","objectList"],"!":["or([verbPath,verbSimple])","objectList"],"(":["or([verbPath,verbSimple])","objectList"],IRI_REF:["or([verbPath,verbSimple])","objectList"],PNAME_LN:["or([verbPath,verbSimple])","objectList"],PNAME_NS:["or([verbPath,verbSimple])","objectList"]},"[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],"^":["pathOneInPropertySet","*[|,pathOneInPropertySet]"],IRI_REF:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_LN:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_NS:["pathOneInPropertySet","*[|,pathOneInPropertySet]"]},"[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["quadsNotTriples","?.","?triplesTemplate"]},"[update1,?[;,update]]":{INSERT:["update1","?[;,update]"],DELETE:["update1","?[;,update]"],LOAD:["update1","?[;,update]"],CLEAR:["update1","?[;,update]"],DROP:["update1","?[;,update]"],ADD:["update1","?[;,update]"],MOVE:["update1","?[;,update]"],COPY:["update1","?[;,update]"],CREATE:["update1","?[;,update]"],WITH:["update1","?[;,update]"]},"[verb,objectList]":{a:["verb","objectList"],VAR1:["verb","objectList"],VAR2:["verb","objectList"],IRI_REF:["verb","objectList"],PNAME_LN:["verb","objectList"],PNAME_NS:["verb","objectList"]},"[|,pathOneInPropertySet]":{"|":["|","pathOneInPropertySet"]},"[|,pathSequence]":{"|":["|","pathSequence"]},"[||,conditionalAndExpression]":{"||":["||","conditionalAndExpression"]},add:{ADD:["ADD","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},additiveExpression:{"!":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"+":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"(":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANGMATCHES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DATATYPE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BOUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BNODE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],RAND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ABS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CEIL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FLOOR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ROUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLEN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ENCODE_FOR_URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONTAINS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRSTARTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRENDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRBEFORE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRAFTER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],YEAR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MONTH:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DAY:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],HOURS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MINUTES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SECONDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TIMEZONE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TZ:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOW:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRUUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MD5:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA256:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA384:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA512:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COALESCE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRDT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMETERM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISIRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISURI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISBLANK:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISLITERAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISNUMERIC:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TRUE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FALSE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COUNT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MIN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MAX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AVG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMPLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],GROUP_CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUBSTR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REPLACE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REGEX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],EXISTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI_REF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_LN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_NS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"]},aggregate:{COUNT:["COUNT","(","?DISTINCT","or([*,expression])",")"],SUM:["SUM","(","?DISTINCT","expression",")"],MIN:["MIN","(","?DISTINCT","expression",")"],MAX:["MAX","(","?DISTINCT","expression",")"],AVG:["AVG","(","?DISTINCT","expression",")"],SAMPLE:["SAMPLE","(","?DISTINCT","expression",")"],GROUP_CONCAT:["GROUP_CONCAT","(","?DISTINCT","expression","?[;,SEPARATOR,=,string]",")"]},allowBnodes:{"}":[]},allowVars:{"}":[]},argList:{NIL:["NIL"],"(":["(","?DISTINCT","expression","*[,,expression]",")"]},askQuery:{ASK:["ASK","*datasetClause","whereClause","solutionModifier"]},baseDecl:{BASE:["BASE","IRI_REF"]},bind:{BIND:["BIND","(","expression","AS","var",")"]},blankNode:{BLANK_NODE_LABEL:["BLANK_NODE_LABEL"],ANON:["ANON"]},blankNodePropertyList:{"[":["[","propertyListNotEmpty","]"]},blankNodePropertyListPath:{"[":["[","propertyListPathNotEmpty","]"]},booleanLiteral:{TRUE:["TRUE"],FALSE:["FALSE"]},brackettedExpression:{"(":["(","expression",")"]},builtInCall:{STR:["STR","(","expression",")"],LANG:["LANG","(","expression",")"],LANGMATCHES:["LANGMATCHES","(","expression",",","expression",")"],DATATYPE:["DATATYPE","(","expression",")"],BOUND:["BOUND","(","var",")"],IRI:["IRI","(","expression",")"],URI:["URI","(","expression",")"],BNODE:["BNODE","or([[ (,expression,)],NIL])"],RAND:["RAND","NIL"],ABS:["ABS","(","expression",")"],CEIL:["CEIL","(","expression",")"],FLOOR:["FLOOR","(","expression",")"],ROUND:["ROUND","(","expression",")"],CONCAT:["CONCAT","expressionList"],SUBSTR:["substringExpression"],STRLEN:["STRLEN","(","expression",")"],REPLACE:["strReplaceExpression"],UCASE:["UCASE","(","expression",")"],LCASE:["LCASE","(","expression",")"],ENCODE_FOR_URI:["ENCODE_FOR_URI","(","expression",")"],CONTAINS:["CONTAINS","(","expression",",","expression",")"],STRSTARTS:["STRSTARTS","(","expression",",","expression",")"],STRENDS:["STRENDS","(","expression",",","expression",")"],STRBEFORE:["STRBEFORE","(","expression",",","expression",")"],STRAFTER:["STRAFTER","(","expression",",","expression",")"],YEAR:["YEAR","(","expression",")"],MONTH:["MONTH","(","expression",")"],DAY:["DAY","(","expression",")"],HOURS:["HOURS","(","expression",")"],MINUTES:["MINUTES","(","expression",")"],SECONDS:["SECONDS","(","expression",")"],TIMEZONE:["TIMEZONE","(","expression",")"],TZ:["TZ","(","expression",")"],NOW:["NOW","NIL"],UUID:["UUID","NIL"],STRUUID:["STRUUID","NIL"],MD5:["MD5","(","expression",")"],SHA1:["SHA1","(","expression",")"],SHA256:["SHA256","(","expression",")"],SHA384:["SHA384","(","expression",")"],SHA512:["SHA512","(","expression",")"],COALESCE:["COALESCE","expressionList"],IF:["IF","(","expression",",","expression",",","expression",")"],STRLANG:["STRLANG","(","expression",",","expression",")"],STRDT:["STRDT","(","expression",",","expression",")"],SAMETERM:["SAMETERM","(","expression",",","expression",")"],ISIRI:["ISIRI","(","expression",")"],ISURI:["ISURI","(","expression",")"],ISBLANK:["ISBLANK","(","expression",")"],ISLITERAL:["ISLITERAL","(","expression",")"],ISNUMERIC:["ISNUMERIC","(","expression",")"],REGEX:["regexExpression"],EXISTS:["existsFunc"],NOT:["notExistsFunc"]},clear:{CLEAR:["CLEAR","?SILENT_2","graphRefAll"]},collection:{"(":["(","+graphNode",")"]},collectionPath:{"(":["(","+graphNodePath",")"]},conditionalAndExpression:{"!":["valueLogical","*[&&,valueLogical]"],"+":["valueLogical","*[&&,valueLogical]"],"-":["valueLogical","*[&&,valueLogical]"],VAR1:["valueLogical","*[&&,valueLogical]"],VAR2:["valueLogical","*[&&,valueLogical]"],"(":["valueLogical","*[&&,valueLogical]"],STR:["valueLogical","*[&&,valueLogical]"],LANG:["valueLogical","*[&&,valueLogical]"],LANGMATCHES:["valueLogical","*[&&,valueLogical]"],DATATYPE:["valueLogical","*[&&,valueLogical]"],BOUND:["valueLogical","*[&&,valueLogical]"],IRI:["valueLogical","*[&&,valueLogical]"],URI:["valueLogical","*[&&,valueLogical]"],BNODE:["valueLogical","*[&&,valueLogical]"],RAND:["valueLogical","*[&&,valueLogical]"],ABS:["valueLogical","*[&&,valueLogical]"],CEIL:["valueLogical","*[&&,valueLogical]"],FLOOR:["valueLogical","*[&&,valueLogical]"],ROUND:["valueLogical","*[&&,valueLogical]"],CONCAT:["valueLogical","*[&&,valueLogical]"],STRLEN:["valueLogical","*[&&,valueLogical]"],UCASE:["valueLogical","*[&&,valueLogical]"],LCASE:["valueLogical","*[&&,valueLogical]"],ENCODE_FOR_URI:["valueLogical","*[&&,valueLogical]"],CONTAINS:["valueLogical","*[&&,valueLogical]"],STRSTARTS:["valueLogical","*[&&,valueLogical]"],STRENDS:["valueLogical","*[&&,valueLogical]"],STRBEFORE:["valueLogical","*[&&,valueLogical]"],STRAFTER:["valueLogical","*[&&,valueLogical]"],YEAR:["valueLogical","*[&&,valueLogical]"],MONTH:["valueLogical","*[&&,valueLogical]"],DAY:["valueLogical","*[&&,valueLogical]"],HOURS:["valueLogical","*[&&,valueLogical]"],MINUTES:["valueLogical","*[&&,valueLogical]"],SECONDS:["valueLogical","*[&&,valueLogical]"],TIMEZONE:["valueLogical","*[&&,valueLogical]"],TZ:["valueLogical","*[&&,valueLogical]"],NOW:["valueLogical","*[&&,valueLogical]"],UUID:["valueLogical","*[&&,valueLogical]"],STRUUID:["valueLogical","*[&&,valueLogical]"],MD5:["valueLogical","*[&&,valueLogical]"],SHA1:["valueLogical","*[&&,valueLogical]"],SHA256:["valueLogical","*[&&,valueLogical]"],SHA384:["valueLogical","*[&&,valueLogical]"],SHA512:["valueLogical","*[&&,valueLogical]"],COALESCE:["valueLogical","*[&&,valueLogical]"],IF:["valueLogical","*[&&,valueLogical]"],STRLANG:["valueLogical","*[&&,valueLogical]"],STRDT:["valueLogical","*[&&,valueLogical]"],SAMETERM:["valueLogical","*[&&,valueLogical]"],ISIRI:["valueLogical","*[&&,valueLogical]"],ISURI:["valueLogical","*[&&,valueLogical]"],ISBLANK:["valueLogical","*[&&,valueLogical]"],ISLITERAL:["valueLogical","*[&&,valueLogical]"],ISNUMERIC:["valueLogical","*[&&,valueLogical]"],TRUE:["valueLogical","*[&&,valueLogical]"],FALSE:["valueLogical","*[&&,valueLogical]"],COUNT:["valueLogical","*[&&,valueLogical]"],SUM:["valueLogical","*[&&,valueLogical]"],MIN:["valueLogical","*[&&,valueLogical]"],MAX:["valueLogical","*[&&,valueLogical]"],AVG:["valueLogical","*[&&,valueLogical]"],SAMPLE:["valueLogical","*[&&,valueLogical]"],GROUP_CONCAT:["valueLogical","*[&&,valueLogical]"],SUBSTR:["valueLogical","*[&&,valueLogical]"],REPLACE:["valueLogical","*[&&,valueLogical]"],REGEX:["valueLogical","*[&&,valueLogical]"],EXISTS:["valueLogical","*[&&,valueLogical]"],NOT:["valueLogical","*[&&,valueLogical]"],IRI_REF:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL2:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG2:["valueLogical","*[&&,valueLogical]"],INTEGER:["valueLogical","*[&&,valueLogical]"],DECIMAL:["valueLogical","*[&&,valueLogical]"],DOUBLE:["valueLogical","*[&&,valueLogical]"],INTEGER_POSITIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_POSITIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_POSITIVE:["valueLogical","*[&&,valueLogical]"],INTEGER_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_NEGATIVE:["valueLogical","*[&&,valueLogical]"],PNAME_LN:["valueLogical","*[&&,valueLogical]"],PNAME_NS:["valueLogical","*[&&,valueLogical]"]},conditionalOrExpression:{"!":["conditionalAndExpression","*[||,conditionalAndExpression]"],"+":["conditionalAndExpression","*[||,conditionalAndExpression]"],"-":["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR1:["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR2:["conditionalAndExpression","*[||,conditionalAndExpression]"],"(":["conditionalAndExpression","*[||,conditionalAndExpression]"],STR:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANGMATCHES:["conditionalAndExpression","*[||,conditionalAndExpression]"],DATATYPE:["conditionalAndExpression","*[||,conditionalAndExpression]"],BOUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],BNODE:["conditionalAndExpression","*[||,conditionalAndExpression]"],RAND:["conditionalAndExpression","*[||,conditionalAndExpression]"],ABS:["conditionalAndExpression","*[||,conditionalAndExpression]"],CEIL:["conditionalAndExpression","*[||,conditionalAndExpression]"],FLOOR:["conditionalAndExpression","*[||,conditionalAndExpression]"],ROUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLEN:["conditionalAndExpression","*[||,conditionalAndExpression]"],UCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],LCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],ENCODE_FOR_URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONTAINS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRSTARTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRENDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRBEFORE:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRAFTER:["conditionalAndExpression","*[||,conditionalAndExpression]"],YEAR:["conditionalAndExpression","*[||,conditionalAndExpression]"],MONTH:["conditionalAndExpression","*[||,conditionalAndExpression]"],DAY:["conditionalAndExpression","*[||,conditionalAndExpression]"],HOURS:["conditionalAndExpression","*[||,conditionalAndExpression]"],MINUTES:["conditionalAndExpression","*[||,conditionalAndExpression]"],SECONDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],TIMEZONE:["conditionalAndExpression","*[||,conditionalAndExpression]"],TZ:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOW:["conditionalAndExpression","*[||,conditionalAndExpression]"],UUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRUUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],MD5:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA1:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA256:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA384:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA512:["conditionalAndExpression","*[||,conditionalAndExpression]"],COALESCE:["conditionalAndExpression","*[||,conditionalAndExpression]"],IF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRDT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMETERM:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISIRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISURI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISBLANK:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISLITERAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISNUMERIC:["conditionalAndExpression","*[||,conditionalAndExpression]"],TRUE:["conditionalAndExpression","*[||,conditionalAndExpression]"],FALSE:["conditionalAndExpression","*[||,conditionalAndExpression]"],COUNT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUM:["conditionalAndExpression","*[||,conditionalAndExpression]"],MIN:["conditionalAndExpression","*[||,conditionalAndExpression]"],MAX:["conditionalAndExpression","*[||,conditionalAndExpression]"],AVG:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMPLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],GROUP_CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUBSTR:["conditionalAndExpression","*[||,conditionalAndExpression]"],REPLACE:["conditionalAndExpression","*[||,conditionalAndExpression]"],REGEX:["conditionalAndExpression","*[||,conditionalAndExpression]"],EXISTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOT:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI_REF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL2:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG2:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_LN:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_NS:["conditionalAndExpression","*[||,conditionalAndExpression]"]},constraint:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"]},constructQuery:{CONSTRUCT:["CONSTRUCT","or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])"]},constructTemplate:{"{":["{","?constructTriples","}"]},constructTriples:{VAR1:["triplesSameSubject","?[.,?constructTriples]"],VAR2:["triplesSameSubject","?[.,?constructTriples]"],NIL:["triplesSameSubject","?[.,?constructTriples]"],"(":["triplesSameSubject","?[.,?constructTriples]"],"[":["triplesSameSubject","?[.,?constructTriples]"],IRI_REF:["triplesSameSubject","?[.,?constructTriples]"],TRUE:["triplesSameSubject","?[.,?constructTriples]"],FALSE:["triplesSameSubject","?[.,?constructTriples]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?constructTriples]"],ANON:["triplesSameSubject","?[.,?constructTriples]"],PNAME_LN:["triplesSameSubject","?[.,?constructTriples]"],PNAME_NS:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL2:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?constructTriples]"],INTEGER:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"]},copy:{COPY:["COPY","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},create:{CREATE:["CREATE","?SILENT_3","graphRef"]},dataBlock:{NIL:["or([inlineDataOneVar,inlineDataFull])"],"(":["or([inlineDataOneVar,inlineDataFull])"],VAR1:["or([inlineDataOneVar,inlineDataFull])"],VAR2:["or([inlineDataOneVar,inlineDataFull])"]},dataBlockValue:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],UNDEF:["UNDEF"]},datasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},defaultGraphClause:{IRI_REF:["sourceSelector"],PNAME_LN:["sourceSelector"],PNAME_NS:["sourceSelector"]},delete1:{DATA:["DATA","quadDataNoBnodes"],WHERE:["WHERE","quadPatternNoBnodes"],"{":["quadPatternNoBnodes","?insertClause","*usingClause","WHERE","groupGraphPattern"]},deleteClause:{DELETE:["DELETE","quadPattern"]},describeDatasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},describeQuery:{DESCRIBE:["DESCRIBE","or([+varOrIRIref,*])","*describeDatasetClause","?whereClause","solutionModifier"]},disallowBnodes:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},disallowVars:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},drop:{DROP:["DROP","?SILENT_2","graphRefAll"]},existsFunc:{EXISTS:["EXISTS","groupGraphPattern"]},expression:{"!":["conditionalOrExpression"],"+":["conditionalOrExpression"],"-":["conditionalOrExpression"],VAR1:["conditionalOrExpression"],VAR2:["conditionalOrExpression"],"(":["conditionalOrExpression"],STR:["conditionalOrExpression"],LANG:["conditionalOrExpression"],LANGMATCHES:["conditionalOrExpression"],DATATYPE:["conditionalOrExpression"],BOUND:["conditionalOrExpression"],IRI:["conditionalOrExpression"],URI:["conditionalOrExpression"],BNODE:["conditionalOrExpression"],RAND:["conditionalOrExpression"],ABS:["conditionalOrExpression"],CEIL:["conditionalOrExpression"],FLOOR:["conditionalOrExpression"],ROUND:["conditionalOrExpression"],CONCAT:["conditionalOrExpression"],STRLEN:["conditionalOrExpression"],UCASE:["conditionalOrExpression"],LCASE:["conditionalOrExpression"],ENCODE_FOR_URI:["conditionalOrExpression"],CONTAINS:["conditionalOrExpression"],STRSTARTS:["conditionalOrExpression"],STRENDS:["conditionalOrExpression"],STRBEFORE:["conditionalOrExpression"],STRAFTER:["conditionalOrExpression"],YEAR:["conditionalOrExpression"],MONTH:["conditionalOrExpression"],DAY:["conditionalOrExpression"],HOURS:["conditionalOrExpression"],MINUTES:["conditionalOrExpression"],SECONDS:["conditionalOrExpression"],TIMEZONE:["conditionalOrExpression"],TZ:["conditionalOrExpression"],NOW:["conditionalOrExpression"],UUID:["conditionalOrExpression"],STRUUID:["conditionalOrExpression"],MD5:["conditionalOrExpression"],SHA1:["conditionalOrExpression"],SHA256:["conditionalOrExpression"],SHA384:["conditionalOrExpression"],SHA512:["conditionalOrExpression"],COALESCE:["conditionalOrExpression"],IF:["conditionalOrExpression"],STRLANG:["conditionalOrExpression"],STRDT:["conditionalOrExpression"],SAMETERM:["conditionalOrExpression"],ISIRI:["conditionalOrExpression"],ISURI:["conditionalOrExpression"],ISBLANK:["conditionalOrExpression"],ISLITERAL:["conditionalOrExpression"],ISNUMERIC:["conditionalOrExpression"],TRUE:["conditionalOrExpression"],FALSE:["conditionalOrExpression"],COUNT:["conditionalOrExpression"],SUM:["conditionalOrExpression"],MIN:["conditionalOrExpression"],MAX:["conditionalOrExpression"],AVG:["conditionalOrExpression"],SAMPLE:["conditionalOrExpression"],GROUP_CONCAT:["conditionalOrExpression"],SUBSTR:["conditionalOrExpression"],REPLACE:["conditionalOrExpression"],REGEX:["conditionalOrExpression"],EXISTS:["conditionalOrExpression"],NOT:["conditionalOrExpression"],IRI_REF:["conditionalOrExpression"],STRING_LITERAL1:["conditionalOrExpression"],STRING_LITERAL2:["conditionalOrExpression"],STRING_LITERAL_LONG1:["conditionalOrExpression"],STRING_LITERAL_LONG2:["conditionalOrExpression"],INTEGER:["conditionalOrExpression"],DECIMAL:["conditionalOrExpression"],DOUBLE:["conditionalOrExpression"],INTEGER_POSITIVE:["conditionalOrExpression"],DECIMAL_POSITIVE:["conditionalOrExpression"],DOUBLE_POSITIVE:["conditionalOrExpression"],INTEGER_NEGATIVE:["conditionalOrExpression"],DECIMAL_NEGATIVE:["conditionalOrExpression"],DOUBLE_NEGATIVE:["conditionalOrExpression"],PNAME_LN:["conditionalOrExpression"],PNAME_NS:["conditionalOrExpression"]},expressionList:{NIL:["NIL"],"(":["(","expression","*[,,expression]",")"]},filter:{FILTER:["FILTER","constraint"]},functionCall:{IRI_REF:["iriRef","argList"],PNAME_LN:["iriRef","argList"],PNAME_NS:["iriRef","argList"]},graphGraphPattern:{GRAPH:["GRAPH","varOrIRIref","groupGraphPattern"]},graphNode:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNode"],"[":["triplesNode"]},graphNodePath:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNodePath"],"[":["triplesNodePath"]},graphOrDefault:{DEFAULT:["DEFAULT"],IRI_REF:["?GRAPH","iriRef"],PNAME_LN:["?GRAPH","iriRef"],PNAME_NS:["?GRAPH","iriRef"],GRAPH:["?GRAPH","iriRef"]},graphPatternNotTriples:{"{":["groupOrUnionGraphPattern"],OPTIONAL:["optionalGraphPattern"],MINUS:["minusGraphPattern"],GRAPH:["graphGraphPattern"],SERVICE:["serviceGraphPattern"],FILTER:["filter"],BIND:["bind"],VALUES:["inlineData"]},graphRef:{GRAPH:["GRAPH","iriRef"]},graphRefAll:{GRAPH:["graphRef"],DEFAULT:["DEFAULT"],NAMED:["NAMED"],ALL:["ALL"]},graphTerm:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],BLANK_NODE_LABEL:["blankNode"],ANON:["blankNode"],NIL:["NIL"]},groupClause:{GROUP:["GROUP","BY","+groupCondition"]},groupCondition:{STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"],"(":["(","expression","?[AS,var]",")"],VAR1:["var"],VAR2:["var"]},groupGraphPattern:{"{":["{","or([subSelect,groupGraphPatternSub])","}"]},groupGraphPatternSub:{"{":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],NIL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"(":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"[":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],IRI_REF:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],TRUE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FALSE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BLANK_NODE_LABEL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],ANON:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_LN:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_NS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"]},groupOrUnionGraphPattern:{"{":["groupGraphPattern","*[UNION,groupGraphPattern]"]},havingClause:{HAVING:["HAVING","+havingCondition"]},havingCondition:{"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"]},inlineData:{VALUES:["VALUES","dataBlock"]},inlineDataFull:{NIL:["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"],"(":["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"]},inlineDataOneVar:{VAR1:["var","{","*dataBlockValue","}"],VAR2:["var","{","*dataBlockValue","}"]},insert1:{DATA:["DATA","quadData"],"{":["quadPattern","*usingClause","WHERE","groupGraphPattern"]},insertClause:{INSERT:["INSERT","quadPattern"]},integer:{INTEGER:["INTEGER"]},iriRef:{IRI_REF:["IRI_REF"],PNAME_LN:["prefixedName"],PNAME_NS:["prefixedName"]},iriRefOrFunction:{IRI_REF:["iriRef","?argList"],PNAME_LN:["iriRef","?argList"],PNAME_NS:["iriRef","?argList"]},limitClause:{LIMIT:["LIMIT","INTEGER"]},limitOffsetClauses:{LIMIT:["limitClause","?offsetClause"],OFFSET:["offsetClause","?limitClause"]},load:{LOAD:["LOAD","?SILENT_1","iriRef","?[INTO,graphRef]"]},minusGraphPattern:{MINUS:["MINUS","groupGraphPattern"]},modify:{WITH:["WITH","iriRef","or([[deleteClause,?insertClause],insertClause])","*usingClause","WHERE","groupGraphPattern"]},move:{MOVE:["MOVE","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},multiplicativeExpression:{"!":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"+":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"-":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"(":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANGMATCHES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DATATYPE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BOUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BNODE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],RAND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ABS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CEIL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FLOOR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ROUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLEN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ENCODE_FOR_URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONTAINS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRSTARTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRENDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRBEFORE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRAFTER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],YEAR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MONTH:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DAY:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],HOURS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MINUTES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SECONDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TIMEZONE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TZ:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOW:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRUUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MD5:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA256:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA384:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA512:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COALESCE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRDT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMETERM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISIRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISURI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISBLANK:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISLITERAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISNUMERIC:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TRUE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FALSE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COUNT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MIN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MAX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],AVG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMPLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],GROUP_CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUBSTR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REPLACE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REGEX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],EXISTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI_REF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_LN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_NS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"]},namedGraphClause:{NAMED:["NAMED","sourceSelector"]},notExistsFunc:{NOT:["NOT","EXISTS","groupGraphPattern"]},numericExpression:{"!":["additiveExpression"],"+":["additiveExpression"],"-":["additiveExpression"],VAR1:["additiveExpression"],VAR2:["additiveExpression"],"(":["additiveExpression"],STR:["additiveExpression"],LANG:["additiveExpression"],LANGMATCHES:["additiveExpression"],DATATYPE:["additiveExpression"],BOUND:["additiveExpression"],IRI:["additiveExpression"],URI:["additiveExpression"],BNODE:["additiveExpression"],RAND:["additiveExpression"],ABS:["additiveExpression"],CEIL:["additiveExpression"],FLOOR:["additiveExpression"],ROUND:["additiveExpression"],CONCAT:["additiveExpression"],STRLEN:["additiveExpression"],UCASE:["additiveExpression"],LCASE:["additiveExpression"],ENCODE_FOR_URI:["additiveExpression"],CONTAINS:["additiveExpression"],STRSTARTS:["additiveExpression"],STRENDS:["additiveExpression"],STRBEFORE:["additiveExpression"],STRAFTER:["additiveExpression"],YEAR:["additiveExpression"],MONTH:["additiveExpression"],DAY:["additiveExpression"],HOURS:["additiveExpression"],MINUTES:["additiveExpression"],SECONDS:["additiveExpression"],TIMEZONE:["additiveExpression"],TZ:["additiveExpression"],NOW:["additiveExpression"],UUID:["additiveExpression"],STRUUID:["additiveExpression"],MD5:["additiveExpression"],SHA1:["additiveExpression"],SHA256:["additiveExpression"],SHA384:["additiveExpression"],SHA512:["additiveExpression"],COALESCE:["additiveExpression"],IF:["additiveExpression"],STRLANG:["additiveExpression"],STRDT:["additiveExpression"],SAMETERM:["additiveExpression"],ISIRI:["additiveExpression"],ISURI:["additiveExpression"],ISBLANK:["additiveExpression"],ISLITERAL:["additiveExpression"],ISNUMERIC:["additiveExpression"],TRUE:["additiveExpression"],FALSE:["additiveExpression"],COUNT:["additiveExpression"],SUM:["additiveExpression"],MIN:["additiveExpression"],MAX:["additiveExpression"],AVG:["additiveExpression"],SAMPLE:["additiveExpression"],GROUP_CONCAT:["additiveExpression"],SUBSTR:["additiveExpression"],REPLACE:["additiveExpression"],REGEX:["additiveExpression"],EXISTS:["additiveExpression"],NOT:["additiveExpression"],IRI_REF:["additiveExpression"],STRING_LITERAL1:["additiveExpression"],STRING_LITERAL2:["additiveExpression"],STRING_LITERAL_LONG1:["additiveExpression"],STRING_LITERAL_LONG2:["additiveExpression"],INTEGER:["additiveExpression"],DECIMAL:["additiveExpression"],DOUBLE:["additiveExpression"],INTEGER_POSITIVE:["additiveExpression"],DECIMAL_POSITIVE:["additiveExpression"],DOUBLE_POSITIVE:["additiveExpression"],INTEGER_NEGATIVE:["additiveExpression"],DECIMAL_NEGATIVE:["additiveExpression"],DOUBLE_NEGATIVE:["additiveExpression"],PNAME_LN:["additiveExpression"],PNAME_NS:["additiveExpression"]},numericLiteral:{INTEGER:["numericLiteralUnsigned"],DECIMAL:["numericLiteralUnsigned"],DOUBLE:["numericLiteralUnsigned"],INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},numericLiteralNegative:{INTEGER_NEGATIVE:["INTEGER_NEGATIVE"],DECIMAL_NEGATIVE:["DECIMAL_NEGATIVE"],DOUBLE_NEGATIVE:["DOUBLE_NEGATIVE"]},numericLiteralPositive:{INTEGER_POSITIVE:["INTEGER_POSITIVE"],DECIMAL_POSITIVE:["DECIMAL_POSITIVE"],DOUBLE_POSITIVE:["DOUBLE_POSITIVE"]},numericLiteralUnsigned:{INTEGER:["INTEGER"],DECIMAL:["DECIMAL"],DOUBLE:["DOUBLE"]},object:{"(":["graphNode"],"[":["graphNode"],VAR1:["graphNode"],VAR2:["graphNode"],NIL:["graphNode"],IRI_REF:["graphNode"],TRUE:["graphNode"],FALSE:["graphNode"],BLANK_NODE_LABEL:["graphNode"],ANON:["graphNode"],PNAME_LN:["graphNode"],PNAME_NS:["graphNode"],STRING_LITERAL1:["graphNode"],STRING_LITERAL2:["graphNode"],STRING_LITERAL_LONG1:["graphNode"],STRING_LITERAL_LONG2:["graphNode"],INTEGER:["graphNode"],DECIMAL:["graphNode"],DOUBLE:["graphNode"],INTEGER_POSITIVE:["graphNode"],DECIMAL_POSITIVE:["graphNode"],DOUBLE_POSITIVE:["graphNode"],INTEGER_NEGATIVE:["graphNode"],DECIMAL_NEGATIVE:["graphNode"],DOUBLE_NEGATIVE:["graphNode"]},objectList:{"(":["object","*[,,object]"],"[":["object","*[,,object]"],VAR1:["object","*[,,object]"],VAR2:["object","*[,,object]"],NIL:["object","*[,,object]"],IRI_REF:["object","*[,,object]"],TRUE:["object","*[,,object]"],FALSE:["object","*[,,object]"],BLANK_NODE_LABEL:["object","*[,,object]"],ANON:["object","*[,,object]"],PNAME_LN:["object","*[,,object]"],PNAME_NS:["object","*[,,object]"],STRING_LITERAL1:["object","*[,,object]"],STRING_LITERAL2:["object","*[,,object]"],STRING_LITERAL_LONG1:["object","*[,,object]"],STRING_LITERAL_LONG2:["object","*[,,object]"],INTEGER:["object","*[,,object]"],DECIMAL:["object","*[,,object]"],DOUBLE:["object","*[,,object]"],INTEGER_POSITIVE:["object","*[,,object]"],DECIMAL_POSITIVE:["object","*[,,object]"],DOUBLE_POSITIVE:["object","*[,,object]"],INTEGER_NEGATIVE:["object","*[,,object]"],DECIMAL_NEGATIVE:["object","*[,,object]"],DOUBLE_NEGATIVE:["object","*[,,object]"]},objectListPath:{"(":["objectPath","*[,,objectPath]"],"[":["objectPath","*[,,objectPath]"],VAR1:["objectPath","*[,,objectPath]"],VAR2:["objectPath","*[,,objectPath]"],NIL:["objectPath","*[,,objectPath]"],IRI_REF:["objectPath","*[,,objectPath]"],TRUE:["objectPath","*[,,objectPath]"],FALSE:["objectPath","*[,,objectPath]"],BLANK_NODE_LABEL:["objectPath","*[,,objectPath]"],ANON:["objectPath","*[,,objectPath]"],PNAME_LN:["objectPath","*[,,objectPath]"],PNAME_NS:["objectPath","*[,,objectPath]"],STRING_LITERAL1:["objectPath","*[,,objectPath]"],STRING_LITERAL2:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG1:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG2:["objectPath","*[,,objectPath]"],INTEGER:["objectPath","*[,,objectPath]"],DECIMAL:["objectPath","*[,,objectPath]"],DOUBLE:["objectPath","*[,,objectPath]"],INTEGER_POSITIVE:["objectPath","*[,,objectPath]"],DECIMAL_POSITIVE:["objectPath","*[,,objectPath]"],DOUBLE_POSITIVE:["objectPath","*[,,objectPath]"],INTEGER_NEGATIVE:["objectPath","*[,,objectPath]"],DECIMAL_NEGATIVE:["objectPath","*[,,objectPath]"],DOUBLE_NEGATIVE:["objectPath","*[,,objectPath]"]},objectPath:{"(":["graphNodePath"],"[":["graphNodePath"],VAR1:["graphNodePath"],VAR2:["graphNodePath"],NIL:["graphNodePath"],IRI_REF:["graphNodePath"],TRUE:["graphNodePath"],FALSE:["graphNodePath"],BLANK_NODE_LABEL:["graphNodePath"],ANON:["graphNodePath"],PNAME_LN:["graphNodePath"],PNAME_NS:["graphNodePath"],STRING_LITERAL1:["graphNodePath"],STRING_LITERAL2:["graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath"],INTEGER:["graphNodePath"],DECIMAL:["graphNodePath"],DOUBLE:["graphNodePath"],INTEGER_POSITIVE:["graphNodePath"],DECIMAL_POSITIVE:["graphNodePath"],DOUBLE_POSITIVE:["graphNodePath"],INTEGER_NEGATIVE:["graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath"]},offsetClause:{OFFSET:["OFFSET","INTEGER"]},optionalGraphPattern:{OPTIONAL:["OPTIONAL","groupGraphPattern"]},"or([*,expression])":{"*":["*"],"!":["expression"],"+":["expression"],"-":["expression"],VAR1:["expression"],VAR2:["expression"],"(":["expression"],STR:["expression"],LANG:["expression"],LANGMATCHES:["expression"],DATATYPE:["expression"],BOUND:["expression"],IRI:["expression"],URI:["expression"],BNODE:["expression"],RAND:["expression"],ABS:["expression"],CEIL:["expression"],FLOOR:["expression"],ROUND:["expression"],CONCAT:["expression"],STRLEN:["expression"],UCASE:["expression"],LCASE:["expression"],ENCODE_FOR_URI:["expression"],CONTAINS:["expression"],STRSTARTS:["expression"],STRENDS:["expression"],STRBEFORE:["expression"],STRAFTER:["expression"],YEAR:["expression"],MONTH:["expression"],DAY:["expression"],HOURS:["expression"],MINUTES:["expression"],SECONDS:["expression"],TIMEZONE:["expression"],TZ:["expression"],NOW:["expression"],UUID:["expression"],STRUUID:["expression"],MD5:["expression"],SHA1:["expression"],SHA256:["expression"],SHA384:["expression"],SHA512:["expression"],COALESCE:["expression"],IF:["expression"],STRLANG:["expression"],STRDT:["expression"],SAMETERM:["expression"],ISIRI:["expression"],ISURI:["expression"],ISBLANK:["expression"],ISLITERAL:["expression"],ISNUMERIC:["expression"],TRUE:["expression"],FALSE:["expression"],COUNT:["expression"],SUM:["expression"],MIN:["expression"],MAX:["expression"],AVG:["expression"],SAMPLE:["expression"],GROUP_CONCAT:["expression"],SUBSTR:["expression"],REPLACE:["expression"],REGEX:["expression"],EXISTS:["expression"],NOT:["expression"],IRI_REF:["expression"],STRING_LITERAL1:["expression"],STRING_LITERAL2:["expression"],STRING_LITERAL_LONG1:["expression"],STRING_LITERAL_LONG2:["expression"],INTEGER:["expression"],DECIMAL:["expression"],DOUBLE:["expression"],INTEGER_POSITIVE:["expression"],DECIMAL_POSITIVE:["expression"],DOUBLE_POSITIVE:["expression"],INTEGER_NEGATIVE:["expression"],DECIMAL_NEGATIVE:["expression"],DOUBLE_NEGATIVE:["expression"],PNAME_LN:["expression"],PNAME_NS:["expression"]},"or([+or([var,[ (,expression,AS,var,)]]),*])":{"(":["+or([var,[ (,expression,AS,var,)]])"],VAR1:["+or([var,[ (,expression,AS,var,)]])"],VAR2:["+or([var,[ (,expression,AS,var,)]])"],"*":["*"]},"or([+varOrIRIref,*])":{VAR1:["+varOrIRIref"],VAR2:["+varOrIRIref"],IRI_REF:["+varOrIRIref"],PNAME_LN:["+varOrIRIref"],PNAME_NS:["+varOrIRIref"],"*":["*"]},"or([ASC,DESC])":{ASC:["ASC"],DESC:["DESC"]},"or([DISTINCT,REDUCED])":{DISTINCT:["DISTINCT"],REDUCED:["REDUCED"]},"or([LANGTAG,[^^,iriRef]])":{LANGTAG:["LANGTAG"],"^^":["[^^,iriRef]"]},"or([NIL,[ (,*var,)]])":{NIL:["NIL"],"(":["[ (,*var,)]"]},"or([[ (,*dataBlockValue,)],NIL])":{"(":["[ (,*dataBlockValue,)]"],NIL:["NIL"]},"or([[ (,expression,)],NIL])":{"(":["[ (,expression,)]"],NIL:["NIL"]},"or([[*,unaryExpression],[/,unaryExpression]])":{"*":["[*,unaryExpression]"],"/":["[/,unaryExpression]"]},"or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["[+,multiplicativeExpression]"],"-":["[-,multiplicativeExpression]"],INTEGER_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],INTEGER_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"]},"or([[,,or([},[integer,}]])],}])":{",":["[,,or([},[integer,}]])]"],"}":["}"]},"or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["[=,numericExpression]"],"!=":["[!=,numericExpression]"],"<":["[<,numericExpression]"],">":["[>,numericExpression]"],"<=":["[<=,numericExpression]"],">=":["[>=,numericExpression]"],IN:["[IN,expressionList]"],NOT:["[NOT,IN,expressionList]"]},"or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])":{"{":["[constructTemplate,*datasetClause,whereClause,solutionModifier]"],WHERE:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"],FROM:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"]},"or([[deleteClause,?insertClause],insertClause])":{DELETE:["[deleteClause,?insertClause]"],INSERT:["insertClause"]},"or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])":{INTEGER:["[integer,or([[,,or([},[integer,}]])],}])]"],",":["[,,integer,}]"]},"or([defaultGraphClause,namedGraphClause])":{IRI_REF:["defaultGraphClause"],PNAME_LN:["defaultGraphClause"],PNAME_NS:["defaultGraphClause"],NAMED:["namedGraphClause"]},"or([inlineDataOneVar,inlineDataFull])":{VAR1:["inlineDataOneVar"],VAR2:["inlineDataOneVar"],NIL:["inlineDataFull"],"(":["inlineDataFull"]},"or([iriRef,[NAMED,iriRef]])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],NAMED:["[NAMED,iriRef]"]},"or([iriRef,a])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"]},"or([numericLiteralPositive,numericLiteralNegative])":{INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},"or([queryAll,updateAll])":{CONSTRUCT:["queryAll"],DESCRIBE:["queryAll"],ASK:["queryAll"],SELECT:["queryAll"],INSERT:["updateAll"],DELETE:["updateAll"],LOAD:["updateAll"],CLEAR:["updateAll"],DROP:["updateAll"],ADD:["updateAll"],MOVE:["updateAll"],COPY:["updateAll"],CREATE:["updateAll"],WITH:["updateAll"],$:["updateAll"]},"or([selectQuery,constructQuery,describeQuery,askQuery])":{SELECT:["selectQuery"],CONSTRUCT:["constructQuery"],DESCRIBE:["describeQuery"],ASK:["askQuery"]},"or([subSelect,groupGraphPatternSub])":{SELECT:["subSelect"],"{":["groupGraphPatternSub"],OPTIONAL:["groupGraphPatternSub"],MINUS:["groupGraphPatternSub"],GRAPH:["groupGraphPatternSub"],SERVICE:["groupGraphPatternSub"],FILTER:["groupGraphPatternSub"],BIND:["groupGraphPatternSub"],VALUES:["groupGraphPatternSub"],VAR1:["groupGraphPatternSub"],VAR2:["groupGraphPatternSub"],NIL:["groupGraphPatternSub"],"(":["groupGraphPatternSub"],"[":["groupGraphPatternSub"],IRI_REF:["groupGraphPatternSub"],TRUE:["groupGraphPatternSub"],FALSE:["groupGraphPatternSub"],BLANK_NODE_LABEL:["groupGraphPatternSub"],ANON:["groupGraphPatternSub"],PNAME_LN:["groupGraphPatternSub"],PNAME_NS:["groupGraphPatternSub"],STRING_LITERAL1:["groupGraphPatternSub"],STRING_LITERAL2:["groupGraphPatternSub"],STRING_LITERAL_LONG1:["groupGraphPatternSub"],STRING_LITERAL_LONG2:["groupGraphPatternSub"],INTEGER:["groupGraphPatternSub"],DECIMAL:["groupGraphPatternSub"],DOUBLE:["groupGraphPatternSub"],INTEGER_POSITIVE:["groupGraphPatternSub"],DECIMAL_POSITIVE:["groupGraphPatternSub"],DOUBLE_POSITIVE:["groupGraphPatternSub"],INTEGER_NEGATIVE:["groupGraphPatternSub"],DECIMAL_NEGATIVE:["groupGraphPatternSub"],DOUBLE_NEGATIVE:["groupGraphPatternSub"],"}":["groupGraphPatternSub"]},"or([var,[ (,expression,AS,var,)]])":{VAR1:["var"],VAR2:["var"],"(":["[ (,expression,AS,var,)]"]},"or([verbPath,verbSimple])":{"^":["verbPath"],a:["verbPath"],"!":["verbPath"],"(":["verbPath"],IRI_REF:["verbPath"],PNAME_LN:["verbPath"],PNAME_NS:["verbPath"],VAR1:["verbSimple"],VAR2:["verbSimple"]},"or([},[integer,}]])":{"}":["}"],INTEGER:["[integer,}]"]},orderClause:{ORDER:["ORDER","BY","+orderCondition"]},orderCondition:{ASC:["or([ASC,DESC])","brackettedExpression"],DESC:["or([ASC,DESC])","brackettedExpression"],"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"],VAR1:["var"],VAR2:["var"]},path:{"^":["pathAlternative"],a:["pathAlternative"],"!":["pathAlternative"],"(":["pathAlternative"],IRI_REF:["pathAlternative"],PNAME_LN:["pathAlternative"],PNAME_NS:["pathAlternative"]},pathAlternative:{"^":["pathSequence","*[|,pathSequence]"],a:["pathSequence","*[|,pathSequence]"],"!":["pathSequence","*[|,pathSequence]"],"(":["pathSequence","*[|,pathSequence]"],IRI_REF:["pathSequence","*[|,pathSequence]"],PNAME_LN:["pathSequence","*[|,pathSequence]"],PNAME_NS:["pathSequence","*[|,pathSequence]"]},pathElt:{a:["pathPrimary","?pathMod"],"!":["pathPrimary","?pathMod"],"(":["pathPrimary","?pathMod"],IRI_REF:["pathPrimary","?pathMod"],PNAME_LN:["pathPrimary","?pathMod"],PNAME_NS:["pathPrimary","?pathMod"]},pathEltOrInverse:{a:["pathElt"],"!":["pathElt"],"(":["pathElt"],IRI_REF:["pathElt"],PNAME_LN:["pathElt"],PNAME_NS:["pathElt"],"^":["^","pathElt"]},pathMod:{"*":["*"],"?":["?"],"+":["+"],"{":["{","or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])"]},pathNegatedPropertySet:{a:["pathOneInPropertySet"],"^":["pathOneInPropertySet"],IRI_REF:["pathOneInPropertySet"],PNAME_LN:["pathOneInPropertySet"],PNAME_NS:["pathOneInPropertySet"],"(":["(","?[pathOneInPropertySet,*[|,pathOneInPropertySet]]",")"]},pathOneInPropertySet:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"],"^":["^","or([iriRef,a])"]},pathPrimary:{IRI_REF:["storeProperty","iriRef"],PNAME_LN:["storeProperty","iriRef"],PNAME_NS:["storeProperty","iriRef"],a:["storeProperty","a"],"!":["!","pathNegatedPropertySet"],"(":["(","path",")"]},pathSequence:{"^":["pathEltOrInverse","*[/,pathEltOrInverse]"],a:["pathEltOrInverse","*[/,pathEltOrInverse]"],"!":["pathEltOrInverse","*[/,pathEltOrInverse]"],"(":["pathEltOrInverse","*[/,pathEltOrInverse]"],IRI_REF:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_LN:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_NS:["pathEltOrInverse","*[/,pathEltOrInverse]"]},prefixDecl:{PREFIX:["PREFIX","PNAME_NS","IRI_REF"]},prefixedName:{PNAME_LN:["PNAME_LN"],PNAME_NS:["PNAME_NS"]},primaryExpression:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["iriRefOrFunction"],PNAME_LN:["iriRefOrFunction"],PNAME_NS:["iriRefOrFunction"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],VAR1:["var"],VAR2:["var"],COUNT:["aggregate"],SUM:["aggregate"],MIN:["aggregate"],MAX:["aggregate"],AVG:["aggregate"],SAMPLE:["aggregate"],GROUP_CONCAT:["aggregate"]},prologue:{PREFIX:["?baseDecl","*prefixDecl"],BASE:["?baseDecl","*prefixDecl"],$:["?baseDecl","*prefixDecl"],CONSTRUCT:["?baseDecl","*prefixDecl"],DESCRIBE:["?baseDecl","*prefixDecl"],ASK:["?baseDecl","*prefixDecl"],INSERT:["?baseDecl","*prefixDecl"],DELETE:["?baseDecl","*prefixDecl"],SELECT:["?baseDecl","*prefixDecl"],LOAD:["?baseDecl","*prefixDecl"],CLEAR:["?baseDecl","*prefixDecl"],DROP:["?baseDecl","*prefixDecl"],ADD:["?baseDecl","*prefixDecl"],MOVE:["?baseDecl","*prefixDecl"],COPY:["?baseDecl","*prefixDecl"],CREATE:["?baseDecl","*prefixDecl"],WITH:["?baseDecl","*prefixDecl"]},propertyList:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"}":[],GRAPH:[]},propertyListNotEmpty:{a:["verb","objectList","*[;,?[verb,objectList]]"],VAR1:["verb","objectList","*[;,?[verb,objectList]]"],VAR2:["verb","objectList","*[;,?[verb,objectList]]"],IRI_REF:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_LN:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_NS:["verb","objectList","*[;,?[verb,objectList]]"]},propertyListPath:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},propertyListPathNotEmpty:{VAR1:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],VAR2:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"^":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],a:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"!":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"(":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],IRI_REF:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_LN:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_NS:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"]},quadData:{"{":["{","disallowVars","quads","allowVars","}"]},quadDataNoBnodes:{"{":["{","disallowBnodes","disallowVars","quads","allowVars","allowBnodes","}"]},quadPattern:{"{":["{","quads","}"]},quadPatternNoBnodes:{"{":["{","disallowBnodes","quads","allowBnodes","}"]},quads:{GRAPH:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],NIL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"(":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"[":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],IRI_REF:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],TRUE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],FALSE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],BLANK_NODE_LABEL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],ANON:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_LN:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_NS:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"}":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"]},quadsNotTriples:{GRAPH:["GRAPH","varOrIRIref","{","?triplesTemplate","}"]},queryAll:{CONSTRUCT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],DESCRIBE:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],ASK:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],SELECT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"]},rdfLiteral:{STRING_LITERAL1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL2:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG2:["string","?or([LANGTAG,[^^,iriRef]])"]},regexExpression:{REGEX:["REGEX","(","expression",",","expression","?[,,expression]",")"]},relationalExpression:{"!":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"+":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"-":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"(":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANGMATCHES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DATATYPE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BOUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BNODE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],RAND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ABS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CEIL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FLOOR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ROUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLEN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ENCODE_FOR_URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONTAINS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRSTARTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRENDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRBEFORE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRAFTER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],YEAR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MONTH:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DAY:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],HOURS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MINUTES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SECONDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TIMEZONE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TZ:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOW:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRUUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MD5:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA256:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA384:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA512:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COALESCE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRDT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMETERM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISIRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISURI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISBLANK:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISLITERAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISNUMERIC:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TRUE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FALSE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COUNT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MIN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MAX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AVG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMPLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],GROUP_CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUBSTR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REPLACE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REGEX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],EXISTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI_REF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_LN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_NS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"]},selectClause:{SELECT:["SELECT","?or([DISTINCT,REDUCED])","or([+or([var,[ (,expression,AS,var,)]]),*])"]},selectQuery:{SELECT:["selectClause","*datasetClause","whereClause","solutionModifier"]},serviceGraphPattern:{SERVICE:["SERVICE","?SILENT","varOrIRIref","groupGraphPattern"]},solutionModifier:{LIMIT:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],OFFSET:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],ORDER:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],HAVING:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],GROUP:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],VALUES:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],$:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],"}":["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"]},sourceSelector:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},sparql11:{$:["prologue","or([queryAll,updateAll])","$"],CONSTRUCT:["prologue","or([queryAll,updateAll])","$"],DESCRIBE:["prologue","or([queryAll,updateAll])","$"],ASK:["prologue","or([queryAll,updateAll])","$"],INSERT:["prologue","or([queryAll,updateAll])","$"],DELETE:["prologue","or([queryAll,updateAll])","$"],SELECT:["prologue","or([queryAll,updateAll])","$"],LOAD:["prologue","or([queryAll,updateAll])","$"],CLEAR:["prologue","or([queryAll,updateAll])","$"],DROP:["prologue","or([queryAll,updateAll])","$"],ADD:["prologue","or([queryAll,updateAll])","$"],MOVE:["prologue","or([queryAll,updateAll])","$"],COPY:["prologue","or([queryAll,updateAll])","$"],CREATE:["prologue","or([queryAll,updateAll])","$"],WITH:["prologue","or([queryAll,updateAll])","$"],PREFIX:["prologue","or([queryAll,updateAll])","$"],BASE:["prologue","or([queryAll,updateAll])","$"]},storeProperty:{VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[],a:[]},strReplaceExpression:{REPLACE:["REPLACE","(","expression",",","expression",",","expression","?[,,expression]",")"]},string:{STRING_LITERAL1:["STRING_LITERAL1"],STRING_LITERAL2:["STRING_LITERAL2"],STRING_LITERAL_LONG1:["STRING_LITERAL_LONG1"],STRING_LITERAL_LONG2:["STRING_LITERAL_LONG2"]},subSelect:{SELECT:["selectClause","whereClause","solutionModifier","valuesClause"]},substringExpression:{SUBSTR:["SUBSTR","(","expression",",","expression","?[,,expression]",")"]},triplesBlock:{VAR1:["triplesSameSubjectPath","?[.,?triplesBlock]"],VAR2:["triplesSameSubjectPath","?[.,?triplesBlock]"],NIL:["triplesSameSubjectPath","?[.,?triplesBlock]"],"(":["triplesSameSubjectPath","?[.,?triplesBlock]"],"[":["triplesSameSubjectPath","?[.,?triplesBlock]"],IRI_REF:["triplesSameSubjectPath","?[.,?triplesBlock]"],TRUE:["triplesSameSubjectPath","?[.,?triplesBlock]"],FALSE:["triplesSameSubjectPath","?[.,?triplesBlock]"],BLANK_NODE_LABEL:["triplesSameSubjectPath","?[.,?triplesBlock]"],ANON:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_LN:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_NS:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL2:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG2:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"]},triplesNode:{"(":["collection"],"[":["blankNodePropertyList"]},triplesNodePath:{"(":["collectionPath"],"[":["blankNodePropertyListPath"]},triplesSameSubject:{VAR1:["varOrTerm","propertyListNotEmpty"],VAR2:["varOrTerm","propertyListNotEmpty"],NIL:["varOrTerm","propertyListNotEmpty"],IRI_REF:["varOrTerm","propertyListNotEmpty"],TRUE:["varOrTerm","propertyListNotEmpty"],FALSE:["varOrTerm","propertyListNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListNotEmpty"],ANON:["varOrTerm","propertyListNotEmpty"],PNAME_LN:["varOrTerm","propertyListNotEmpty"],PNAME_NS:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListNotEmpty"],INTEGER:["varOrTerm","propertyListNotEmpty"],DECIMAL:["varOrTerm","propertyListNotEmpty"],DOUBLE:["varOrTerm","propertyListNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListNotEmpty"],"(":["triplesNode","propertyList"],"[":["triplesNode","propertyList"]},triplesSameSubjectPath:{VAR1:["varOrTerm","propertyListPathNotEmpty"],VAR2:["varOrTerm","propertyListPathNotEmpty"],NIL:["varOrTerm","propertyListPathNotEmpty"],IRI_REF:["varOrTerm","propertyListPathNotEmpty"],TRUE:["varOrTerm","propertyListPathNotEmpty"],FALSE:["varOrTerm","propertyListPathNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListPathNotEmpty"],ANON:["varOrTerm","propertyListPathNotEmpty"],PNAME_LN:["varOrTerm","propertyListPathNotEmpty"],PNAME_NS:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListPathNotEmpty"],INTEGER:["varOrTerm","propertyListPathNotEmpty"],DECIMAL:["varOrTerm","propertyListPathNotEmpty"],DOUBLE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],"(":["triplesNodePath","propertyListPath"],"[":["triplesNodePath","propertyListPath"]},triplesTemplate:{VAR1:["triplesSameSubject","?[.,?triplesTemplate]"],VAR2:["triplesSameSubject","?[.,?triplesTemplate]"],NIL:["triplesSameSubject","?[.,?triplesTemplate]"],"(":["triplesSameSubject","?[.,?triplesTemplate]"],"[":["triplesSameSubject","?[.,?triplesTemplate]"],IRI_REF:["triplesSameSubject","?[.,?triplesTemplate]"],TRUE:["triplesSameSubject","?[.,?triplesTemplate]"],FALSE:["triplesSameSubject","?[.,?triplesTemplate]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?triplesTemplate]"],ANON:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_LN:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_NS:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL2:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"]},unaryExpression:{"!":["!","primaryExpression"],"+":["+","primaryExpression"],"-":["-","primaryExpression"],VAR1:["primaryExpression"],VAR2:["primaryExpression"],"(":["primaryExpression"],STR:["primaryExpression"],LANG:["primaryExpression"],LANGMATCHES:["primaryExpression"],DATATYPE:["primaryExpression"],BOUND:["primaryExpression"],IRI:["primaryExpression"],URI:["primaryExpression"],BNODE:["primaryExpression"],RAND:["primaryExpression"],ABS:["primaryExpression"],CEIL:["primaryExpression"],FLOOR:["primaryExpression"],ROUND:["primaryExpression"],CONCAT:["primaryExpression"],STRLEN:["primaryExpression"],UCASE:["primaryExpression"],LCASE:["primaryExpression"],ENCODE_FOR_URI:["primaryExpression"],CONTAINS:["primaryExpression"],STRSTARTS:["primaryExpression"],STRENDS:["primaryExpression"],STRBEFORE:["primaryExpression"],STRAFTER:["primaryExpression"],YEAR:["primaryExpression"],MONTH:["primaryExpression"],DAY:["primaryExpression"],HOURS:["primaryExpression"],MINUTES:["primaryExpression"],SECONDS:["primaryExpression"],TIMEZONE:["primaryExpression"],TZ:["primaryExpression"],NOW:["primaryExpression"],UUID:["primaryExpression"],STRUUID:["primaryExpression"],MD5:["primaryExpression"],SHA1:["primaryExpression"],SHA256:["primaryExpression"],SHA384:["primaryExpression"],SHA512:["primaryExpression"],COALESCE:["primaryExpression"],IF:["primaryExpression"],STRLANG:["primaryExpression"],STRDT:["primaryExpression"],SAMETERM:["primaryExpression"],ISIRI:["primaryExpression"],ISURI:["primaryExpression"],ISBLANK:["primaryExpression"],ISLITERAL:["primaryExpression"],ISNUMERIC:["primaryExpression"],TRUE:["primaryExpression"],FALSE:["primaryExpression"],COUNT:["primaryExpression"],SUM:["primaryExpression"],MIN:["primaryExpression"],MAX:["primaryExpression"],AVG:["primaryExpression"],SAMPLE:["primaryExpression"],GROUP_CONCAT:["primaryExpression"],SUBSTR:["primaryExpression"],REPLACE:["primaryExpression"],REGEX:["primaryExpression"],EXISTS:["primaryExpression"],NOT:["primaryExpression"],IRI_REF:["primaryExpression"],STRING_LITERAL1:["primaryExpression"],STRING_LITERAL2:["primaryExpression"],STRING_LITERAL_LONG1:["primaryExpression"],STRING_LITERAL_LONG2:["primaryExpression"],INTEGER:["primaryExpression"],DECIMAL:["primaryExpression"],DOUBLE:["primaryExpression"],INTEGER_POSITIVE:["primaryExpression"],DECIMAL_POSITIVE:["primaryExpression"],DOUBLE_POSITIVE:["primaryExpression"],INTEGER_NEGATIVE:["primaryExpression"],DECIMAL_NEGATIVE:["primaryExpression"],DOUBLE_NEGATIVE:["primaryExpression"],PNAME_LN:["primaryExpression"],PNAME_NS:["primaryExpression"]},update:{INSERT:["prologue","?[update1,?[;,update]]"],DELETE:["prologue","?[update1,?[;,update]]"],LOAD:["prologue","?[update1,?[;,update]]"],CLEAR:["prologue","?[update1,?[;,update]]"],DROP:["prologue","?[update1,?[;,update]]"],ADD:["prologue","?[update1,?[;,update]]"],MOVE:["prologue","?[update1,?[;,update]]"],COPY:["prologue","?[update1,?[;,update]]"],CREATE:["prologue","?[update1,?[;,update]]"],WITH:["prologue","?[update1,?[;,update]]"],PREFIX:["prologue","?[update1,?[;,update]]"],BASE:["prologue","?[update1,?[;,update]]"],$:["prologue","?[update1,?[;,update]]"]},update1:{LOAD:["load"],CLEAR:["clear"],DROP:["drop"],ADD:["add"],MOVE:["move"],COPY:["copy"],CREATE:["create"],INSERT:["INSERT","insert1"],DELETE:["DELETE","delete1"],WITH:["modify"]},updateAll:{INSERT:["?[update1,?[;,update]]"],DELETE:["?[update1,?[;,update]]"],LOAD:["?[update1,?[;,update]]"],CLEAR:["?[update1,?[;,update]]"],DROP:["?[update1,?[;,update]]"],ADD:["?[update1,?[;,update]]"],MOVE:["?[update1,?[;,update]]"],COPY:["?[update1,?[;,update]]"],CREATE:["?[update1,?[;,update]]"],WITH:["?[update1,?[;,update]]"],$:["?[update1,?[;,update]]"]},usingClause:{USING:["USING","or([iriRef,[NAMED,iriRef]])"]},valueLogical:{"!":["relationalExpression"],"+":["relationalExpression"],"-":["relationalExpression"],VAR1:["relationalExpression"],VAR2:["relationalExpression"],"(":["relationalExpression"],STR:["relationalExpression"],LANG:["relationalExpression"],LANGMATCHES:["relationalExpression"],DATATYPE:["relationalExpression"],BOUND:["relationalExpression"],IRI:["relationalExpression"],URI:["relationalExpression"],BNODE:["relationalExpression"],RAND:["relationalExpression"],ABS:["relationalExpression"],CEIL:["relationalExpression"],FLOOR:["relationalExpression"],ROUND:["relationalExpression"],CONCAT:["relationalExpression"],STRLEN:["relationalExpression"],UCASE:["relationalExpression"],LCASE:["relationalExpression"],ENCODE_FOR_URI:["relationalExpression"],CONTAINS:["relationalExpression"],STRSTARTS:["relationalExpression"],STRENDS:["relationalExpression"],STRBEFORE:["relationalExpression"],STRAFTER:["relationalExpression"],YEAR:["relationalExpression"],MONTH:["relationalExpression"],DAY:["relationalExpression"],HOURS:["relationalExpression"],MINUTES:["relationalExpression"],SECONDS:["relationalExpression"],TIMEZONE:["relationalExpression"],TZ:["relationalExpression"],NOW:["relationalExpression"],UUID:["relationalExpression"],STRUUID:["relationalExpression"],MD5:["relationalExpression"],SHA1:["relationalExpression"],SHA256:["relationalExpression"],SHA384:["relationalExpression"],SHA512:["relationalExpression"],COALESCE:["relationalExpression"],IF:["relationalExpression"],STRLANG:["relationalExpression"],STRDT:["relationalExpression"],SAMETERM:["relationalExpression"],ISIRI:["relationalExpression"],ISURI:["relationalExpression"],ISBLANK:["relationalExpression"],ISLITERAL:["relationalExpression"],ISNUMERIC:["relationalExpression"],TRUE:["relationalExpression"],FALSE:["relationalExpression"],COUNT:["relationalExpression"],SUM:["relationalExpression"],MIN:["relationalExpression"],MAX:["relationalExpression"],AVG:["relationalExpression"],SAMPLE:["relationalExpression"],GROUP_CONCAT:["relationalExpression"],SUBSTR:["relationalExpression"],REPLACE:["relationalExpression"],REGEX:["relationalExpression"],EXISTS:["relationalExpression"],NOT:["relationalExpression"],IRI_REF:["relationalExpression"],STRING_LITERAL1:["relationalExpression"],STRING_LITERAL2:["relationalExpression"],STRING_LITERAL_LONG1:["relationalExpression"],STRING_LITERAL_LONG2:["relationalExpression"],INTEGER:["relationalExpression"],DECIMAL:["relationalExpression"],DOUBLE:["relationalExpression"],INTEGER_POSITIVE:["relationalExpression"],DECIMAL_POSITIVE:["relationalExpression"],DOUBLE_POSITIVE:["relationalExpression"],INTEGER_NEGATIVE:["relationalExpression"],DECIMAL_NEGATIVE:["relationalExpression"],DOUBLE_NEGATIVE:["relationalExpression"],PNAME_LN:["relationalExpression"],PNAME_NS:["relationalExpression"]},valuesClause:{VALUES:["VALUES","dataBlock"],$:[],"}":[]},"var":{VAR1:["VAR1"],VAR2:["VAR2"]},varOrIRIref:{VAR1:["var"],VAR2:["var"],IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},varOrTerm:{VAR1:["var"],VAR2:["var"],NIL:["graphTerm"],IRI_REF:["graphTerm"],TRUE:["graphTerm"],FALSE:["graphTerm"],BLANK_NODE_LABEL:["graphTerm"],ANON:["graphTerm"],PNAME_LN:["graphTerm"],PNAME_NS:["graphTerm"],STRING_LITERAL1:["graphTerm"],STRING_LITERAL2:["graphTerm"],STRING_LITERAL_LONG1:["graphTerm"],STRING_LITERAL_LONG2:["graphTerm"],INTEGER:["graphTerm"],DECIMAL:["graphTerm"],DOUBLE:["graphTerm"],INTEGER_POSITIVE:["graphTerm"],DECIMAL_POSITIVE:["graphTerm"],DOUBLE_POSITIVE:["graphTerm"],INTEGER_NEGATIVE:["graphTerm"],DECIMAL_NEGATIVE:["graphTerm"],DOUBLE_NEGATIVE:["graphTerm"]},verb:{VAR1:["storeProperty","varOrIRIref"],VAR2:["storeProperty","varOrIRIref"],IRI_REF:["storeProperty","varOrIRIref"],PNAME_LN:["storeProperty","varOrIRIref"],PNAME_NS:["storeProperty","varOrIRIref"],a:["storeProperty","a"]},verbPath:{"^":["path"],a:["path"],"!":["path"],"(":["path"],IRI_REF:["path"],PNAME_LN:["path"],PNAME_NS:["path"]},verbSimple:{VAR1:["var"],VAR2:["var"]},whereClause:{"{":["?WHERE","groupGraphPattern"],WHERE:["?WHERE","groupGraphPattern"]}}),s=/^(GROUP_CONCAT|DATATYPE|BASE|PREFIX|SELECT|CONSTRUCT|DESCRIBE|ASK|FROM|NAMED|ORDER|BY|LIMIT|ASC|DESC|OFFSET|DISTINCT|REDUCED|WHERE|GRAPH|OPTIONAL|UNION|FILTER|GROUP|HAVING|AS|VALUES|LOAD|CLEAR|DROP|CREATE|MOVE|COPY|SILENT|INSERT|DELETE|DATA|WITH|TO|USING|NAMED|MINUS|BIND|LANGMATCHES|LANG|BOUND|SAMETERM|ISIRI|ISURI|ISBLANK|ISLITERAL|REGEX|TRUE|FALSE|UNDEF|ADD|DEFAULT|ALL|SERVICE|INTO|IN|NOT|IRI|URI|BNODE|RAND|ABS|CEIL|FLOOR|ROUND|CONCAT|STRLEN|UCASE|LCASE|ENCODE_FOR_URI|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|NOW|UUID|STRUUID|MD5|SHA1|SHA256|SHA384|SHA512|COALESCE|IF|STRLANG|STRDT|ISNUMERIC|SUBSTR|REPLACE|EXISTS|COUNT|SUM|MIN|MAX|AVG|SAMPLE|SEPARATOR|STR)/i,a=/^(\*|a|\.|\{|\}|,|\(|\)|;|\[|\]|\|\||&&|=|!=|!|<=|>=|<|>|\+|-|\/|\^\^|\?|\||\^)/,p=null,E="sparql11",l="sparql11",u=!0,c=i(),d=c.terminal,N={"*[,, object]":3,"*[(,),object]":3,"*[(,),objectPath]":3,"*[/,pathEltOrInverse]":2,object:2,objectPath:2,objectList:2,objectListPath:2,storeProperty:2,pathMod:2,"?pathMod":2,propertyListNotEmpty:1,propertyList:1,propertyListPath:1,propertyListPathNotEmpty:1,"?[verb,objectList]":1,"?[or([verbPath, verbSimple]),objectList]":1},I={"}":1,"]":0,")":1,"{":-1,"(":-1,"*[;,?[or([verbPath,verbSimple]),objectList]]":1};
return{token:n,startState:function(){return{tokenize:n,OK:!0,complete:u,errorStartPos:null,errorEndPos:null,queryType:p,possibleCurrent:r(l),possibleNext:r(l),allowVars:!0,allowBnodes:!0,storeProperty:!1,lastProperty:"",stack:[l]}},indent:o,electricChars:"}])"}}),e.defineMIME("application/x-sparql-query","sparql11")})},{codemirror:void 0}],4:[function(e,i){i.exports=Trie=function(){this.words=0,this.prefixes=0,this.children=[]},Trie.prototype={insert:function(e,i){if(0!=e.length){var r,n,o=this;if(void 0===i&&(i=0),i===e.length)return void o.words++;o.prefixes++,r=e[i],void 0===o.children[r]&&(o.children[r]=new Trie),n=o.children[r],n.insert(e,i+1)}},remove:function(e,i){if(0!=e.length){var r,n,o=this;if(void 0===i&&(i=0),void 0!==o){if(i===e.length)return void o.words--;o.prefixes--,r=e[i],n=o.children[r],n.remove(e,i+1)}}},update:function(e,i){0!=e.length&&0!=i.length&&(this.remove(e),this.insert(i))},countWord:function(e,i){if(0==e.length)return 0;var r,n,o=this,t=0;return void 0===i&&(i=0),i===e.length?o.words:(r=e[i],n=o.children[r],void 0!==n&&(t=n.countWord(e,i+1)),t)},countPrefix:function(e,i){if(0==e.length)return 0;var r,n,o=this,t=0;if(void 0===i&&(i=0),i===e.length)return o.prefixes;var r=e[i];return n=o.children[r],void 0!==n&&(t=n.countPrefix(e,i+1)),t},find:function(e){return 0==e.length?!1:this.countWord(e)>0?!0:!1},getAllWords:function(e){var i,r,n=this,o=[];if(void 0===e&&(e=""),void 0===n)return[];n.words>0&&o.push(e);for(i in n.children)r=n.children[i],o=o.concat(r.getAllWords(e+i));return o},autoComplete:function(e,i){var r,n,o=this;return 0==e.length?void 0===i?o.getAllWords(e):[]:(void 0===i&&(i=0),r=e[i],n=o.children[r],void 0===n?[]:i===e.length-1?n.getAllWords(e):n.autoComplete(e,i+1))}}},{}],5:[function(i,r,n){!function(o){"object"==typeof n&&"object"==typeof r?o(function(){try{return i("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],o):o(CodeMirror)}(function(e){"use strict";function i(e){var i=e.getWrapperElement();e.state.fullScreenRestore={scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,width:i.style.width,height:i.style.height},i.style.width="",i.style.height="auto",i.className+=" CodeMirror-fullscreen",document.documentElement.style.overflow="hidden",e.refresh()}function r(e){var i=e.getWrapperElement();i.className=i.className.replace(/\s*CodeMirror-fullscreen\b/,""),document.documentElement.style.overflow="";var r=e.state.fullScreenRestore;i.style.width=r.width,i.style.height=r.height,window.scrollTo(r.scrollLeft,r.scrollTop),e.refresh()}e.defineOption("fullScreen",!1,function(n,o,t){t==e.Init&&(t=!1),!t!=!o&&(o?i(n):r(n))})})},{codemirror:void 0}],6:[function(i,r,n){!function(o){"object"==typeof n&&"object"==typeof r?o(function(){try{return i("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],o):o(CodeMirror)}(function(e){function i(e,i,n,o){var t=e.getLineHandle(i.line),p=i.ch-1,E=p>=0&&a[t.text.charAt(p)]||a[t.text.charAt(++p)];if(!E)return null;var l=">"==E.charAt(1)?1:-1;if(n&&l>0!=(p==i.ch))return null;var u=e.getTokenTypeAt(s(i.line,p+1)),c=r(e,s(i.line,p+(l>0?1:0)),l,u||null,o);return null==c?null:{from:s(i.line,p),to:c&&c.pos,match:c&&c.ch==E.charAt(0),forward:l>0}}function r(e,i,r,n,o){for(var t=o&&o.maxScanLineLength||1e4,p=o&&o.maxScanLines||1e3,E=[],l=o&&o.bracketRegex?o.bracketRegex:/[(){}[\]]/,u=r>0?Math.min(i.line+p,e.lastLine()+1):Math.max(e.firstLine()-1,i.line-p),c=i.line;c!=u;c+=r){var d=e.getLine(c);if(d){var N=r>0?0:d.length-1,I=r>0?d.length:-1;if(!(d.length>t))for(c==i.line&&(N=i.ch-(0>r?1:0));N!=I;N+=r){var x=d.charAt(N);if(l.test(x)&&(void 0===n||e.getTokenTypeAt(s(c,N+1))==n)){var L=a[x];if(">"==L.charAt(1)==r>0)E.push(x);else{if(!E.length)return{pos:s(c,N),ch:x};E.pop()}}}}}return c-r==(r>0?e.lastLine():e.firstLine())?!1:null}function n(e,r,n){for(var o=e.state.matchBrackets.maxHighlightLineLength||1e3,a=[],p=e.listSelections(),E=0;E<p.length;E++){var l=p[E].empty()&&i(e,p[E].head,!1,n);if(l&&e.getLine(l.from.line).length<=o){var u=l.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";a.push(e.markText(l.from,s(l.from.line,l.from.ch+1),{className:u})),l.to&&e.getLine(l.to.line).length<=o&&a.push(e.markText(l.to,s(l.to.line,l.to.ch+1),{className:u}))}}if(a.length){t&&e.state.focused&&e.display.input.focus();var c=function(){e.operation(function(){for(var e=0;e<a.length;e++)a[e].clear()})};if(!r)return c;setTimeout(c,800)}}function o(e){e.operation(function(){p&&(p(),p=null),p=n(e,!1,e.state.matchBrackets)})}var t=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),s=e.Pos,a={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},p=null;e.defineOption("matchBrackets",!1,function(i,r,n){n&&n!=e.Init&&i.off("cursorActivity",o),r&&(i.state.matchBrackets="object"==typeof r?r:{},i.on("cursorActivity",o))}),e.defineExtension("matchBrackets",function(){n(this,!0)}),e.defineExtension("findMatchingBracket",function(e,r,n){return i(this,e,r,n)}),e.defineExtension("scanForBracket",function(e,i,n,o){return r(this,e,i,n,o)})})},{codemirror:void 0}],7:[function(i,r,n){!function(o){"object"==typeof n&&"object"==typeof r?o(function(){try{return i("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],o):o(CodeMirror)}(function(e){"use strict";function i(e,i){this.cm=e,this.options=this.buildOptions(i),this.widget=this.onClose=null}function r(e){return"string"==typeof e?e:e.text}function n(e,i){function r(e,r){var o;o="string"!=typeof r?function(e){return r(e,i)}:n.hasOwnProperty(r)?n[r]:r,t[e]=o}var n={Up:function(){i.moveFocus(-1)},Down:function(){i.moveFocus(1)},PageUp:function(){i.moveFocus(-i.menuSize()+1,!0)},PageDown:function(){i.moveFocus(i.menuSize()-1,!0)},Home:function(){i.setFocus(0)},End:function(){i.setFocus(i.length-1)},Enter:i.pick,Tab:i.pick,Esc:i.close},o=e.options.customKeys,t=o?{}:n;if(o)for(var s in o)o.hasOwnProperty(s)&&r(s,o[s]);var a=e.options.extraKeys;if(a)for(var s in a)a.hasOwnProperty(s)&&r(s,a[s]);return t}function o(e,i){for(;i&&i!=e;){if("LI"===i.nodeName.toUpperCase()&&i.parentNode==e)return i;i=i.parentNode}}function t(i,t){this.completion=i,this.data=t;var p=this,E=i.cm,l=this.hints=document.createElement("ul");l.className="CodeMirror-hints",this.selectedHint=t.selectedHint||0;for(var u=t.list,c=0;c<u.length;++c){var d=l.appendChild(document.createElement("li")),N=u[c],I=s+(c!=this.selectedHint?"":" "+a);null!=N.className&&(I=N.className+" "+I),d.className=I,N.render?N.render(d,t,N):d.appendChild(document.createTextNode(N.displayText||r(N))),d.hintId=c}var x=E.cursorCoords(i.options.alignWithWord?t.from:null),L=x.left,T=x.bottom,m=!0;l.style.left=L+"px",l.style.top=T+"px";var A=window.innerWidth||Math.max(document.body.offsetWidth,document.documentElement.offsetWidth),S=window.innerHeight||Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);(i.options.container||document.body).appendChild(l);var R=l.getBoundingClientRect(),g=R.bottom-S;if(g>0){var v=R.bottom-R.top,C=x.top-(x.bottom-R.top);if(C-v>0)l.style.top=(T=x.top-v)+"px",m=!1;else if(v>S){l.style.height=S-5+"px",l.style.top=(T=x.bottom-R.top)+"px";var h=E.getCursor();t.from.ch!=h.ch&&(x=E.cursorCoords(h),l.style.left=(L=x.left)+"px",R=l.getBoundingClientRect())}}var O=R.left-A;if(O>0&&(R.right-R.left>A&&(l.style.width=A-5+"px",O-=R.right-R.left-A),l.style.left=(L=x.left-O)+"px"),E.addKeyMap(this.keyMap=n(i,{moveFocus:function(e,i){p.changeActive(p.selectedHint+e,i)},setFocus:function(e){p.changeActive(e)},menuSize:function(){return p.screenAmount()},length:u.length,close:function(){i.close()},pick:function(){p.pick()},data:t})),i.options.closeOnUnfocus){var P;E.on("blur",this.onBlur=function(){P=setTimeout(function(){i.close()},100)}),E.on("focus",this.onFocus=function(){clearTimeout(P)})}var y=E.getScrollInfo();return E.on("scroll",this.onScroll=function(){var e=E.getScrollInfo(),r=E.getWrapperElement().getBoundingClientRect(),n=T+y.top-e.top,o=n-(window.pageYOffset||(document.documentElement||document.body).scrollTop);return m||(o+=l.offsetHeight),o<=r.top||o>=r.bottom?i.close():(l.style.top=n+"px",void(l.style.left=L+y.left-e.left+"px"))}),e.on(l,"dblclick",function(e){var i=o(l,e.target||e.srcElement);i&&null!=i.hintId&&(p.changeActive(i.hintId),p.pick())}),e.on(l,"click",function(e){var r=o(l,e.target||e.srcElement);r&&null!=r.hintId&&(p.changeActive(r.hintId),i.options.completeOnSingleClick&&p.pick())}),e.on(l,"mousedown",function(){setTimeout(function(){E.focus()},20)}),e.signal(t,"select",u[0],l.firstChild),!0}var s="CodeMirror-hint",a="CodeMirror-hint-active";e.showHint=function(e,i,r){if(!i)return e.showHint(r);r&&r.async&&(i.async=!0);var n={hint:i};if(r)for(var o in r)n[o]=r[o];return e.showHint(n)},e.defineExtension("showHint",function(r){if(!(this.listSelections().length>1||this.somethingSelected())){this.state.completionActive&&this.state.completionActive.close();var n=this.state.completionActive=new i(this,r),o=n.options.hint;if(o)return e.signal(this,"startCompletion",this),o.async?void o(this,function(e){n.showHints(e)},n.options):n.showHints(o(this,n.options))}}),i.prototype={close:function(){this.active()&&(this.cm.state.completionActive=null,this.widget&&this.widget.close(),this.onClose&&this.onClose(),e.signal(this.cm,"endCompletion",this.cm))},active:function(){return this.cm.state.completionActive==this},pick:function(i,n){var o=i.list[n];o.hint?o.hint(this.cm,i,o):this.cm.replaceRange(r(o),o.from||i.from,o.to||i.to,"complete"),e.signal(i,"pick",o),this.close()},showHints:function(e){return e&&e.list.length&&this.active()?void(this.options.completeSingle&&1==e.list.length?this.pick(e,0):this.showWidget(e)):this.close()},showWidget:function(i){function r(){p||(p=!0,l.close(),l.cm.off("cursorActivity",a),i&&e.signal(i,"close"))}function n(){if(!p){e.signal(i,"update");var r=l.options.hint;r.async?r(l.cm,o,l.options):o(r(l.cm,l.options))}}function o(e){if(i=e,!p){if(!i||!i.list.length)return r();l.widget&&l.widget.close(),l.widget=new t(l,i)}}function s(){E&&(I(E),E=0)}function a(){s();var e=l.cm.getCursor(),i=l.cm.getLine(e.line);e.line!=c.line||i.length-e.ch!=d-c.ch||e.ch<c.ch||l.cm.somethingSelected()||e.ch&&u.test(i.charAt(e.ch-1))?l.close():(E=N(n),l.widget&&l.widget.close())}this.widget=new t(this,i),e.signal(i,"shown");var p,E=0,l=this,u=this.options.closeCharacters,c=this.cm.getCursor(),d=this.cm.getLine(c.line).length,N=window.requestAnimationFrame||function(e){return setTimeout(e,1e3/60)},I=window.cancelAnimationFrame||clearTimeout;this.cm.on("cursorActivity",a),this.onClose=r},buildOptions:function(e){var i=this.cm.options.hintOptions,r={};for(var n in p)r[n]=p[n];if(i)for(var n in i)void 0!==i[n]&&(r[n]=i[n]);if(e)for(var n in e)void 0!==e[n]&&(r[n]=e[n]);return r}},t.prototype={close:function(){if(this.completion.widget==this){this.completion.widget=null,this.hints.parentNode.removeChild(this.hints),this.completion.cm.removeKeyMap(this.keyMap);var e=this.completion.cm;this.completion.options.closeOnUnfocus&&(e.off("blur",this.onBlur),e.off("focus",this.onFocus)),e.off("scroll",this.onScroll)}},pick:function(){this.completion.pick(this.data,this.selectedHint)},changeActive:function(i,r){if(i>=this.data.list.length?i=r?this.data.list.length-1:0:0>i&&(i=r?0:this.data.list.length-1),this.selectedHint!=i){var n=this.hints.childNodes[this.selectedHint];n.className=n.className.replace(" "+a,""),n=this.hints.childNodes[this.selectedHint=i],n.className+=" "+a,n.offsetTop<this.hints.scrollTop?this.hints.scrollTop=n.offsetTop-3:n.offsetTop+n.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=n.offsetTop+n.offsetHeight-this.hints.clientHeight+3),e.signal(this.data,"select",this.data.list[this.selectedHint],n)}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}},e.registerHelper("hint","auto",function(i,r){var n,o=i.getHelpers(i.getCursor(),"hint");if(o.length)for(var t=0;t<o.length;t++){var s=o[t](i,r);if(s&&s.list.length)return s}else if(n=i.getHelper(i.getCursor(),"hintWords")){if(n)return e.hint.fromList(i,{words:n})}else if(e.hint.anyword)return e.hint.anyword(i,r)}),e.registerHelper("hint","fromList",function(i,r){for(var n=i.getCursor(),o=i.getTokenAt(n),t=[],s=0;s<r.words.length;s++){var a=r.words[s];a.slice(0,o.string.length)==o.string&&t.push(a)}return t.length?{list:t,from:e.Pos(n.line,o.start),to:e.Pos(n.line,o.end)}:void 0}),e.commands.autocomplete=e.showHint;var p={hint:e.hint.auto,completeSingle:!0,alignWithWord:!0,closeCharacters:/[\s()\[\]{};:>,]/,closeOnUnfocus:!0,completeOnSingleClick:!1,container:null,customKeys:null,extraKeys:null};e.defineOption("hintOptions",null)})},{codemirror:void 0}],8:[function(i,r,n){!function(o){"object"==typeof n&&"object"==typeof r?o(function(){try{return i("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],o):o(CodeMirror)}(function(e){"use strict";e.runMode=function(i,r,n,o){var t=e.getMode(e.defaults,r),s=/MSIE \d/.test(navigator.userAgent),a=s&&(null==document.documentMode||document.documentMode<9);if(1==n.nodeType){var p=o&&o.tabSize||e.defaults.tabSize,E=n,l=0;E.innerHTML="",n=function(e,i){if("\n"==e)return E.appendChild(document.createTextNode(a?"\r":e)),void(l=0);for(var r="",n=0;;){var o=e.indexOf(" ",n);if(-1==o){r+=e.slice(n),l+=e.length-n;break}l+=o-n,r+=e.slice(n,o);var t=p-l%p;l+=t;for(var s=0;t>s;++s)r+=" ";n=o+1}if(i){var u=E.appendChild(document.createElement("span"));u.className="cm-"+i.replace(/ +/g," cm-"),u.appendChild(document.createTextNode(r))}else E.appendChild(document.createTextNode(r))}}for(var u=e.splitLines(i),c=o&&o.state||e.startState(t),d=0,N=u.length;N>d;++d){d&&n("\n");var I=new e.StringStream(u[d]);for(!I.string&&t.blankLine&&t.blankLine(c);!I.eol();){var x=t.token(I,c);n(I.current(),x,d,I.start,c),I.start=I.pos}}}})},{codemirror:void 0}],9:[function(i,r,n){!function(o){"object"==typeof n&&"object"==typeof r?o(function(){try{return i("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],o):o(CodeMirror)}(function(e){"use strict";function i(e,i,o,t){if(this.atOccurrence=!1,this.doc=e,null==t&&"string"==typeof i&&(t=!1),o=o?e.clipPos(o):n(0,0),this.pos={from:o,to:o},"string"!=typeof i)i.global||(i=new RegExp(i.source,i.ignoreCase?"ig":"g")),this.matches=function(r,o){if(r){i.lastIndex=0;for(var t,s,a=e.getLine(o.line).slice(0,o.ch),p=0;;){i.lastIndex=p;var E=i.exec(a);if(!E)break;if(t=E,s=t.index,p=t.index+(t[0].length||1),p==a.length)break}var l=t&&t[0].length||0;l||(0==s&&0==a.length?t=void 0:s!=e.getLine(o.line).length&&l++)}else{i.lastIndex=o.ch;var a=e.getLine(o.line),t=i.exec(a),l=t&&t[0].length||0,s=t&&t.index;s+l==a.length||l||(l=1)}return t&&l?{from:n(o.line,s),to:n(o.line,s+l),match:t}:void 0};else{var s=i;t&&(i=i.toLowerCase());var a=t?function(e){return e.toLowerCase()}:function(e){return e},p=i.split("\n");if(1==p.length)this.matches=i.length?function(o,t){if(o){var p=e.getLine(t.line).slice(0,t.ch),E=a(p),l=E.lastIndexOf(i);if(l>-1)return l=r(p,E,l),{from:n(t.line,l),to:n(t.line,l+s.length)}}else{var p=e.getLine(t.line).slice(t.ch),E=a(p),l=E.indexOf(i);if(l>-1)return l=r(p,E,l)+t.ch,{from:n(t.line,l),to:n(t.line,l+s.length)}}}:function(){};else{var E=s.split("\n");this.matches=function(i,r){var o=p.length-1;if(i){if(r.line-(p.length-1)<e.firstLine())return;if(a(e.getLine(r.line).slice(0,E[o].length))!=p[p.length-1])return;for(var t=n(r.line,E[o].length),s=r.line-1,l=o-1;l>=1;--l,--s)if(p[l]!=a(e.getLine(s)))return;var u=e.getLine(s),c=u.length-E[0].length;if(a(u.slice(c))!=p[0])return;return{from:n(s,c),to:t}}if(!(r.line+(p.length-1)>e.lastLine())){var u=e.getLine(r.line),c=u.length-E[0].length;if(a(u.slice(c))==p[0]){for(var d=n(r.line,c),s=r.line+1,l=1;o>l;++l,++s)if(p[l]!=a(e.getLine(s)))return;if(a(e.getLine(s).slice(0,E[o].length))==p[o])return{from:d,to:n(s,E[o].length)}}}}}}}function r(e,i,r){if(e.length==i.length)return r;for(var n=Math.min(r,e.length);;){var o=e.slice(0,n).toLowerCase().length;if(r>o)++n;else{if(!(o>r))return n;--n}}}var n=e.Pos;i.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(e){function i(e){var i=n(e,0);return r.pos={from:i,to:i},r.atOccurrence=!1,!1}for(var r=this,o=this.doc.clipPos(e?this.pos.from:this.pos.to);;){if(this.pos=this.matches(e,o))return this.atOccurrence=!0,this.pos.match||!0;if(e){if(!o.line)return i(0);o=n(o.line-1,this.doc.getLine(o.line-1).length)}else{var t=this.doc.lineCount();if(o.line==t-1)return i(t);o=n(o.line+1,0)}}},from:function(){return this.atOccurrence?this.pos.from:void 0},to:function(){return this.atOccurrence?this.pos.to:void 0},replace:function(i){if(this.atOccurrence){var r=e.splitLines(i);this.doc.replaceRange(r,this.pos.from,this.pos.to),this.pos.to=n(this.pos.from.line+r.length-1,r[r.length-1].length+(1==r.length?this.pos.from.ch:0))}}},e.defineExtension("getSearchCursor",function(e,r,n){return new i(this.doc,e,r,n)}),e.defineDocExtension("getSearchCursor",function(e,r,n){return new i(this,e,r,n)}),e.defineExtension("selectMatches",function(i,r){for(var n,o=[],t=this.getSearchCursor(i,this.getCursor("from"),r);(n=t.findNext())&&!(e.cmpPos(t.to(),this.getCursor("to"))>0);)o.push({anchor:t.from(),head:t.to()});o.length&&this.setSelections(o,0)})})},{codemirror:void 0}],10:[function(i,r){!function(i){function n(){try{return E in i&&i[E]}catch(e){return!1}}function o(e){return function(){var i=Array.prototype.slice.call(arguments,0);i.unshift(s),u.appendChild(s),s.addBehavior("#default#userData"),s.load(E);var r=e.apply(a,i);return u.removeChild(s),r}}function t(e){return e.replace(/^d/,"___$&").replace(N,"___")}var s,a={},p=i.document,E="localStorage",l="script";if(a.disabled=!1,a.set=function(){},a.get=function(){},a.remove=function(){},a.clear=function(){},a.transact=function(e,i,r){var n=a.get(e);null==r&&(r=i,i=null),"undefined"==typeof n&&(n=i||{}),r(n),a.set(e,n)},a.getAll=function(){},a.forEach=function(){},a.serialize=function(e){return JSON.stringify(e)},a.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(i){return e||void 0}},n())s=i[E],a.set=function(e,i){return void 0===i?a.remove(e):(s.setItem(e,a.serialize(i)),i)},a.get=function(e){return a.deserialize(s.getItem(e))},a.remove=function(e){s.removeItem(e)},a.clear=function(){s.clear()},a.getAll=function(){var e={};return a.forEach(function(i,r){e[i]=r}),e},a.forEach=function(e){for(var i=0;i<s.length;i++){var r=s.key(i);e(r,a.get(r))}};else if(p.documentElement.addBehavior){var u,c;try{c=new ActiveXObject("htmlfile"),c.open(),c.write("<"+l+">document.w=window</"+l+'><iframe src="/favicon.ico"></iframe>'),c.close(),u=c.w.frames[0].document,s=u.createElement("div")}catch(d){s=p.createElement("div"),u=p.body}var N=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");a.set=o(function(e,i,r){return i=t(i),void 0===r?a.remove(i):(e.setAttribute(i,a.serialize(r)),e.save(E),r)}),a.get=o(function(e,i){return i=t(i),a.deserialize(e.getAttribute(i))}),a.remove=o(function(e,i){i=t(i),e.removeAttribute(i),e.save(E)}),a.clear=o(function(e){var i=e.XMLDocument.documentElement.attributes;e.load(E);for(var r,n=0;r=i[n];n++)e.removeAttribute(r.name);e.save(E)}),a.getAll=function(){var e={};return a.forEach(function(i,r){e[i]=r}),e},a.forEach=o(function(e,i){for(var r,n=e.XMLDocument.documentElement.attributes,o=0;r=n[o];++o)i(r.name,a.deserialize(e.getAttribute(r.name)))})}try{var I="__storejs__";a.set(I,I),a.get(I)!=I&&(a.disabled=!0),a.remove(I)}catch(d){a.disabled=!0}a.enabled=!a.disabled,"undefined"!=typeof r&&r.exports&&this.module!==r?r.exports=a:"function"==typeof e&&e.amd?e(a):i.store=a}(Function("return this")())},{}],11:[function(e,i){i.exports={name:"yasgui-utils",version:"1.4.1",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:"Laurens Rietveld",maintainers:[{name:"Laurens Rietveld",email:"laurens.rietveld@gmail.com",web:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"}}},{}],12:[function(e,i){window.console=window.console||{log:function(){}},i.exports={storage:e("./storage.js"),svg:e("./svg.js"),version:{"yasgui-utils":e("../package.json").version}}},{"../package.json":11,"./storage.js":13,"./svg.js":14}],13:[function(e,i){{var r=e("store"),n={day:function(){return 864e5},month:function(){30*n.day()},year:function(){12*n.month()}};i.exports={set:function(e,i,o){"string"==typeof o&&(o=n[o]()),i.documentElement&&(i=(new XMLSerializer).serializeToString(i.documentElement)),r.set(e,{val:i,exp:o,time:(new Date).getTime()})},get:function(e){var i=r.get(e);return i?i.exp&&(new Date).getTime()-i.time>i.exp?null:i.val:null}}}},{store:10}],14:[function(e,i){i.exports={draw:function(e,r,n){if(e){var o=i.exports.getElement(r,n);o&&(e.append?e.append(o):e.appendChild(o))}},getElement:function(e,i){if(e&&0==e.indexOf("<svg")){i.width||(i.width="100%"),i.height||(i.height="100%");var r=new DOMParser,n=r.parseFromString(e,"text/xml"),o=n.documentElement,t=document.createElement("div");return t.style.display="inline-block",t.style.width=i.width,t.style.height=i.height,t.appendChild(o),t}return!1}}},{}],15:[function(e,i){i.exports={name:"yasgui-yasqe",description:"Yet Another SPARQL Query Editor",version:"2.2.1",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasqe.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasqe.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"^0.3.11","gulp-notify":"^1.2.5","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^0.2.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.4",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","browserify-transform-tools":"^1.2.1"},bugs:"https://github.com/YASGUI/YASQE/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"laurens.rietveld@gmail.com",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASQE.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","twitter-bootstrap-3.0.0":"^3.0.0","yasgui-utils":"^1.4.1"},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"}}}},{}],16:[function(e,i){var r=function(){try{return e("jquery")}catch(i){return window.jQuery}}(),n=e("../utils.js"),o=e("yasgui-utils"),t=e("../../lib/trie.js");i.exports=function(e){var i={},a={},p={};e.on("cursorActivity",function(){u(!0)}),e.on("change",function(){var n=[];for(var o in i)i[o].is(":visible")&&n.push(i[o]);if(n.length>0){var t=r(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),s=0;t.is(":visible")&&(s=t.outerWidth()),n.forEach(function(e){e.css("right",s)})}});var E=function(i,r){p[i.name]=new t;for(var s=0;s<r.length;s++)p[i.name].insert(r[s]);var a=n.getPersistencyId(e,i.persistent);a&&o.storage.set(a,r,"month")},l=function(i,r){var t=a[i]=new r(e,i);if(t.name=i,t.bulk){var s=function(e){e&&e instanceof Array&&e.length>0&&E(t,e)};if(t.get instanceof Array)s(t.get);else{var p=null,l=n.getPersistencyId(e,t.persistent);l&&(p=o.storage.get(l)),p&&p.length>0?s(p):t.get instanceof Function&&(t.async?t.get(null,s):s(t.get()))}}},u=function(i){if(!e.somethingSelected()){var n=function(r){if(i&&(!r.autoShow||!r.bulk&&r.async))return!1;var n={closeCharacters:/(?=a)b/,completeSingle:!1};!r.bulk&&r.async&&(n.async=!0);{var o=function(e,i){return c(r,i)};YASQE.showHint(e,o,n)}return!0};for(var o in a)if(-1!=r.inArray(o,e.options.autocompleters)){var t=a[o];if(t.isValidCompletionPosition)if(t.isValidCompletionPosition()){if(!t.callbacks||!t.callbacks.validPosition||t.callbacks.validPosition(e,t)!==!1){var s=n(t);if(s)break}}else t.callbacks&&t.callbacks.invalidPosition&&t.callbacks.invalidPosition(e,t)}}},c=function(i,r){var n=function(e){var r=e.autocompletionString||e.string,n=[];if(p[i.name])n=p[i.name].autoComplete(r);else if("function"==typeof i.get&&0==i.async)n=i.get(r);else if("object"==typeof i.get)for(var o=r.length,t=0;t<i.get.length;t++){var s=i.get[t];s.slice(0,o)==r&&n.push(s)}return d(n,i,e)},o=e.getCompleteToken();if(i.preProcessToken&&(o=i.preProcessToken(o)),o){if(i.bulk||!i.async)return n(o);var t=function(e){r(d(e,i,o))};i.get(o,t)}},d=function(i,r,n){for(var o=[],t=0;t<i.length;t++){var a=i[t];r.postProcessToken&&(a=r.postProcessToken(n,a)),o.push({text:a,displayText:a,hint:s})}var p=e.getCursor(),E={completionToken:n.string,list:o,from:{line:p.line,ch:n.start},to:{line:p.line,ch:n.end}};if(r.callbacks)for(var l in r.callbacks)r.callbacks[l]&&e.on(E,l,r.callbacks[l]);return E};return{init:l,completers:a,notifications:{getEl:function(e){return r(i[e.name])},show:function(e,n){n.autoshow||(i[n.name]||(i[n.name]=r("<div class='completionNotification'></div>")),i[n.name].show().text("Press "+(-1!=navigator.userAgent.indexOf("Mac OS X")?"CMD":"CTRL")+" - <spacebar> to autocomplete").appendTo(r(e.getWrapperElement())))},hide:function(e,r){i[r.name]&&i[r.name].hide()}},autoComplete:u,getTrie:function(e){return"string"==typeof e?p[e]:p[e.name]}}};var s=function(e,i,r){r.text!=e.getTokenAt(e.getCursor()).string&&e.replaceRange(r.text,i.from,i.to)}},{"../../lib/trie.js":4,"../utils.js":28,jquery:void 0,"yasgui-utils":12}],17:[function(e,i){!function(){try{return e("jquery")}catch(i){return window.jQuery}}();i.exports=function(r,n){return{isValidCompletionPosition:function(){return i.exports.isValidCompletionPosition(r)},get:function(i,n){return e("./utils").fetchFromLov(r,this,i,n)},preProcessToken:function(e){return i.exports.preProcessToken(r,e)},postProcessToken:function(e,n){return i.exports.postProcessToken(r,e,n)},async:!0,bulk:!1,autoShow:!1,persistent:n,callbacks:{validPosition:r.autocompleters.notifications.show,invalidPosition:r.autocompleters.notifications.hide}}},i.exports.isValidCompletionPosition=function(e){var i=e.getCompleteToken();if(0==i.string.indexOf("?"))return!1;var r=e.getCursor(),n=e.getPreviousNonWsToken(r.line,i);return"a"==n.string?!0:"rdf:type"==n.string?!0:"rdfs:domain"==n.string?!0:"rdfs:range"==n.string?!0:!1},i.exports.preProcessToken=function(i,r){return e("./utils.js").preprocessResourceTokenForCompletion(i,r)},i.exports.postProcessToken=function(i,r,n){return e("./utils.js").postprocessResourceTokenForCompletion(i,r,n)}},{"./utils":20,"./utils.js":20,jquery:void 0}],18:[function(e,i){var r=function(){try{return e("jquery")}catch(i){return window.jQuery}}(),n={"string-2":"prefixed",atom:"var"};i.exports=function(e,n){return e.on("change",function(){i.exports.appendPrefixIfNeeded(e,n)}),{isValidCompletionPosition:function(){return i.exports.isValidCompletionPosition(e)},get:function(e,i){r.get("http://prefix.cc/popular/all.file.json",function(e){var r=[];for(var n in e)if("bif"!=n){var o=n+": <"+e[n]+">";r.push(o)}r.sort(),i(r)})},preProcessToken:function(r){return i.exports.preprocessPrefixTokenForCompletion(e,r)},async:!0,bulk:!0,autoShow:!0,persistent:n}},i.exports.isValidCompletionPosition=function(e){var i=e.getCursor(),n=e.getTokenAt(i);if(e.getLine(i.line).length>i.ch)return!1;if("ws"!=n.type&&(n=e.getCompleteToken()),0==!n.string.indexOf("a")&&-1==r.inArray("PNAME_NS",n.state.possibleCurrent))return!1;var o=e.getPreviousNonWsToken(i.line,n);return o&&"PREFIX"==o.string.toUpperCase()?!0:!1},i.exports.preprocessPrefixTokenForCompletion=function(e,i){var r=e.getPreviousNonWsToken(e.getCursor().line,i);return r&&r.string&&":"==r.string.slice(-1)&&(i={start:r.start,end:i.end,string:r.string+" "+i.string,state:i.state}),i},i.exports.appendPrefixIfNeeded=function(e,i){if(e.autocompleters.getTrie(i)&&e.options.autocompleters&&-1!=e.options.autocompleters.indexOf(i)){var r=e.getCursor(),o=e.getTokenAt(r);if("prefixed"==n[o.type]){var t=o.string.indexOf(":");if(-1!==t){var s=e.getPreviousNonWsToken(r.line,o).string.toUpperCase(),a=e.getTokenAt({line:r.line,ch:o.start});if("PREFIX"!=s&&("ws"==a.type||null==a.type)){var p=o.string.substring(0,t+1),E=e.getPrefixesFromQuery();if(null==E[p]){var l=e.autocompleters.getTrie(i).autoComplete(p);l.length>0&&e.addPrefixes(l[0])}}}}}}},{jquery:void 0}],19:[function(e,i){var r=function(){try{return e("jquery")}catch(i){return window.jQuery}}();i.exports=function(r,n){return{isValidCompletionPosition:function(){return i.exports.isValidCompletionPosition(r)},get:function(i,n){return e("./utils").fetchFromLov(r,this,i,n)},preProcessToken:function(e){return i.exports.preProcessToken(r,e)},postProcessToken:function(e,n){return i.exports.postProcessToken(r,e,n)},async:!0,bulk:!1,autoShow:!1,persistent:n,callbacks:{validPosition:r.autocompleters.notifications.show,invalidPosition:r.autocompleters.notifications.hide}}},i.exports.isValidCompletionPosition=function(e){var i=e.getCompleteToken();if(0==i.string.length)return!1;if(0==i.string.indexOf("?"))return!1;if(r.inArray("a",i.state.possibleCurrent)>=0)return!0;var n=e.getCursor(),o=e.getPreviousNonWsToken(n.line,i);return"rdfs:subPropertyOf"==o.string?!0:!1},i.exports.preProcessToken=function(i,r){return e("./utils.js").preprocessResourceTokenForCompletion(i,r)},i.exports.postProcessToken=function(i,r,n){return e("./utils.js").postprocessResourceTokenForCompletion(i,r,n)}},{"./utils":20,"./utils.js":20,jquery:void 0}],20:[function(e,i){var r=function(){try{return e("jquery")}catch(i){return window.jQuery}}(),n=(e("./utils.js"),e("yasgui-utils")),o=function(e,i){var r=e.getPrefixesFromQuery();if(0==!i.string.indexOf("<")&&(i.tokenPrefix=i.string.substring(0,i.string.indexOf(":")+1),null!=r[i.tokenPrefix]&&(i.tokenPrefixUri=r[i.tokenPrefix])),i.autocompletionString=i.string.trim(),0==!i.string.indexOf("<")&&i.string.indexOf(":")>-1)for(var n in r)if(r.hasOwnProperty(n)&&0==i.string.indexOf(n)){i.autocompletionString=r[n],i.autocompletionString+=i.string.substring(n.length);break}return 0==i.autocompletionString.indexOf("<")&&(i.autocompletionString=i.autocompletionString.substring(1)),-1!==i.autocompletionString.indexOf(">",i.length-1)&&(i.autocompletionString=i.autocompletionString.substring(0,i.autocompletionString.length-1)),i},t=function(e,i,r){return r=i.tokenPrefix&&i.autocompletionString&&i.tokenPrefixUri?i.tokenPrefix+r.substring(i.tokenPrefixUri.length):"<"+r+">"},s=function(i,o,t,s){if(!t||!t.string||0==t.string.trim().length)return i.autocompleters.notifications.getEl(o).empty().append("Nothing to autocomplete yet!"),!1;var a=50,p={q:t.autocompletionString,page:1};p.type="classes"==o.name?"class":"property";var E=[],l="",u=function(){l="http://lov.okfn.org/dataset/lov/api/v2/autocomplete/terms?"+r.param(p)};u();var c=function(){p.page++,u()},d=function(){r.get(l,function(e){for(var n=0;n<e.results.length;n++)E.push(r.isArray(e.results[n].uri)&&e.results[n].uri.length>0?e.results[n].uri[0]:e.results[n].uri);E.length<e.total_results&&E.length<a?(c(),d()):(E.length>0?i.autocompleters.notifications.hide(i,o):i.autocompleters.notifications.getEl(o).text("0 matches found..."),s(E))}).fail(function(){i.autocompleters.notifications.getEl(o).empty().append("Failed fetching suggestions..")})};i.autocompleters.notifications.getEl(o).empty().append(r("<span>Fetchting autocompletions </span>")).append(r(n.svg.getElement(e("../imgs.js").loader,{width:"18px",height:"18px"})).css("vertical-align","middle")),d()
};i.exports={fetchFromLov:s,preprocessResourceTokenForCompletion:o,postprocessResourceTokenForCompletion:t}},{"../imgs.js":23,"./utils.js":20,jquery:void 0,"yasgui-utils":12}],21:[function(e,i){var r=function(){try{return e("jquery")}catch(i){return window.jQuery}}();i.exports=function(e){return{isValidCompletionPosition:function(){var i=e.getTokenAt(e.getCursor());return"ws"!=i.type&&(i=e.getCompleteToken(i),i&&0==i.string.indexOf("?"))?!0:!1},get:function(i){if(0==i.trim().length)return[];var n={};r(e.getWrapperElement()).find(".cm-atom").each(function(){var e=this.innerHTML;if(0==e.indexOf("?")){var o=r(this).next(),t=o.attr("class");if(t&&o.attr("class").indexOf("cm-atom")>=0&&(e+=o.text()),e.length<=1)return;if(0!==e.indexOf(i))return;if(e==i)return;n[e]=!0}});var o=[];for(var t in n)o.push(t);return o.sort(),o},async:!1,bulk:!1,autoShow:!0}}},{jquery:void 0}],22:[function(e,i){var r=function(){try{return e("jquery")}catch(i){return window.jQuery}}(),n=e("./sparql.js");i.exports={use:function(e){e.defaults=r.extend(e.defaults,{mode:"sparql11",value:"SELECT * WHERE {\n ?sub ?pred ?obj .\n} \nLIMIT 10",highlightSelectionMatches:{showToken:/\w/},tabMode:"indent",lineNumbers:!0,gutters:["gutterErrorBar","CodeMirror-linenumbers"],matchBrackets:!0,fixedGutter:!0,syntaxErrorCheck:!0,extraKeys:{"Ctrl-Space":e.autoComplete,"Cmd-Space":e.autoComplete,"Ctrl-D":e.deleteLine,"Ctrl-K":e.deleteLine,"Cmd-D":e.deleteLine,"Cmd-K":e.deleteLine,"Ctrl-/":e.commentLines,"Cmd-/":e.commentLines,"Ctrl-Alt-Down":e.copyLineDown,"Ctrl-Alt-Up":e.copyLineUp,"Cmd-Alt-Down":e.copyLineDown,"Cmd-Alt-Up":e.copyLineUp,"Shift-Ctrl-F":e.doAutoFormat,"Shift-Cmd-F":e.doAutoFormat,"Ctrl-]":e.indentMore,"Cmd-]":e.indentMore,"Ctrl-[":e.indentLess,"Cmd-[":e.indentLess,"Ctrl-S":e.storeQuery,"Cmd-S":e.storeQuery,"Ctrl-Enter":n.executeQuery,"Cmd-Enter":n.executeQuery,F11:function(e){e.setOption("fullScreen",!e.getOption("fullScreen"))},Esc:function(e){e.getOption("fullScreen")&&e.setOption("fullScreen",!1)}},cursorHeight:.9,createShareLink:e.createShareLink,consumeShareLink:e.consumeShareLink,persistent:function(e){return"queryVal_"+r(e.getWrapperElement()).closest("[id]").attr("id")},sparql:{showQueryButton:!1,endpoint:"http://dbpedia.org/sparql",requestMethod:"POST",acceptHeaderGraph:"text/turtle,*/*;q=0.9",acceptHeaderSelect:"application/sparql-results+json,*/*;q=0.9",acceptHeaderUpdate:"text/plain,*/*;q=0.9",namedGraphs:[],defaultGraphs:[],args:[],headers:{},callbacks:{beforeSend:null,complete:null,error:null,success:null},handlers:{}}})}}},{"./sparql.js":25,jquery:void 0}],23:[function(e,i){i.exports={loader:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" fill="black"> <circle cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(45 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.125s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(90 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.25s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(135 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.375s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(225 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.625s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(270 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.75s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(315 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.875s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle></svg>',query:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 80 80" enable-background="new 0 0 80 80" xml:space="preserve"><g id="Layer_1"></g><g id="Layer_2"> <path d="M64.622,2.411H14.995c-6.627,0-12,5.373-12,12v49.897c0,6.627,5.373,12,12,12h49.627c6.627,0,12-5.373,12-12V14.411 C76.622,7.783,71.249,2.411,64.622,2.411z M24.125,63.906V15.093L61,39.168L24.125,63.906z"/></g></svg>',queryInvalid:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 73.627 73.897" enable-background="new 0 0 80 80" xml:space="preserve" ><g id="Layer_1" transform="translate(-2.995,-2.411)" /><g id="Layer_2" transform="translate(-2.995,-2.411)"><path d="M 64.622,2.411 H 14.995 c -6.627,0 -12,5.373 -12,12 v 49.897 c 0,6.627 5.373,12 12,12 h 49.627 c 6.627,0 12,-5.373 12,-12 V 14.411 c 0,-6.628 -5.373,-12 -12,-12 z M 24.125,63.906 V 15.093 L 61,39.168 24.125,63.906 z" id="path6" inkscape:connector-curvature="0" /></g><g transform="matrix(0.76805408,0,0,0.76805408,-0.90231954,-2.0060895)" id="g3"><path style="fill:#c02608;fill-opacity:1" inkscape:connector-curvature="0" d="m 88.184,81.468 c 1.167,1.167 1.167,3.075 0,4.242 l -2.475,2.475 c -1.167,1.167 -3.076,1.167 -4.242,0 l -69.65,-69.65 c -1.167,-1.167 -1.167,-3.076 0,-4.242 l 2.476,-2.476 c 1.167,-1.167 3.076,-1.167 4.242,0 l 69.649,69.651 z" id="path5" /></g><g transform="matrix(0.76805408,0,0,0.76805408,-0.90231954,-2.0060895)" id="g7"><path style="fill:#c02608;fill-opacity:1" inkscape:connector-curvature="0" d="m 18.532,88.184 c -1.167,1.166 -3.076,1.166 -4.242,0 l -2.475,-2.475 c -1.167,-1.166 -1.167,-3.076 0,-4.242 l 69.65,-69.651 c 1.167,-1.167 3.075,-1.167 4.242,0 l 2.476,2.476 c 1.166,1.167 1.166,3.076 0,4.242 l -69.651,69.65 z" id="path9" /></g></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g id="Captions"></g><g id="Your_Icon"> <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',share:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="Icons" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve"><path id="ShareThis" d="M36.764,50c0,0.308-0.07,0.598-0.088,0.905l32.247,16.119c2.76-2.338,6.293-3.797,10.195-3.797 C87.89,63.228,95,70.338,95,79.109C95,87.89,87.89,95,79.118,95c-8.78,0-15.882-7.11-15.882-15.891c0-0.316,0.07-0.598,0.088-0.905 L31.077,62.085c-2.769,2.329-6.293,3.788-10.195,3.788C12.11,65.873,5,58.771,5,50c0-8.78,7.11-15.891,15.882-15.891 c3.902,0,7.427,1.468,10.195,3.797l32.247-16.119c-0.018-0.308-0.088-0.598-0.088-0.914C63.236,12.11,70.338,5,79.118,5 C87.89,5,95,12.11,95,20.873c0,8.78-7.11,15.891-15.882,15.891c-3.911,0-7.436-1.468-10.195-3.806L36.676,49.086 C36.693,49.394,36.764,49.684,36.764,50z"/></svg>',warning:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" viewBox="0 0 66.399998 66.399998" enable-background="new 0 0 69.3 69.3" xml:space="preserve" height="100%" width="100%" inkscape:version="0.48.4 r9939" ><g id="g3" transform="translate(-1.5,-1.5)" style="fill:#ff0000"><path d="M 34.7,1.5 C 16.4,1.5 1.5,16.4 1.5,34.7 1.5,53 16.4,67.9 34.7,67.9 53,67.9 67.9,53 67.9,34.7 67.9,16.4 53,1.5 34.7,1.5 z m 0,59.4 C 20.2,60.9 8.5,49.1 8.5,34.7 8.5,20.2 20.3,8.5 34.7,8.5 c 14.4,0 26.2,11.8 26.2,26.2 0,14.4 -11.8,26.2 -26.2,26.2 z" id="path5" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.6,47.1 c -1.4,0 -2.5,0.5 -3.5,1.5 -0.9,1 -1.4,2.2 -1.4,3.6 0,1.6 0.5,2.8 1.5,3.8 1,0.9 2.1,1.3 3.4,1.3 1.3,0 2.4,-0.5 3.4,-1.4 1,-0.9 1.5,-2.2 1.5,-3.7 0,-1.4 -0.5,-2.6 -1.4,-3.6 -0.9,-1 -2.1,-1.5 -3.5,-1.5 z" id="path7" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.8,13.9 c -1.5,0 -2.8,0.5 -3.7,1.6 -0.9,1 -1.4,2.4 -1.4,4.2 0,1.1 0.1,2.9 0.2,5.6 l 0.8,13.1 c 0.2,1.8 0.4,3.2 0.9,4.1 0.5,1.2 1.5,1.8 2.9,1.8 1.3,0 2.3,-0.7 2.9,-1.9 0.5,-1 0.7,-2.3 0.9,-4 L 39.4,25 c 0.1,-1.3 0.2,-2.5 0.2,-3.8 0,-2.2 -0.3,-3.9 -0.8,-5.1 -0.5,-1 -1.6,-2.2 -4,-2.2 z" id="path9" inkscape:connector-curvature="0" style="fill:#ff0000" /></g></svg>'}},{}],24:[function(e,i){var r=function(e,i){if("string"==typeof i)n(e,i);else for(var r in i)n(r+" "+i)},n=function(e,i){for(var r=null,n=0,o=e.lineCount(),t=0;o>t;t++){var a=e.getNextNonWsToken(t);null==a||"PREFIX"!=a.string&&"BASE"!=a.string||(r=a,n=t)}if(null==r)e.replaceRange("PREFIX "+i+"\n",{line:0,ch:0});else{var p=s(e,n);e.replaceRange("\n"+p+"PREFIX "+i,{line:n})}},o=function(e,i){var r=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")};for(var n in i)e.setValue(e.getValue().replace(new RegExp("PREFIX\\s*"+n+"\\s*"+r(i[n])+"\\s*","ig"),""))},t=function(e){for(var i={},r=!0,n=function(o,s){if(r){s||(s=1);var a=e.getNextNonWsToken(t,s);if(a)if(-1==a.state.possibleCurrent.indexOf("PREFIX")&&-1==a.state.possibleNext.indexOf("PREFIX")&&(r=!1),"PREFIX"==a.string.toUpperCase()){var p=e.getNextNonWsToken(t,a.end+1);if(p){var E=e.getNextNonWsToken(t,p.end+1);if(E){var l=E.string;0==l.indexOf("<")&&(l=l.substring(1)),">"==l.slice(-1)&&(l=l.substring(0,l.length-1)),i[p.string]=l,n(o,E.end+1)}else n(o,p.end+1)}else n(o,a.end+1)}else n(o,a.end+1)}},o=e.lineCount(),t=0;o>t&&r;t++)n(t);return i},s=function(e,i,r){void 0==r&&(r=1);var n=e.getTokenAt({line:i,ch:r});return null==n||void 0==n||"ws"!=n.type?"":n.string+s(e,i,n.end+1)};i.exports={addPrefixes:r,getPrefixesFromQuery:t,removePrefixes:o}},{}],25:[function(e,i){var r=function(){try{return e("jquery")}catch(i){return window.jQuery}}();i.exports={use:function(e){e.executeQuery=function(i,o){var t="function"==typeof o?o:null,s="object"==typeof o?o:{},a=i.getQueryMode();if(i.options.sparql&&(s=r.extend({},i.options.sparql,s)),s.handlers&&r.extend(!0,s.callbacks,s.handlers),s.endpoint&&0!=s.endpoint.length){var p={url:"function"==typeof s.endpoint?s.endpoint(i):s.endpoint,type:"function"==typeof s.requestMethod?s.requestMethod(i):s.requestMethod,data:[{name:a,value:i.getValue()}],headers:{Accept:n(i,s)}},E=!1;if(s.callbacks)for(var l in s.callbacks)s.callbacks[l]&&(E=!0,p[l]=s.callbacks[l]);if(E||t){if(t&&(p.complete=t),s.namedGraphs&&s.namedGraphs.length>0)for(var u="query"==a?"named-graph-uri":"using-named-graph-uri ",c=0;c<s.namedGraphs.length;c++)p.data.push({name:u,value:s.namedGraphs[c]});if(s.defaultGraphs&&s.defaultGraphs.length>0)for(var u="query"==a?"default-graph-uri":"using-graph-uri ",c=0;c<s.defaultGraphs.length;c++)p.data.push({name:u,value:s.defaultGraphs[c]});s.headers&&!r.isEmptyObject(s.headers)&&r.extend(p.headers,s.headers),s.args&&s.args.length>0&&r.merge(p.data,s.args),e.updateQueryButton(i,"busy");var d=function(){e.updateQueryButton(i)};if(p.complete){var N=p.complete;p.complete=function(e,i){N(e,i),d()}}else p.complete=d;i.xhr=r.ajax(p)}}}}};var n=function(e,i){var r=null;if(!i.acceptHeader||i.acceptHeaderGraph||i.acceptHeaderSelect||i.acceptHeaderUpdate)if("update"==e.getQueryMode())r="function"==typeof i.acceptHeader?i.acceptHeaderUpdate(e):i.acceptHeaderUpdate;else{var n=e.getQueryType();r="DESCRIBE"==n||"CONSTRUCT"==n?"function"==typeof i.acceptHeaderGraph?i.acceptHeaderGraph(e):i.acceptHeaderGraph:"function"==typeof i.acceptHeaderSelect?i.acceptHeaderSelect(e):i.acceptHeaderSelect}else r="function"==typeof i.acceptHeader?i.acceptHeader(e):i.acceptHeader;return r}},{jquery:void 0}],26:[function(e,i){var r=function(e,i,n){n||(n=e.getCursor()),i||(i=e.getTokenAt(n));var o=e.getTokenAt({line:n.line,ch:i.start});return null!=o.type&&"ws"!=o.type&&null!=i.type&&"ws"!=i.type?(i.start=o.start,i.string=o.string+i.string,r(e,i,{line:n.line,ch:o.start})):null!=i.type&&"ws"==i.type?(i.start=i.start+1,i.string=i.string.substring(1),i):i},n=function(e,i,r){var o=e.getTokenAt({line:i,ch:r.start});return null!=o&&"ws"==o.type&&(o=n(e,i,o)),o},o=function(e,i,r){void 0==r&&(r=1);var n=e.getTokenAt({line:i,ch:r});return null==n||void 0==n||n.end<r?null:"ws"==n.type?o(e,i,n.end+1):n};i.exports={getPreviousNonWsToken:n,getCompleteToken:r,getNextNonWsToken:o}},{}],27:[function(e,i){{var r=function(){try{return e("jquery")}catch(i){return window.jQuery}}();e("./utils.js")}i.exports=function(e,i,n){var o,i=r(i);i.hover(function(){"function"==typeof n&&(n=n()),o=r("<div>").addClass("yasqe_tooltip").html(n).appendTo(i),t()},function(){r(".yasqe_tooltip").remove()});var t=function(){r(e.getWrapperElement()).offset().top>=o.offset().top&&(o.css("bottom","auto"),o.css("top","26px"))}}},{"./utils.js":28,jquery:void 0}],28:[function(e,i){var r=function(){try{return e("jquery")}catch(i){return window.jQuery}}(),n=function(e,i){var r=!1;try{void 0!==e[i]&&(r=!0)}catch(n){}return r},o=function(e,i){var r=null;return i&&(r="string"==typeof i?i:i(e)),r},t=function(){function e(e){var i,n,o;return i=r(e).offset(),n=r(e).width(),o=r(e).height(),[[i.left,i.left+n],[i.top,i.top+o]]}function i(e,i){var r,n;return r=e[0]<i[0]?e:i,n=e[0]<i[0]?i:e,r[1]>n[0]||r[0]===n[0]}return function(r,n){var o=e(r),t=e(n);return i(o[0],t[0])&&i(o[1],t[1])}}();i.exports={keyExists:n,getPersistencyId:o,elementsOverlap:t}},{jquery:void 0}]},{},[1])(1)});
//# sourceMappingURL=yasqe.min.js.map | dlueth/jsdelivr | files/yasqe/2.2.1/yasqe.min.js | JavaScript | mit | 226,210 |
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.YASR=e()}}(function(){var e;return function t(e,r,n){function a(i,s){if(!r[i]){if(!e[i]){var l="function"==typeof require&&require;if(!s&&l)return l(i,!0);if(o)return o(i,!0);var u=new Error("Cannot find module '"+i+"'");throw u.code="MODULE_NOT_FOUND",u}var c=r[i]={exports:{}};e[i][0].call(c.exports,function(t){var r=e[i][1][t];return a(r?r:t)},c,c.exports,t,e,r,n)}return r[i].exports}for(var o="function"==typeof require&&require,i=0;i<n.length;i++)a(n[i]);return a}({1:[function(e,t){"use strict";var r=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),n=e("yasgui-utils");console=console||{log:function(){}};var a=t.exports=function(t,s,l){var u={};u.options=r.extend(!0,{},a.defaults,s),u.container=r("<div class='yasr'></div>").appendTo(t),u.header=r("<div class='yasr_header'></div>").appendTo(u.container),u.resultsContainer=r("<div class='yasr_results'></div>").appendTo(u.container),u.plugins={};for(var c in a.plugins)u.plugins[c]=new a.plugins[c](u);if(u.draw=function(e){if(!u.results)return!1;if(e||(e=u.options.output),e in u.plugins&&u.plugins[e].canHandleResults(u))return r(u.resultsContainer).empty(),u.plugins[e].draw(),!0;var t=null,n=-1;for(var a in u.plugins)if(u.plugins[a].canHandleResults(u)){var o=u.plugins[a].getPriority;"function"==typeof o&&(o=o(u)),null!=o&&void 0!=o&&o>n&&(n=o,t=a)}return t?(r(u.resultsContainer).empty(),u.plugins[t].draw(),!0):!1},u.somethingDrawn=function(){return!u.resultsContainer.is(":empty")},u.setResponse=function(t){try{u.results=e("./parsers/wrapper.js")(t)}catch(r){u.results=r}if(u.draw(),u.options.persistency&&u.options.persistency.results&&u.results.getOriginalResponseAsString&&u.results.getOriginalResponseAsString().length<u.options.persistency.results.maxSize){var a="string"==typeof u.options.persistency.results.id?u.options.persistency.results.id:u.options.persistency.results.id(u);n.storage.set(a,u.results.getOriginalResponse(),"month")}},u.options.persistency&&u.options.persistency.outputSelector){var d="string"==typeof u.options.persistency.outputSelector?u.options.persistency.outputSelector:u.options.persistency.outputSelector(u);if(d){var f=n.storage.get(d);f&&(u.options.output=f)}}if(!l&&u.options.persistency&&u.options.persistency.results){var d="string"==typeof u.options.persistency.results.id?u.options.persistency.results.id:u.options.persistency.results.id(u);l=n.storage.get(d)}return i(u),l&&u.setResponse(l),o(u),u},o=function(e){var t=e.header.find(".yasr_downloadIcon");t.removeAttr("title");var r=e.plugins[e.options.output];if(r){var n=r.getDownloadInfo?r.getDownloadInfo():null;n?(n.buttonTitle&&t.attr(n.buttonTitle),t.prop("disabled",!1),t.find("path").each(function(){this.style.fill="black"})):(t.prop("disabled",!0).prop("title","Download not supported for this result representation"),t.find("path").each(function(){this.style.fill="gray"}))}},i=function(t){var a=function(){var e=r('<div class="yasr_btnGroup"></div>');r.each(t.plugins,function(a,i){if(!i.hideFromSelection){var s=i.name||a,l=r("<button class='yasr_btn'></button>").text(s).addClass("select_"+a).click(function(){if(e.find("button.selected").removeClass("selected"),r(this).addClass("selected"),t.options.output=a,t.options.persistency&&t.options.persistency.outputSelector){var i="string"==typeof t.options.persistency.outputSelector?t.options.persistency.outputSelector:t.options.persistency.outputSelector(t);n.storage.set(i,t.options.output,"month")}t.draw(),o(t)}).appendTo(e);t.options.output==a&&l.addClass("selected")}}),e.children().length>1&&t.header.append(e)},i=function(){var n=function(e,t){var r=null,n=window.URL||window.webkitURL||window.mozURL||window.msURL;if(n&&Blob){var a=new Blob([e],{type:t});r=n.createObjectURL(a)}return r},a=r("<button class='yasr_btn yasr_downloadIcon'></button>").append(e("yasgui-utils").svg.getElement(e("./imgs.js").download,{width:"15px",height:"15px"})).click(function(){var e=t.plugins[t.options.output];if(e&&e.getDownloadInfo){var a=e.getDownloadInfo(),o=n(a.getContent(),a.contentType?a.contentType:"text/plain"),i=r("<a></a>");i.attr("href",o),i.attr("download",a.filename),i.get(0).click()}});t.header.append(a)};t.options.drawOutputSelector&&a(),t.options.drawDownloadIcon&&i()};a.plugins={},a.registerOutput=function(e,t){a.plugins[e]=t},a.registerOutput("boolean",e("./boolean.js")),a.registerOutput("table",e("./table.js")),a.registerOutput("rawResponse",e("./rawResponse.js")),a.registerOutput("error",e("./error.js")),a.defaults=e("./defaults.js"),a.version={YASR:e("../package.json").version,jquery:r.fn.jquery,"yasgui-utils":e("yasgui-utils").version}},{"../package.json":11,"./boolean.js":13,"./defaults.js":14,"./error.js":15,"./imgs.js":16,"./parsers/wrapper.js":21,"./rawResponse.js":23,"./table.js":24,jquery:void 0,"yasgui-utils":8}],2:[function(){RegExp.escape=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")},function(e){"use strict";e.csv={defaults:{separator:",",delimiter:'"',headers:!0},hooks:{castToScalar:function(e){var t=/\./;if(isNaN(e))return e;if(t.test(e))return parseFloat(e);var r=parseInt(e);return isNaN(r)?null:r}},parsers:{parse:function(e,t){function r(){if(l=0,u="",t.start&&t.state.rowNum<t.start)return s=[],t.state.rowNum++,void(t.state.colNum=1);if(void 0===t.onParseEntry)i.push(s);else{var e=t.onParseEntry(s,t.state);e!==!1&&i.push(e)}s=[],t.end&&t.state.rowNum>=t.end&&(c=!0),t.state.rowNum++,t.state.colNum=1}function n(){if(void 0===t.onParseValue)s.push(u);else{var e=t.onParseValue(u,t.state);e!==!1&&s.push(e)}u="",l=0,t.state.colNum++}var a=t.separator,o=t.delimiter;t.state.rowNum||(t.state.rowNum=1),t.state.colNum||(t.state.colNum=1);var i=[],s=[],l=0,u="",c=!1,d=RegExp.escape(a),f=RegExp.escape(o),p=/(D|S|\n|\r|[^DS\r\n]+)/,m=p.source;return m=m.replace(/S/g,d),m=m.replace(/D/g,f),p=RegExp(m,"gm"),e.replace(p,function(e){if(!c)switch(l){case 0:if(e===a){u+="",n();break}if(e===o){l=1;break}if("\n"===e){n(),r();break}if(/^\r$/.test(e))break;u+=e,l=3;break;case 1:if(e===o){l=2;break}u+=e,l=1;break;case 2:if(e===o){u+=e,l=1;break}if(e===a){n();break}if("\n"===e){n(),r();break}if(/^\r$/.test(e))break;throw new Error("CSVDataError: Illegal State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");case 3:if(e===a){n();break}if("\n"===e){n(),r();break}if(/^\r$/.test(e))break;if(e===o)throw new Error("CSVDataError: Illegal Quote [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]")}}),0!==s.length&&(n(),r()),i},splitLines:function(e,t){function r(){if(i=0,t.start&&t.state.rowNum<t.start)return s="",void t.state.rowNum++;if(void 0===t.onParseEntry)o.push(s);else{var e=t.onParseEntry(s,t.state);e!==!1&&o.push(e)}s="",t.end&&t.state.rowNum>=t.end&&(l=!0),t.state.rowNum++}var n=t.separator,a=t.delimiter;t.state.rowNum||(t.state.rowNum=1);var o=[],i=0,s="",l=!1,u=RegExp.escape(n),c=RegExp.escape(a),d=/(D|S|\n|\r|[^DS\r\n]+)/,f=d.source;return f=f.replace(/S/g,u),f=f.replace(/D/g,c),d=RegExp(f,"gm"),e.replace(d,function(e){if(!l)switch(i){case 0:if(e===n){s+=e,i=0;break}if(e===a){s+=e,i=1;break}if("\n"===e){r();break}if(/^\r$/.test(e))break;s+=e,i=3;break;case 1:if(e===a){s+=e,i=2;break}s+=e,i=1;break;case 2:var o=s.substr(s.length-1);if(e===a&&o===a){s+=e,i=1;break}if(e===n){s+=e,i=0;break}if("\n"===e){r();break}if("\r"===e)break;throw new Error("CSVDataError: Illegal state [Row:"+t.state.rowNum+"]");case 3:if(e===n){s+=e,i=0;break}if("\n"===e){r();break}if("\r"===e)break;if(e===a)throw new Error("CSVDataError: Illegal quote [Row:"+t.state.rowNum+"]");throw new Error("CSVDataError: Illegal state [Row:"+t.state.rowNum+"]");default:throw new Error("CSVDataError: Unknown state [Row:"+t.state.rowNum+"]")}}),""!==s&&r(),o},parseEntry:function(e,t){function r(){if(void 0===t.onParseValue)o.push(s);else{var e=t.onParseValue(s,t.state);e!==!1&&o.push(e)}s="",i=0,t.state.colNum++}var n=t.separator,a=t.delimiter;t.state.rowNum||(t.state.rowNum=1),t.state.colNum||(t.state.colNum=1);var o=[],i=0,s="";if(!t.match){var l=RegExp.escape(n),u=RegExp.escape(a),c=/(D|S|\n|\r|[^DS\r\n]+)/,d=c.source;d=d.replace(/S/g,l),d=d.replace(/D/g,u),t.match=RegExp(d,"gm")}return e.replace(t.match,function(e){switch(i){case 0:if(e===n){s+="",r();break}if(e===a){i=1;break}if("\n"===e||"\r"===e)break;s+=e,i=3;break;case 1:if(e===a){i=2;break}s+=e,i=1;break;case 2:if(e===a){s+=e,i=1;break}if(e===n){r();break}if("\n"===e||"\r"===e)break;throw new Error("CSVDataError: Illegal State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");case 3:if(e===n){r();break}if("\n"===e||"\r"===e)break;if(e===a)throw new Error("CSVDataError: Illegal Quote [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");throw new Error("CSVDataError: Illegal Data [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]");default:throw new Error("CSVDataError: Unknown State [Row:"+t.state.rowNum+"][Col:"+t.state.colNum+"]")}}),r(),o}},toArray:function(t,r,n){var r=void 0!==r?r:{},a={};a.callback=void 0!==n&&"function"==typeof n?n:!1,a.separator="separator"in r?r.separator:e.csv.defaults.separator,a.delimiter="delimiter"in r?r.delimiter:e.csv.defaults.delimiter;var o=void 0!==r.state?r.state:{},r={delimiter:a.delimiter,separator:a.separator,onParseEntry:r.onParseEntry,onParseValue:r.onParseValue,state:o},i=e.csv.parsers.parseEntry(t,r);return a.callback?void a.callback("",i):i},toArrays:function(t,r,n){var r=void 0!==r?r:{},a={};a.callback=void 0!==n&&"function"==typeof n?n:!1,a.separator="separator"in r?r.separator:e.csv.defaults.separator,a.delimiter="delimiter"in r?r.delimiter:e.csv.defaults.delimiter;var o=[],r={delimiter:a.delimiter,separator:a.separator,onParseEntry:r.onParseEntry,onParseValue:r.onParseValue,start:r.start,end:r.end,state:{rowNum:1,colNum:1}};return o=e.csv.parsers.parse(t,r),a.callback?void a.callback("",o):o},toObjects:function(t,r,n){var r=void 0!==r?r:{},a={};a.callback=void 0!==n&&"function"==typeof n?n:!1,a.separator="separator"in r?r.separator:e.csv.defaults.separator,a.delimiter="delimiter"in r?r.delimiter:e.csv.defaults.delimiter,a.headers="headers"in r?r.headers:e.csv.defaults.headers,r.start="start"in r?r.start:1,a.headers&&r.start++,r.end&&a.headers&&r.end++;var o=[],i=[],r={delimiter:a.delimiter,separator:a.separator,onParseEntry:r.onParseEntry,onParseValue:r.onParseValue,start:r.start,end:r.end,state:{rowNum:1,colNum:1},match:!1},s={delimiter:a.delimiter,separator:a.separator,start:1,end:1,state:{rowNum:1,colNum:1}},l=e.csv.parsers.splitLines(t,s),u=e.csv.toArray(l[0],r),o=e.csv.parsers.splitLines(t,r);r.state.colNum=1,r.state.rowNum=u?2:1;for(var c=0,d=o.length;d>c;c++){var f=e.csv.toArray(o[c],r),p={};for(var m in u)p[u[m]]=f[m];i.push(p),r.state.rowNum++}return a.callback?void a.callback("",i):i},fromArrays:function(t,r,n){var r=void 0!==r?r:{},a={};if(a.callback=void 0!==n&&"function"==typeof n?n:!1,a.separator="separator"in r?r.separator:e.csv.defaults.separator,a.delimiter="delimiter"in r?r.delimiter:e.csv.defaults.delimiter,a.escaper="escaper"in r?r.escaper:e.csv.defaults.escaper,a.experimental="experimental"in r?r.experimental:!1,!a.experimental)throw new Error("not implemented");var o=[];for(i in t)o.push(t[i]);return a.callback?void a.callback("",o):o},fromObjects2CSV:function(t,r,n){var r=void 0!==r?r:{},a={};if(a.callback=void 0!==n&&"function"==typeof n?n:!1,a.separator="separator"in r?r.separator:e.csv.defaults.separator,a.delimiter="delimiter"in r?r.delimiter:e.csv.defaults.delimiter,a.experimental="experimental"in r?r.experimental:!1,!a.experimental)throw new Error("not implemented");var o=[];for(i in t)o.push(arrays[i]);return a.callback?void a.callback("",o):o}},e.csvEntry2Array=e.csv.toArray,e.csv2Array=e.csv.toArrays,e.csv2Dictionary=e.csv.toObjects}(jQuery)},{}],3:[function(t,r,n){!function(a){"object"==typeof n&&"object"==typeof r?a(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],a):a(CodeMirror)}(function(e){function t(e,t,n,a){var o=e.getLineHandle(t.line),l=t.ch-1,u=l>=0&&s[o.text.charAt(l)]||s[o.text.charAt(++l)];if(!u)return null;var c=">"==u.charAt(1)?1:-1;if(n&&c>0!=(l==t.ch))return null;var d=e.getTokenTypeAt(i(t.line,l+1)),f=r(e,i(t.line,l+(c>0?1:0)),c,d||null,a);return null==f?null:{from:i(t.line,l),to:f&&f.pos,match:f&&f.ch==u.charAt(0),forward:c>0}}function r(e,t,r,n,a){for(var o=a&&a.maxScanLineLength||1e4,l=a&&a.maxScanLines||1e3,u=[],c=a&&a.bracketRegex?a.bracketRegex:/[(){}[\]]/,d=r>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),f=t.line;f!=d;f+=r){var p=e.getLine(f);if(p){var m=r>0?0:p.length-1,v=r>0?p.length:-1;if(!(p.length>o))for(f==t.line&&(m=t.ch-(0>r?1:0));m!=v;m+=r){var g=p.charAt(m);if(c.test(g)&&(void 0===n||e.getTokenTypeAt(i(f,m+1))==n)){var h=s[g];if(">"==h.charAt(1)==r>0)u.push(g);else{if(!u.length)return{pos:i(f,m),ch:g};u.pop()}}}}}return f-r==(r>0?e.lastLine():e.firstLine())?!1:null}function n(e,r,n){for(var a=e.state.matchBrackets.maxHighlightLineLength||1e3,s=[],l=e.listSelections(),u=0;u<l.length;u++){var c=l[u].empty()&&t(e,l[u].head,!1,n);if(c&&e.getLine(c.from.line).length<=a){var d=c.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";s.push(e.markText(c.from,i(c.from.line,c.from.ch+1),{className:d})),c.to&&e.getLine(c.to.line).length<=a&&s.push(e.markText(c.to,i(c.to.line,c.to.ch+1),{className:d}))}}if(s.length){o&&e.state.focused&&e.display.input.focus();var f=function(){e.operation(function(){for(var e=0;e<s.length;e++)s[e].clear()})};if(!r)return f;setTimeout(f,800)}}function a(e){e.operation(function(){l&&(l(),l=null),l=n(e,!1,e.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),i=e.Pos,s={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;e.defineOption("matchBrackets",!1,function(t,r,n){n&&n!=e.Init&&t.off("cursorActivity",a),r&&(t.state.matchBrackets="object"==typeof r?r:{},t.on("cursorActivity",a))}),e.defineExtension("matchBrackets",function(){n(this,!0)}),e.defineExtension("findMatchingBracket",function(e,r,n){return t(this,e,r,n)}),e.defineExtension("scanForBracket",function(e,t,n,a){return r(this,e,t,n,a)})})},{codemirror:void 0}],4:[function(t,r,n){!function(a){"object"==typeof n&&"object"==typeof r?a(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],a):a(CodeMirror)}(function(e){"use strict";e.defineMode("javascript",function(t,r){function n(e){for(var t,r=!1,n=!1;null!=(t=e.next());){if(!r){if("/"==t&&!n)return;"["==t?n=!0:n&&"]"==t&&(n=!1)}r=!r&&"\\"==t}}function a(e,t,r){return mt=e,vt=r,t}function o(e,t){var r=e.next();if('"'==r||"'"==r)return t.tokenize=i(r),t.tokenize(e,t);if("."==r&&e.match(/^\d+(?:[eE][+\-]?\d+)?/))return a("number","number");if("."==r&&e.match(".."))return a("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(r))return a(r);if("="==r&&e.eat(">"))return a("=>","operator");if("0"==r&&e.eat(/x/i))return e.eatWhile(/[\da-f]/i),a("number","number");if(/\d/.test(r))return e.match(/^\d*(?:\.\d*)?(?:[eE][+\-]?\d+)?/),a("number","number");if("/"==r)return e.eat("*")?(t.tokenize=s,s(e,t)):e.eat("/")?(e.skipToEnd(),a("comment","comment")):"operator"==t.lastType||"keyword c"==t.lastType||"sof"==t.lastType||/^[\[{}\(,;:]$/.test(t.lastType)?(n(e),e.eatWhile(/[gimy]/),a("regexp","string-2")):(e.eatWhile(jt),a("operator","operator",e.current()));if("`"==r)return t.tokenize=l,l(e,t);if("#"==r)return e.skipToEnd(),a("error","error");if(jt.test(r))return e.eatWhile(jt),a("operator","operator",e.current());if(xt.test(r)){e.eatWhile(xt);var o=e.current(),u=kt.propertyIsEnumerable(o)&&kt[o];return u&&"."!=t.lastType?a(u.type,u.style,o):a("variable","variable",o)}}function i(e){return function(t,r){var n,i=!1;if(yt&&"@"==t.peek()&&t.match(Ct))return r.tokenize=o,a("jsonld-keyword","meta");for(;null!=(n=t.next())&&(n!=e||i);)i=!i&&"\\"==n;return i||(r.tokenize=o),a("string","string")}}function s(e,t){for(var r,n=!1;r=e.next();){if("/"==r&&n){t.tokenize=o;break}n="*"==r}return a("comment","comment")}function l(e,t){for(var r,n=!1;null!=(r=e.next());){if(!n&&("`"==r||"$"==r&&e.eat("{"))){t.tokenize=o;break}n=!n&&"\\"==r}return a("quasi","string-2",e.current())}function u(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var r=e.string.indexOf("=>",e.start);if(!(0>r)){for(var n=0,a=!1,o=r-1;o>=0;--o){var i=e.string.charAt(o),s=St.indexOf(i);if(s>=0&&3>s){if(!n){++o;break}if(0==--n)break}else if(s>=3&&6>s)++n;else if(xt.test(i))a=!0;else if(a&&!n){++o;break}}a&&!n&&(t.fatArrowAt=o)}}function c(e,t,r,n,a,o){this.indented=e,this.column=t,this.type=r,this.prev=a,this.info=o,null!=n&&(this.align=n)}function d(e,t){for(var r=e.localVars;r;r=r.next)if(r.name==t)return!0;for(var n=e.context;n;n=n.prev)for(var r=n.vars;r;r=r.next)if(r.name==t)return!0}function f(e,t,r,n,a){var o=e.cc;for(Nt.state=e,Nt.stream=a,Nt.marked=null,Nt.cc=o,Nt.style=t,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);;){var i=o.length?o.pop():wt?k:x;if(i(r,n)){for(;o.length&&o[o.length-1].lex;)o.pop()();return Nt.marked?Nt.marked:"variable"==r&&d(e,n)?"variable-2":t}}}function p(){for(var e=arguments.length-1;e>=0;e--)Nt.cc.push(arguments[e])}function m(){return p.apply(null,arguments),!0}function v(e){function t(t){for(var r=t;r;r=r.next)if(r.name==e)return!0;return!1}var n=Nt.state;if(n.context){if(Nt.marked="def",t(n.localVars))return;n.localVars={name:e,next:n.localVars}}else{if(t(n.globalVars))return;r.globalVars&&(n.globalVars={name:e,next:n.globalVars})}}function g(){Nt.state.context={prev:Nt.state.context,vars:Nt.state.localVars},Nt.state.localVars=Tt}function h(){Nt.state.localVars=Nt.state.context.vars,Nt.state.context=Nt.state.context.prev}function y(e,t){var r=function(){var r=Nt.state,n=r.indented;if("stat"==r.lexical.type)n=r.lexical.indented;else for(var a=r.lexical;a&&")"==a.type&&a.align;a=a.prev)n=a.indented;r.lexical=new c(n,Nt.stream.column(),e,null,r.lexical,t)};return r.lex=!0,r}function w(){var e=Nt.state;e.lexical.prev&&(")"==e.lexical.type&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function b(e){function t(r){return r==e?m():";"==e?p():m(t)}return t}function x(e,t){return"var"==e?m(y("vardef",t.length),Q,b(";"),w):"keyword a"==e?m(y("form"),k,x,w):"keyword b"==e?m(y("form"),x,w):"{"==e?m(y("}"),_,w):";"==e?m():"if"==e?("else"==Nt.state.lexical.info&&Nt.state.cc[Nt.state.cc.length-1]==w&&Nt.state.cc.pop()(),m(y("form"),k,x,w,$)):"function"==e?m(et):"for"==e?m(y("form"),G,x,w):"variable"==e?m(y("stat"),I):"switch"==e?m(y("form"),k,y("}","switch"),b("{"),_,w,w):"case"==e?m(k,b(":")):"default"==e?m(b(":")):"catch"==e?m(y("form"),g,b("("),tt,b(")"),x,w,h):"module"==e?m(y("form"),g,it,h,w):"class"==e?m(y("form"),rt,w):"export"==e?m(y("form"),st,w):"import"==e?m(y("form"),lt,w):p(y("stat"),k,b(";"),w)}function k(e){return C(e,!1)}function j(e){return C(e,!0)}function C(e,t){if(Nt.state.fatArrowAt==Nt.stream.start){var r=t?L:R;if("("==e)return m(g,y(")"),P(H,")"),w,b("=>"),r,h);if("variable"==e)return p(g,H,b("=>"),r,h)}var n=t?T:N;return Et.hasOwnProperty(e)?m(n):"function"==e?m(et,n):"keyword c"==e?m(t?E:S):"("==e?m(y(")"),S,pt,b(")"),w,n):"operator"==e||"spread"==e?m(t?j:k):"["==e?m(y("]"),dt,w,n):"{"==e?V(D,"}",null,n):"quasi"==e?p(M,n):m()}function S(e){return e.match(/[;\}\)\],]/)?p():p(k)}function E(e){return e.match(/[;\}\)\],]/)?p():p(j)}function N(e,t){return","==e?m(k):T(e,t,!1)}function T(e,t,r){var n=0==r?N:T,a=0==r?k:j;return"=>"==e?m(g,r?L:R,h):"operator"==e?/\+\+|--/.test(t)?m(n):"?"==t?m(k,b(":"),a):m(a):"quasi"==e?p(M,n):";"!=e?"("==e?V(j,")","call",n):"."==e?m(q,n):"["==e?m(y("]"),S,b("]"),w,n):void 0:void 0}function M(e,t){return"quasi"!=e?p():"${"!=t.slice(t.length-2)?m(M):m(k,A)}function A(e){return"}"==e?(Nt.marked="string-2",Nt.state.tokenize=l,m(M)):void 0}function R(e){return u(Nt.stream,Nt.state),p("{"==e?x:k)}function L(e){return u(Nt.stream,Nt.state),p("{"==e?x:j)}function I(e){return":"==e?m(w,x):p(N,b(";"),w)}function q(e){return"variable"==e?(Nt.marked="property",m()):void 0}function D(e,t){return"variable"==e||"keyword"==Nt.style?(Nt.marked="property",m("get"==t||"set"==t?z:O)):"number"==e||"string"==e?(Nt.marked=yt?"property":Nt.style+" property",m(O)):"jsonld-keyword"==e?m(O):"["==e?m(k,b("]"),O):void 0}function z(e){return"variable"!=e?p(O):(Nt.marked="property",m(et))}function O(e){return":"==e?m(j):"("==e?p(et):void 0}function P(e,t){function r(n){if(","==n){var a=Nt.state.lexical;return"call"==a.info&&(a.pos=(a.pos||0)+1),m(e,r)}return n==t?m():m(b(t))}return function(n){return n==t?m():p(e,r)}}function V(e,t,r){for(var n=3;n<arguments.length;n++)Nt.cc.push(arguments[n]);return m(y(t,r),P(e,t),w)}function _(e){return"}"==e?m():p(x,_)}function U(e){return bt&&":"==e?m(B):void 0}function B(e){return"variable"==e?(Nt.marked="variable-3",m()):void 0}function Q(){return p(H,U,F,W)}function H(e,t){return"variable"==e?(v(t),m()):"["==e?V(H,"]"):"{"==e?V(Y,"}"):void 0}function Y(e,t){return"variable"!=e||Nt.stream.match(/^\s*:/,!1)?("variable"==e&&(Nt.marked="property"),m(b(":"),H,F)):(v(t),m(F))}function F(e,t){return"="==t?m(j):void 0}function W(e){return","==e?m(Q):void 0}function $(e,t){return"keyword b"==e&&"else"==t?m(y("form","else"),x,w):void 0}function G(e){return"("==e?m(y(")"),X,b(")"),w):void 0}function X(e){return"var"==e?m(Q,b(";"),K):";"==e?m(K):"variable"==e?m(J):p(k,b(";"),K)}function J(e,t){return"in"==t||"of"==t?(Nt.marked="keyword",m(k)):m(N,K)}function K(e,t){return";"==e?m(Z):"in"==t||"of"==t?(Nt.marked="keyword",m(k)):p(k,b(";"),Z)}function Z(e){")"!=e&&m(k)}function et(e,t){return"*"==t?(Nt.marked="keyword",m(et)):"variable"==e?(v(t),m(et)):"("==e?m(g,y(")"),P(tt,")"),w,x,h):void 0}function tt(e){return"spread"==e?m(tt):p(H,U)}function rt(e,t){return"variable"==e?(v(t),m(nt)):void 0}function nt(e,t){return"extends"==t?m(k,nt):"{"==e?m(y("}"),at,w):void 0}function at(e,t){return"variable"==e||"keyword"==Nt.style?(Nt.marked="property","get"==t||"set"==t?m(ot,et,at):m(et,at)):"*"==t?(Nt.marked="keyword",m(at)):";"==e?m(at):"}"==e?m():void 0}function ot(e){return"variable"!=e?p():(Nt.marked="property",m())}function it(e,t){return"string"==e?m(x):"variable"==e?(v(t),m(ct)):void 0}function st(e,t){return"*"==t?(Nt.marked="keyword",m(ct,b(";"))):"default"==t?(Nt.marked="keyword",m(k,b(";"))):p(x)}function lt(e){return"string"==e?m():p(ut,ct)}function ut(e,t){return"{"==e?V(ut,"}"):("variable"==e&&v(t),m())}function ct(e,t){return"from"==t?(Nt.marked="keyword",m(k)):void 0}function dt(e){return"]"==e?m():p(j,ft)}function ft(e){return"for"==e?p(pt,b("]")):","==e?m(P(E,"]")):p(P(j,"]"))}function pt(e){return"for"==e?m(G,pt):"if"==e?m(k,pt):void 0}var mt,vt,gt=t.indentUnit,ht=r.statementIndent,yt=r.jsonld,wt=r.json||yt,bt=r.typescript,xt=r.wordCharacters||/[\w$\xa1-\uffff]/,kt=function(){function e(e){return{type:e,style:"keyword"}}var t=e("keyword a"),r=e("keyword b"),n=e("keyword c"),a=e("operator"),o={type:"atom",style:"atom"},i={"if":e("if"),"while":t,"with":t,"else":r,"do":r,"try":r,"finally":r,"return":n,"break":n,"continue":n,"new":n,"delete":n,"throw":n,"debugger":n,"var":e("var"),"const":e("var"),let:e("var"),"function":e("function"),"catch":e("catch"),"for":e("for"),"switch":e("switch"),"case":e("case"),"default":e("default"),"in":a,"typeof":a,"instanceof":a,"true":o,"false":o,"null":o,undefined:o,NaN:o,Infinity:o,"this":e("this"),module:e("module"),"class":e("class"),"super":e("atom"),"yield":n,"export":e("export"),"import":e("import"),"extends":n};if(bt){var s={type:"variable",style:"variable-3"},l={"interface":e("interface"),"extends":e("extends"),constructor:e("constructor"),"public":e("public"),"private":e("private"),"protected":e("protected"),"static":e("static"),string:s,number:s,bool:s,any:s};for(var u in l)i[u]=l[u]}return i}(),jt=/[+\-*&%=<>!?|~^]/,Ct=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/,St="([{}])",Et={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,"this":!0,"jsonld-keyword":!0},Nt={state:null,column:null,marked:null,cc:null},Tt={name:"this",next:{name:"arguments"}};return w.lex=!0,{startState:function(e){var t={tokenize:o,lastType:"sof",cc:[],lexical:new c((e||0)-gt,0,"block",!1),localVars:r.localVars,context:r.localVars&&{vars:r.localVars},indented:0};return r.globalVars&&"object"==typeof r.globalVars&&(t.globalVars=r.globalVars),t},token:function(e,t){if(e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation(),u(e,t)),t.tokenize!=s&&e.eatSpace())return null;var r=t.tokenize(e,t);return"comment"==mt?r:(t.lastType="operator"!=mt||"++"!=vt&&"--"!=vt?mt:"incdec",f(t,r,mt,vt,e))},indent:function(t,n){if(t.tokenize==s)return e.Pass;if(t.tokenize!=o)return 0;var a=n&&n.charAt(0),i=t.lexical;if(!/^\s*else\b/.test(n))for(var l=t.cc.length-1;l>=0;--l){var u=t.cc[l];if(u==w)i=i.prev;else if(u!=$)break}"stat"==i.type&&"}"==a&&(i=i.prev),ht&&")"==i.type&&"stat"==i.prev.type&&(i=i.prev);var c=i.type,d=a==c;return"vardef"==c?i.indented+("operator"==t.lastType||","==t.lastType?i.info+1:0):"form"==c&&"{"==a?i.indented:"form"==c?i.indented+gt:"stat"==c?i.indented+("operator"==t.lastType||","==t.lastType?ht||gt:0):"switch"!=i.info||d||0==r.doubleIndentSwitch?i.align?i.column+(d?0:1):i.indented+(d?0:gt):i.indented+(/^(?:case|default)\b/.test(n)?gt:2*gt)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:wt?null:"/*",blockCommentEnd:wt?null:"*/",lineComment:wt?null:"//",fold:"brace",helperType:wt?"json":"javascript",jsonldMode:yt,jsonMode:wt}}),e.registerHelper("wordChars","javascript",/[\w$]/),e.defineMIME("text/javascript","javascript"),e.defineMIME("text/ecmascript","javascript"),e.defineMIME("application/javascript","javascript"),e.defineMIME("application/x-javascript","javascript"),e.defineMIME("application/ecmascript","javascript"),e.defineMIME("application/json",{name:"javascript",json:!0}),e.defineMIME("application/x-json",{name:"javascript",json:!0}),e.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),e.defineMIME("text/typescript",{name:"javascript",typescript:!0}),e.defineMIME("application/typescript",{name:"javascript",typescript:!0})})},{codemirror:void 0}],5:[function(t,r,n){!function(a){"object"==typeof n&&"object"==typeof r?a(function(){try{return t("codemirror")}catch(e){return window.CodeMirror}}()):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],a):a(CodeMirror)}(function(e){"use strict";e.defineMode("xml",function(t,r){function n(e,t){function r(r){return t.tokenize=r,r(e,t)}var n=e.next();if("<"==n)return e.eat("!")?e.eat("[")?e.match("CDATA[")?r(i("atom","]]>")):null:e.match("--")?r(i("comment","-->")):e.match("DOCTYPE",!0,!0)?(e.eatWhile(/[\w\._\-]/),r(s(1))):null:e.eat("?")?(e.eatWhile(/[\w\._\-]/),t.tokenize=i("meta","?>"),"meta"):(j=e.eat("/")?"closeTag":"openTag",t.tokenize=a,"tag bracket");if("&"==n){var o;return o=e.eat("#")?e.eat("x")?e.eatWhile(/[a-fA-F\d]/)&&e.eat(";"):e.eatWhile(/[\d]/)&&e.eat(";"):e.eatWhile(/[\w\.\-:]/)&&e.eat(";"),o?"atom":"error"}return e.eatWhile(/[^&<]/),null}function a(e,t){var r=e.next();if(">"==r||"/"==r&&e.eat(">"))return t.tokenize=n,j=">"==r?"endTag":"selfcloseTag","tag bracket";if("="==r)return j="equals",null;if("<"==r){t.tokenize=n,t.state=d,t.tagName=t.tagStart=null;var a=t.tokenize(e,t);return a?a+" tag error":"tag error"}return/[\'\"]/.test(r)?(t.tokenize=o(r),t.stringStartCol=e.column(),t.tokenize(e,t)):(e.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/),"word")}function o(e){var t=function(t,r){for(;!t.eol();)if(t.next()==e){r.tokenize=a;break}return"string"};return t.isInAttribute=!0,t}function i(e,t){return function(r,a){for(;!r.eol();){if(r.match(t)){a.tokenize=n;break}r.next()}return e}}function s(e){return function(t,r){for(var a;null!=(a=t.next());){if("<"==a)return r.tokenize=s(e+1),r.tokenize(t,r);if(">"==a){if(1==e){r.tokenize=n;break}return r.tokenize=s(e-1),r.tokenize(t,r)}}return"meta"}}function l(e,t,r){this.prev=e.context,this.tagName=t,this.indent=e.indented,this.startOfLine=r,(S.doNotIndent.hasOwnProperty(t)||e.context&&e.context.noIndent)&&(this.noIndent=!0)}function u(e){e.context&&(e.context=e.context.prev)}function c(e,t){for(var r;;){if(!e.context)return;if(r=e.context.tagName,!S.contextGrabbers.hasOwnProperty(r)||!S.contextGrabbers[r].hasOwnProperty(t))return;u(e)}}function d(e,t,r){return"openTag"==e?(r.tagStart=t.column(),f):"closeTag"==e?p:d}function f(e,t,r){return"word"==e?(r.tagName=t.current(),C="tag",g):(C="error",f)}function p(e,t,r){if("word"==e){var n=t.current();return r.context&&r.context.tagName!=n&&S.implicitlyClosed.hasOwnProperty(r.context.tagName)&&u(r),r.context&&r.context.tagName==n?(C="tag",m):(C="tag error",v)}return C="error",v}function m(e,t,r){return"endTag"!=e?(C="error",m):(u(r),d)}function v(e,t,r){return C="error",m(e,t,r)}function g(e,t,r){if("word"==e)return C="attribute",h;if("endTag"==e||"selfcloseTag"==e){var n=r.tagName,a=r.tagStart;return r.tagName=r.tagStart=null,"selfcloseTag"==e||S.autoSelfClosers.hasOwnProperty(n)?c(r,n):(c(r,n),r.context=new l(r,n,a==r.indented)),d}return C="error",g}function h(e,t,r){return"equals"==e?y:(S.allowMissing||(C="error"),g(e,t,r))}function y(e,t,r){return"string"==e?w:"word"==e&&S.allowUnquoted?(C="string",g):(C="error",g(e,t,r))}function w(e,t,r){return"string"==e?w:g(e,t,r)}var b=t.indentUnit,x=r.multilineTagIndentFactor||1,k=r.multilineTagIndentPastTag;null==k&&(k=!0);var j,C,S=r.htmlMode?{autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0}:{autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,caseFold:!1},E=r.alignCDATA;return{startState:function(){return{tokenize:n,state:d,indented:0,tagName:null,tagStart:null,context:null}},token:function(e,t){if(!t.tagName&&e.sol()&&(t.indented=e.indentation()),e.eatSpace())return null;j=null;var r=t.tokenize(e,t);return(r||j)&&"comment"!=r&&(C=null,t.state=t.state(j||r,e,t),C&&(r="error"==C?r+" error":C)),r},indent:function(t,r,o){var i=t.context;if(t.tokenize.isInAttribute)return t.tagStart==t.indented?t.stringStartCol+1:t.indented+b;if(i&&i.noIndent)return e.Pass;if(t.tokenize!=a&&t.tokenize!=n)return o?o.match(/^(\s*)/)[0].length:0;if(t.tagName)return k?t.tagStart+t.tagName.length+2:t.tagStart+b*x;if(E&&/<!\[CDATA\[/.test(r))return 0;var s=r&&/^<(\/)?([\w_:\.-]*)/.exec(r);if(s&&s[1])for(;i;){if(i.tagName==s[2]){i=i.prev;break}if(!S.implicitlyClosed.hasOwnProperty(i.tagName))break;i=i.prev}else if(s)for(;i;){var l=S.contextGrabbers[i.tagName];if(!l||!l.hasOwnProperty(s[2]))break;i=i.prev}for(;i&&!i.startOfLine;)i=i.prev;return i?i.indent+b:0},electricInput:/<\/[\s\w:]+>$/,blockCommentStart:"<!--",blockCommentEnd:"-->",configuration:r.htmlMode?"html":"xml",helperType:r.htmlMode?"html":"xml"}}),e.defineMIME("text/xml","xml"),e.defineMIME("application/xml","xml"),e.mimeModes.hasOwnProperty("text/html")||e.defineMIME("text/html",{name:"xml",htmlMode:!0})
})},{codemirror:void 0}],6:[function(t,r){!function(t){function n(){try{return u in t&&t[u]}catch(e){return!1}}function a(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(i),d.appendChild(i),i.addBehavior("#default#userData"),i.load(u);var r=e.apply(s,t);return d.removeChild(i),r}}function o(e){return e.replace(/^d/,"___$&").replace(m,"___")}var i,s={},l=t.document,u="localStorage",c="script";if(s.disabled=!1,s.set=function(){},s.get=function(){},s.remove=function(){},s.clear=function(){},s.transact=function(e,t,r){var n=s.get(e);null==r&&(r=t,t=null),"undefined"==typeof n&&(n=t||{}),r(n),s.set(e,n)},s.getAll=function(){},s.forEach=function(){},s.serialize=function(e){return JSON.stringify(e)},s.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}},n())i=t[u],s.set=function(e,t){return void 0===t?s.remove(e):(i.setItem(e,s.serialize(t)),t)},s.get=function(e){return s.deserialize(i.getItem(e))},s.remove=function(e){i.removeItem(e)},s.clear=function(){i.clear()},s.getAll=function(){var e={};return s.forEach(function(t,r){e[t]=r}),e},s.forEach=function(e){for(var t=0;t<i.length;t++){var r=i.key(t);e(r,s.get(r))}};else if(l.documentElement.addBehavior){var d,f;try{f=new ActiveXObject("htmlfile"),f.open(),f.write("<"+c+">document.w=window</"+c+'><iframe src="/favicon.ico"></iframe>'),f.close(),d=f.w.frames[0].document,i=d.createElement("div")}catch(p){i=l.createElement("div"),d=l.body}var m=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");s.set=a(function(e,t,r){return t=o(t),void 0===r?s.remove(t):(e.setAttribute(t,s.serialize(r)),e.save(u),r)}),s.get=a(function(e,t){return t=o(t),s.deserialize(e.getAttribute(t))}),s.remove=a(function(e,t){t=o(t),e.removeAttribute(t),e.save(u)}),s.clear=a(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(u);for(var r,n=0;r=t[n];n++)e.removeAttribute(r.name);e.save(u)}),s.getAll=function(){var e={};return s.forEach(function(t,r){e[t]=r}),e},s.forEach=a(function(e,t){for(var r,n=e.XMLDocument.documentElement.attributes,a=0;r=n[a];++a)t(r.name,s.deserialize(e.getAttribute(r.name)))})}try{var v="__storejs__";s.set(v,v),s.get(v)!=v&&(s.disabled=!0),s.remove(v)}catch(p){s.disabled=!0}s.enabled=!s.disabled,"undefined"!=typeof r&&r.exports&&this.module!==r?r.exports=s:"function"==typeof e&&e.amd?e(s):t.store=s}(Function("return this")())},{}],7:[function(e,t){t.exports={name:"yasgui-utils",version:"1.4.1",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:{name:"Laurens Rietveld"},maintainers:[{name:"Laurens Rietveld",email:"laurens.rietveld@gmail.com",url:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"},readme:"A simple utils repo for the YASGUI tools\n",readmeFilename:"README.md",_id:"yasgui-utils@1.4.1",_from:"yasgui-utils@^1.4.1"}},{}],8:[function(e,t){window.console=window.console||{log:function(){}},t.exports={storage:e("./storage.js"),svg:e("./svg.js"),version:{"yasgui-utils":e("../package.json").version}}},{"../package.json":7,"./storage.js":9,"./svg.js":10}],9:[function(e,t){{var r=e("store"),n={day:function(){return 864e5},month:function(){30*n.day()},year:function(){12*n.month()}};t.exports={set:function(e,t,a){"string"==typeof a&&(a=n[a]()),t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement)),r.set(e,{val:t,exp:a,time:(new Date).getTime()})},get:function(e){var t=r.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}}}},{store:6}],10:[function(e,t){t.exports={draw:function(e,r,n){if(e){var a=t.exports.getElement(r,n);a&&(e.append?e.append(a):e.appendChild(a))}},getElement:function(e,t){if(e&&0==e.indexOf("<svg")){t.width||(t.width="100%"),t.height||(t.height="100%");var r=new DOMParser,n=r.parseFromString(e,"text/xml"),a=n.documentElement,o=document.createElement("div");return o.style.display="inline-block",o.style.width=t.width,o.style.height=t.height,o.appendChild(a),o}return!1}}},{}],11:[function(e,t){t.exports={name:"yasgui-yasr",description:"Yet Another SPARQL Resultset GUI",version:"2.1.0",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasr.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasr.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"^0.3.0","gulp-notify":"^1.2.5","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^0.2.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.4",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","yasgui-yasqe":"^2.0.1","twitter-bootstrap-3.0.0":"^3.0.0","browserify-transform-tools":"^1.2.1"},bugs:"https://github.com/YASGUI/YASR/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"laurens.rietveld@gmail.com",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASR.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.2.0","yasgui-utils":"^1.4.1"},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"},"../lib/DataTables/media/js/jquery.dataTables.js":{require:"jquery.dataTables",global:"jQuery"}}}},{}],12:[function(e,t){t.exports=function(e){var t='"',r=",",n="\n",a=e.head.vars,o=e.results.bindings,i=function(){for(var e=0;e<a.length;e++)u(a[e]);csvString+=n},s=function(){for(var e=0;e<o.length;e++)l(o[e]),csvString+=n},l=function(e){for(var t=0;t<a.length;t++){var r=a[t];u(e.hasOwnProperty(r)?e[r].value:"")}},u=function(e){e.replace(t,t+t),c(e)&&(e=t+e+t),csvString+=" "+e+" "+r},c=function(e){var n=!1;return e.match("[\\w|"+r+"|"+t+"]")&&(n=!0),n};return csvString="",i(),s(),csvString}},{}],13:[function(e,t){var r=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),n=t.exports=function(t){var n=r("<div class='booleanResult'></div>"),a=function(){n.empty().appendTo(t.resultsContainer);var a=t.results.getBoolean(),o=null,i=null;a===!0?(o="check",i="True"):a===!1?(o="cross",i="False"):(n.width("140"),i="Could not find boolean value in response"),o&&e("yasgui-utils").svg.draw(n,e("./imgs.js")[o],{width:25,height:25}),r("<span></span>").text(i).appendTo(n)},o=function(){return t.results.getBoolean()===!0||0==t.results.getBoolean()};return{name:null,draw:a,hideFromSelection:!0,getPriority:10,canHandleResults:o}};n.version={"YASR-boolean":e("../package.json").version,jquery:r.fn.jquery}},{"../package.json":11,"./imgs.js":16,jquery:void 0,"yasgui-utils":8}],14:[function(e,t){var r=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports={output:"table",outputPlugins:["table","error","boolean","rawResponse"],drawOutputSelector:!0,drawDownloadIcon:!0,getUsedPrefixes:null,persistency:{outputSelector:function(e){return"selector_"+r(e.container).closest("[id]").attr("id")},results:{id:function(e){return"results_"+r(e.container).closest("[id]").attr("id")},maxSize:1e5}}}},{jquery:void 0}],15:[function(e,t){var r=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),n=t.exports=function(e){var t=r("<div class='errorResult'></div>"),a=(r.extend(!0,{},n.defaults),function(){t.empty().appendTo(e.resultsContainer),r("<span class='exception'>ERROR</span>").appendTo(t),r("<p></p>").html(e.results.getException()).appendTo(t)}),o=function(e){return e.results.getException()||!1};return{name:null,draw:a,getPriority:20,hideFromSelection:!0,canHandleResults:o}};n.defaults={}},{jquery:void 0}],16:[function(e,t){t.exports={cross:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><g> <path d="M83.288,88.13c-2.114,2.112-5.575,2.112-7.689,0L53.659,66.188c-2.114-2.112-5.573-2.112-7.687,0L24.251,87.907 c-2.113,2.114-5.571,2.114-7.686,0l-4.693-4.691c-2.114-2.114-2.114-5.573,0-7.688l21.719-21.721c2.113-2.114,2.113-5.573,0-7.686 L11.872,24.4c-2.114-2.113-2.114-5.571,0-7.686l4.842-4.842c2.113-2.114,5.571-2.114,7.686,0L46.12,33.591 c2.114,2.114,5.572,2.114,7.688,0l21.721-21.719c2.114-2.114,5.573-2.114,7.687,0l4.695,4.695c2.111,2.113,2.111,5.571-0.003,7.686 L66.188,45.973c-2.112,2.114-2.112,5.573,0,7.686L88.13,75.602c2.112,2.111,2.112,5.572,0,7.687L83.288,88.13z"/></g></svg>',check:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="30px" height="30px" viewBox="0 0 100 100" enable-background="new 0 0 100 100" xml:space="preserve"><path fill="#000000" d="M14.301,49.982l22.606,17.047L84.361,4.903c2.614-3.733,7.76-4.64,11.493-2.026l0.627,0.462 c3.732,2.614,4.64,7.758,2.025,11.492l-51.783,79.77c-1.955,2.791-3.896,3.762-7.301,3.988c-3.405,0.225-5.464-1.039-7.508-3.084 L2.447,61.814c-3.263-3.262-3.263-8.553,0-11.814l0.041-0.019C5.75,46.718,11.039,46.718,14.301,49.982z"/></svg>',unsorted:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path7-9" d="m 8.8748339,52.571766 16.9382111,-0.222584 4.050851,-0.06665 15.719154,-0.222166 0.27778,-0.04246 0.43276,0.0017 0.41632,-0.06121 0.37532,-0.0611 0.47132,-0.119342 0.27767,-0.08206 0.55244,-0.198047 0.19707,-0.08043 0.61095,-0.259721 0.0988,-0.05825 0.019,-0.01914 0.59303,-0.356548 0.11787,-0.0788 0.49125,-0.337892 0.17994,-0.139779 0.37317,-0.336871 0.21862,-0.219786 0.31311,-0.31479 0.21993,-0.259387 c 0.92402,-1.126057 1.55249,-2.512251 1.78961,-4.016904 l 0.0573,-0.25754 0.0195,-0.374113 0.0179,-0.454719 0.0175,-0.05874 -0.0169,-0.258049 -0.0225,-0.493503 -0.0398,-0.355569 -0.0619,-0.414201 -0.098,-0.414812 -0.083,-0.353334 L 53.23955,41.1484 53.14185,40.850967 52.93977,40.377742 52.84157,40.161628 34.38021,4.2507375 C 33.211567,1.9401875 31.035446,0.48226552 28.639484,0.11316952 l -0.01843,-0.01834 -0.671963,-0.07882 -0.236871,0.0042 L 27.335984,-4.7826577e-7 27.220736,0.00379952 l -0.398804,0.0025 -0.313848,0.04043 -0.594474,0.07724 -0.09611,0.02147 C 23.424549,0.60716252 21.216017,2.1142355 20.013025,4.4296865 L 0.93967491,40.894479 c -2.08310801,3.997178 -0.588125,8.835482 3.35080799,10.819749 1.165535,0.613495 2.43199,0.88731 3.675026,0.864202 l 0.49845,-0.02325 0.410875,0.01658 z M 9.1502369,43.934401 9.0136999,43.910011 27.164145,9.2564625 44.70942,43.42818 l -14.765289,0.214677 -4.031106,0.0468 -16.7627881,0.244744 z" /></svg>',sortDesc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,-0.70898699,-0.70898699,0.70522156,97.988199,55.081205)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,0.12823506 0.09753,0.02006 c 2.39093,0.458209 4.599455,1.96811104 5.80244,4.28639004 L 52.785897,40.894525 c 2.088044,4.002139 0.590949,8.836902 -3.348692,10.821875 -1.329078,0.688721 -2.766603,0.943695 -4.133174,0.841768 l -0.454018,0.02 L 27.910392,52.354171 23.855313,52.281851 8.14393,52.061827 7.862608,52.021477 7.429856,52.021738 7.014241,51.959818 6.638216,51.900838 6.164776,51.779369 5.889216,51.699439 5.338907,51.500691 5.139719,51.419551 4.545064,51.145023 4.430618,51.105123 4.410168,51.084563 3.817138,50.730843 3.693615,50.647783 3.207314,50.310611 3.028071,50.174369 2.652795,49.833957 2.433471,49.613462 2.140099,49.318523 1.901127,49.041407 C 0.97781,47.916059 0.347935,46.528448 0.11153,45.021676 L 0.05352,44.766255 0.05172,44.371683 0.01894,43.936017 0,43.877277 0.01836,43.62206 0.03666,43.122889 0.0765,42.765905 0.13912,42.352413 0.23568,41.940425 0.32288,41.588517 0.481021,41.151945 0.579391,40.853806 0.77369,40.381268 0.876097,40.162336 19.338869,4.2542801 c 1.172169,-2.308419 3.34759,-3.76846504 5.740829,-4.17716604 l 0.01975,0.01985 0.69605,-0.09573 0.218437,0.0225 0.490791,-0.02132 0.39809,0.0046 0.315972,0.03973 0.594462,0.08149 z" /></svg>',sortAsc:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" id="Layer_1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 54.552711 113.78478" enable-background="new 0 0 100 100" xml:space="preserve"><g id="g5" transform="matrix(-0.70522156,0.70898699,-0.70898699,-0.70522156,97.988199,58.704807)"><path style="fill:#000000" inkscape:connector-curvature="0" id="path7" d="M 57.911,66.915 45.808,55.063 42.904,52.238 31.661,41.25 31.435,41.083 31.131,40.775 30.794,40.523 30.486,40.3 30.069,40.05 29.815,39.911 29.285,39.659 29.089,39.576 28.474,39.326 28.363,39.297 H 28.336 L 27.665,39.128 27.526,39.1 26.94,38.99 26.714,38.961 26.212,38.934 h -0.31 -0.444 l -0.339,0.027 c -1.45,0.139 -2.876,0.671 -4.11,1.564 l -0.223,0.141 -0.279,0.25 -0.335,0.308 -0.054,0.029 -0.171,0.194 -0.334,0.364 -0.224,0.279 -0.25,0.336 -0.225,0.362 -0.192,0.308 -0.197,0.421 -0.142,0.279 -0.193,0.477 -0.084,0.222 -12.441,38.414 c -0.814,2.458 -0.313,5.029 1.115,6.988 v 0.026 l 0.418,0.532 0.17,0.165 0.251,0.281 0.084,0.079 0.283,0.281 0.25,0.194 0.474,0.367 0.083,0.053 c 2.015,1.371 4.641,1.874 7.131,1.094 L 55.228,80.776 c 4.303,-1.342 6.679,-5.814 5.308,-10.006 -0.387,-1.259 -1.086,-2.35 -1.979,-3.215 l -0.368,-0.337 -0.278,-0.303 z m -6.318,5.896 0.079,0.114 -37.369,11.57 11.854,-36.538 10.565,10.317 2.876,2.825 11.995,11.712 z" /></g><path style="fill:#000000" inkscape:connector-curvature="0" id="path9" d="m 27.813273,113.65778 0.09753,-0.0201 c 2.39093,-0.45821 4.599455,-1.96811 5.80244,-4.28639 L 52.785897,72.891487 c 2.088044,-4.002139 0.590949,-8.836902 -3.348692,-10.821875 -1.329078,-0.688721 -2.766603,-0.943695 -4.133174,-0.841768 l -0.454018,-0.02 -16.939621,0.223997 -4.055079,0.07232 -15.711383,0.220024 -0.281322,0.04035 -0.432752,-2.61e-4 -0.415615,0.06192 -0.376025,0.05898 -0.47344,0.121469 -0.27556,0.07993 -0.550309,0.198748 -0.199188,0.08114 -0.594655,0.274528 -0.114446,0.0399 -0.02045,0.02056 -0.59303,0.35372 -0.123523,0.08306 -0.486301,0.337172 -0.179243,0.136242 -0.375276,0.340412 -0.219324,0.220495 -0.293372,0.294939 -0.238972,0.277116 C 0.97781,65.869953 0.347935,67.257564 0.11153,68.764336 L 0.05352,69.019757 0.05172,69.414329 0.01894,69.849995 0,69.908735 l 0.01836,0.255217 0.0183,0.499171 0.03984,0.356984 0.06262,0.413492 0.09656,0.411988 0.0872,0.351908 0.158141,0.436572 0.09837,0.298139 0.194299,0.472538 0.102407,0.218932 18.462772,35.908054 c 1.172169,2.30842 3.34759,3.76847 5.740829,4.17717 l 0.01975,-0.0199 0.69605,0.0957 0.218437,-0.0225 0.490791,0.0213 0.39809,-0.005 0.315972,-0.0397 0.594462,-0.0815 z" /></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g id="Captions"></g><g id="Your_Icon"> <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>'}},{}],17:[function(e,t){!function(){try{return e("jquery")}catch(t){return window.jQuery}}(),t.exports=function(t){return e("./dlv.js")(t,",")}},{"./dlv.js":18,jquery:void 0}],18:[function(e,t){var r=jQuery=function(){try{return e("jquery")}catch(t){return window.jQuery}}();e("../../lib/jquery.csv-0.71.js");t.exports=function(e,t){var n={},a=r.csv.toArrays(e,{separator:t}),o=function(e){return 0==e.indexOf("http")?"uri":null},i=function(){return 2!=a.length||1!=a[0].length||1!=a[1].length||"boolean"!=a[0][0]||"1"!=a[1][0]&&"0"!=a[1][0]?!1:(n.boolean="1"==a[1][0]?!0:!1,!0)},s=function(){return a.length>0&&a[0].length>0?(n.head={vars:a[0]},!0):!1},l=function(){if(a.length>1){n.results={bindings:[]};for(var e=1;e<a.length;e++){for(var t={},r=0;r<a[e].length;r++){var i=n.head.vars[r];if(i){var s=a[e][r],l=o(s);t[i]={value:s},l&&(t[i].type=l)}}n.results.bindings.push(t)}return n.head={vars:a[0]},!0}return!1},u=i();if(!u){var c=s();c&&l()}return n}},{"../../lib/jquery.csv-0.71.js":2,jquery:void 0}],19:[function(e,t){!function(){try{return e("jquery")}catch(t){return window.jQuery}}(),t.exports=function(e){if("string"==typeof e)try{return JSON.parse(e)}catch(t){return!1}return"object"==typeof e&&e.constructor==={}.constructor?e:!1}},{jquery:void 0}],20:[function(e,t){!function(){try{return e("jquery")}catch(t){return window.jQuery}}(),t.exports=function(t){return e("./dlv.js")(t," ")}},{"./dlv.js":18,jquery:void 0}],21:[function(e,t){!function(){try{return e("jquery")}catch(t){return window.jQuery}}(),t.exports=function(t){var r,n,a={xml:e("./xml.js"),json:e("./json.js"),tsv:e("./tsv.js"),csv:e("./csv.js")},o=null,i=null,s="object"==typeof t&&t.exception?t.exception:null;r="object"==typeof t&&t.contentType?t.contentType.toLowerCase():null,n="object"==typeof t&&t.response?t.response:t;var l=function(){if(o)return o;if(o===!1||s)return!1;var e=function(){if(r)if(r.indexOf("json")>-1){try{o=a.json(n)}catch(e){s=e}i="json"}else if(r.indexOf("xml")>-1){try{o=a.xml(n)}catch(e){s=e}i="xml"}else if(r.indexOf("csv")>-1){try{o=a.csv(n)}catch(e){s=e}i="csv"}else if(r.indexOf("tab-separated")>-1){try{o=a.tsv(n)}catch(e){s=e}i="tsv"}},t=function(){if(o=a.json(n))i="json";else try{o=a.xml(n),o&&(i="xml")}catch(e){}};return e(),o||t(),o||(o=!1),o},u=function(){var e=l();return e&&"head"in e?e.head.vars:null},c=function(){var e=l();return e&&"results"in e?e.results.bindings:null},d=function(){var e=l();return e&&"boolean"in e?e.boolean:null},f=function(){return n},p=function(){var e="";return"string"==typeof n?e=n:"json"==i?e=JSON.stringify(n,void 0,2):"xml"==i&&(e=(new XMLSerializer).serializeToString(n)),e},m=function(){return s},v=function(){return null==i&&l(),i};return o=l(),{getAsJson:l,getOriginalResponse:f,getOriginalResponseAsString:p,getOriginalContentType:function(){return r},getVariables:u,getBindings:c,getBoolean:d,getType:v,getException:m}}},{"./csv.js":17,"./json.js":19,"./tsv.js":20,"./xml.js":22,jquery:void 0}],22:[function(e,t){{var r=function(){try{return e("jquery")}catch(t){return window.jQuery}}();t.exports=function(e){var t=function(e){i.head={};for(var t=0;t<e.childNodes.length;t++){var r=e.childNodes[t];if("variable"==r.nodeName){i.head.vars||(i.head.vars=[]);var n=r.getAttribute("name");n&&i.head.vars.push(n)}}},n=function(e){i.results={},i.results.bindings=[];for(var t=0;t<e.childNodes.length;t++){for(var r=e.childNodes[t],n=null,a=0;a<r.childNodes.length;a++){var o=r.childNodes[a];if("binding"==o.nodeName){var s=o.getAttribute("name");if(s){n=n||{},n[s]={};for(var l=0;l<o.childNodes.length;l++){var u=o.childNodes[l],c=u.nodeName;if("#text"!=c){n[s].type=c,n[s].value=u.innerHTML;var d=u.getAttribute("datatype");d&&(n[s].datatype=d)}}}}}n&&i.results.bindings.push(n)}},a=function(e){i.boolean="true"==e.innerHTML?!0:!1},o=null;"string"==typeof e?o=r.parseXML(e):r.isXMLDoc(e)&&(o=e);var e=null;if(!(o.childNodes.length>0))return null;e=o.childNodes[0];for(var i={},s=0;s<e.childNodes.length;s++){var l=e.childNodes[s];"head"==l.nodeName&&t(l),"results"==l.nodeName&&n(l),"boolean"==l.nodeName&&a(l)}return i}}},{jquery:void 0}],23:[function(e,t){var r=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),n=function(){try{return e("codemirror")}catch(t){return window.CodeMirror}}();e("codemirror/addon/edit/matchbrackets.js"),e("codemirror/mode/xml/xml.js"),e("codemirror/mode/javascript/javascript.js");var a=t.exports=function(e){var t=r.extend(!0,{},a.defaults),o=function(){var r=t.CodeMirror;r.value=e.results.getOriginalResponseAsString();var a=e.results.getType();a&&("json"==a&&(a={name:"javascript",json:!0}),r.mode=a),n(e.resultsContainer.get()[0],r)},i=function(){if(!e.results)return!1;var t=e.results.getOriginalResponseAsString();return t&&0!=t.length||!e.results.getException()?!0:!1},s=function(){if(!e.results)return null;var t=e.results.getOriginalContentType(),r=e.results.getType();return{getContent:function(){return e.results.getOriginalResponse()},filename:"queryResults"+(r?"."+r:""),contentType:t?t:"text/plain",buttonTitle:"Download raw response"}};return{draw:o,name:"Raw Response",canHandleResults:i,getPriority:2,getDownloadInfo:s}};a.defaults={CodeMirror:{readOnly:!0}},a.version={"YASR-rawResponse":e("../package.json").version,jquery:r.fn.jquery,CodeMirror:n.version}},{"../package.json":11,codemirror:void 0,"codemirror/addon/edit/matchbrackets.js":3,"codemirror/mode/javascript/javascript.js":4,"codemirror/mode/xml/xml.js":5,jquery:void 0}],24:[function(e,t){var r=function(){try{return e("jquery")}catch(t){return window.jQuery}}(),n=e("yasgui-utils"),a=e("./imgs.js");!function(){try{return e("jquery.dataTables")}catch(t){return window.jQuery}}();var o=t.exports=function(t){var i=null,l=r.extend(!0,{},o.defaults),u=function(){var e=[],r=t.results.getBindings(),n=t.results.getVariables(),a=null;t.options.getUsedPrefixes&&(a="function"==typeof t.options.getUsedPrefixes?t.options.getUsedPrefixes(t):t.options.getUsedPrefixes);for(var o=0;o<r.length;o++){var i=[];i.push("");for(var s=r[o],u=0;u<n.length;u++){var c=n[u];i.push(c in s?l.drawCellContent?l.drawCellContent(t,o,u,s,c,a):"":"")}e.push(i)}return e},c=function(){i.on("order.dt",function(){f()}),r.extend(!0,l.callbacks,l.handlers),i.delegate("td","click",function(e){if(l.callbacks&&l.callbacks.onCellClick){var t=l.callbacks.onCellClick(this,e);if(t===!1)return!1}}).delegate("td","mouseenter",function(e){l.callbacks&&l.callbacks.onCellMouseEnter&&l.callbacks.onCellMouseEnter(this,e);var t=r(this);l.fetchTitlesFromPreflabel&&void 0===t.attr("title")&&0==t.text().trim().indexOf("http")&&s(t)}).delegate("td","mouseleave",function(e){l.callbacks&&l.callbacks.onCellMouseLeave&&l.callbacks.onCellMouseLeave(this,e)})},d=function(){i=r('<table cellpadding="0" cellspacing="0" border="0" class="resultsTable"></table>'),r(t.resultsContainer).html(i);var e=l.datatable;e.data=u(),e.columns=l.getColumns(t),i.DataTable(r.extend(!0,{},e)),f(),c();var n=t.header.outerHeight()-5;n>0&&t.resultsContainer.find(".dataTables_wrapper").css("position","relative").css("top","-"+n+"px").css("margin-bottom","-"+n+"px")},f=function(){var e={sorting:"unsorted",sorting_asc:"sortAsc",sorting_desc:"sortDesc"};i.find(".sortIcons").remove();var t=8,o=13;for(var s in e){var l=r("<div class='sortIcons'></div>").css("float","right").css("margin-right","-12px").width(t).height(o);n.svg.draw(l,a[e[s]],{width:t+2,height:o+1}),i.find("th."+s).append(l)}},p=function(){return t.results&&t.results.getVariables()&&t.results.getVariables().length>0},m=function(){return t.results?{getContent:function(){return e("./bindingsToCsv.js")(t.results.getAsJson())},filename:"queryResults.csv",contentType:"text/csv",buttonTitle:"Download as CSV"}:null};return{name:"Table",draw:d,getPriority:10,getDownloadInfo:m,canHandleResults:p}},i=function(e,t,r,n,a,o){var i=n[a],s=null;if("uri"==i.type){var l=visibleString=i.value;if(o)for(var u in o)if(0==visibleString.indexOf(o[u])){visibleString=u+l.substring(o[u].length);break}s="<a class='uri' target='_blank' href='"+l+"'>"+visibleString+"</a>"}else{var c=i.value;if(i["xml:lang"])c='"'+i.value+'"@'+i["xml:lang"];else if(i.datatype){var d="http://www.w3.org/2001/XMLSchema#",f=i.datatype;f=0==f.indexOf(d)?"xsd:"+f.substring(d.length):"<"+f+">",c='"'+c+'"^^'+f}s="<span class='nonUri'>"+c+"</span>"}return s},s=function(e){var t=function(){e.attr("title","")};r.get("http://preflabel.org/api/v1/label/"+encodeURIComponent(e.text())+"?silent=true").success(function(r){"object"==typeof r&&r.label?e.attr("title",r.label):"string"==typeof r&&r.length>0?e.attr("title",r):t()}).fail(t)};o.defaults={drawCellContent:i,getColumns:function(e){var t=[];t.push({title:""});for(var r=e.results.getVariables(),n=0;n<r.length;n++)t.push({title:r[n]});return t},fetchTitlesFromPreflabel:!0,callbacks:{onCellMouseEnter:null,onCellMouseLeave:null,onCellClick:null},datatable:{order:[],pageLength:50,lengthMenu:[[10,50,100,1e3,-1],[10,50,100,1e3,"All"]],lengthChange:!0,pagingType:"full_numbers",drawCallback:function(e){for(var t=0;t<e.aiDisplay.length;t++)r("td:eq(0)",e.aoData[e.aiDisplay[t]].nTr).html(t+1);var n=!1;r(e.nTableWrapper).find(".paginate_button").each(function(){-1==r(this).attr("class").indexOf("current")&&-1==r(this).attr("class").indexOf("disabled")&&(n=!0)}),n?r(e.nTableWrapper).find(".dataTables_paginate").show():r(e.nTableWrapper).find(".dataTables_paginate").hide()},columnDefs:[{width:"12px",orderable:!1,targets:0}]}},o.version={"YASR-table":e("../package.json").version,jquery:r.fn.jquery,"jquery-datatables":r.fn.DataTable.version}},{"../package.json":11,"./bindingsToCsv.js":12,"./imgs.js":16,jquery:void 0,"jquery.dataTables":void 0,"yasgui-utils":8}]},{},[1])(1)});
//# sourceMappingURL=yasr.min.js.map | ruslanas/cdnjs | ajax/libs/yasr/2.1.0/yasr.min.js | JavaScript | mit | 60,957 |
var baseFlatten = require('./_baseFlatten'),
baseIteratee = require('./_baseIteratee'),
baseUniq = require('./_baseUniq'),
isArrayLikeObject = require('./isArrayLikeObject'),
last = require('./last'),
rest = require('./rest');
/**
* This method is like `_.union` except that it accepts `iteratee` which is
* invoked for each element of each `arrays` to generate the criterion by
* which uniqueness is computed. The iteratee is invoked with one argument:
* (value).
*
* @static
* @memberOf _
* @since 4.0.0
* @category Array
* @param {...Array} [arrays] The arrays to inspect.
* @param {Array|Function|Object|string} [iteratee=_.identity]
* The iteratee invoked per element.
* @returns {Array} Returns the new array of combined values.
* @example
*
* _.unionBy([2.1], [1.2, 2.3], Math.floor);
* // => [2.1, 1.2]
*
* // The `_.property` iteratee shorthand.
* _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
* // => [{ 'x': 1 }, { 'x': 2 }]
*/
var unionBy = rest(function(arrays) {
var iteratee = last(arrays);
if (isArrayLikeObject(iteratee)) {
iteratee = undefined;
}
return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), baseIteratee(iteratee));
});
module.exports = unionBy;
| tedsf/tiptap | node_modules/babel-template/node_modules/lodash/unionBy.js | JavaScript | mit | 1,252 |
/*!
backbone.fetch-cache v0.1.10
by Andy Appleton - https://github.com/mrappleton/backbone-fetch-cache.git
*/
// AMD wrapper from https://github.com/umdjs/umd/blob/master/amdWebGlobal.js
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module and set browser global
define(['underscore', 'backbone'], function (_, Backbone) {
return (root.Backbone = factory(_, Backbone));
});
} else {
// Browser globals
root.Backbone = factory(root._, root.Backbone);
}
}(this, function (_, Backbone) {
// Setup
var superMethods = {
modelFetch: Backbone.Model.prototype.fetch,
modelSync: Backbone.Model.prototype.sync,
collectionFetch: Backbone.Collection.prototype.fetch
},
supportLocalStorage = typeof window.localStorage !== 'undefined';
Backbone.fetchCache = (Backbone.fetchCache || {});
Backbone.fetchCache._cache = (Backbone.fetchCache._cache || {});
Backbone.fetchCache.priorityFn = function(a, b) {
if (!a || !a.expires || !b || !b.expires) {
return a;
}
return a.expires - b.expires;
};
Backbone.fetchCache._prioritize = function() {
var sorted = _.values(this._cache).sort(this.priorityFn);
var index = _.indexOf(_.values(this._cache), sorted[0]);
return _.keys(this._cache)[index];
};
Backbone.fetchCache._deleteCacheWithPriority = function() {
Backbone.fetchCache._cache[this._prioritize()] = null;
delete Backbone.fetchCache._cache[this._prioritize()];
Backbone.fetchCache.setLocalStorage();
};
if (typeof Backbone.fetchCache.localStorage === 'undefined') {
Backbone.fetchCache.localStorage = true;
}
function getCacheKey(instance, opts) {
var url = _.isFunction(instance.url) ? instance.url() : instance.url;
// Need url to use as cache key so return if we can't get it
if(!url) { return; }
if(opts && opts.data) {
return url + "?" + $.param(opts.data);
}
return url;
}
// Shared methods
function setCache(instance, opts, attrs) {
opts = (opts || {});
var key = Backbone.fetchCache.getCacheKey(instance, opts),
expires = false;
// Need url to use as cache key so return if we can't get it
if (!key) { return; }
// Never set the cache if user has explicitly said not to
if (opts.cache === false) { return; }
// Don't set the cache unless cache: true or prefill: true option is passed
if (!(opts.cache || opts.prefill)) { return; }
if (opts.expires !== false) {
expires = (new Date()).getTime() + ((opts.expires || 5 * 60) * 1000);
}
Backbone.fetchCache._cache[key] = {
expires: expires,
value: attrs
};
Backbone.fetchCache.setLocalStorage();
}
function clearItem(key) {
delete Backbone.fetchCache._cache[key];
Backbone.fetchCache.setLocalStorage();
}
function setLocalStorage() {
if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; }
try {
localStorage.setItem('backboneCache', JSON.stringify(Backbone.fetchCache._cache));
} catch (err) {
var code = err.code || err.number || err.message;
if (code === 22) {
this._deleteCacheWithPriority();
} else {
throw(err);
}
}
}
function getLocalStorage() {
if (!supportLocalStorage || !Backbone.fetchCache.localStorage) { return; }
var json = localStorage.getItem('backboneCache') || '{}';
Backbone.fetchCache._cache = JSON.parse(json);
}
// Instance methods
Backbone.Model.prototype.fetch = function(opts) {
opts = (opts || {});
var key = Backbone.fetchCache.getCacheKey(this, opts),
data = Backbone.fetchCache._cache[key],
expired = false,
attributes = false,
promise = new $.Deferred();
if (data) {
expired = data.expires;
expired = expired && data.expires < (new Date()).getTime();
attributes = data.value;
}
if (!expired && (opts.cache || opts.prefill) && attributes) {
this.set(this.parse(attributes), opts);
if (_.isFunction(opts.prefillSuccess)) { opts.prefillSuccess(this, attributes, opts); }
// Trigger sync events
this.trigger('cachesync', this, attributes, opts);
this.trigger('sync', this, attributes, opts);
// Notify progress if we're still waiting for an AJAX call to happen...
if (opts.prefill) { promise.notify(this); }
// ...finish and return if we're not
else {
if (_.isFunction(opts.success)) { opts.success(this); }
// Mimic actual fetch behaviour buy returning a fulfilled promise
return promise.resolve(this);
}
}
// Delegate to the actual fetch method and store the attributes in the cache
superMethods.modelFetch.apply(this, arguments)
// resolve the returned promise when the AJAX call completes
.done( _.bind(promise.resolve, this, this) )
// Set the new data in the cache
.done( _.bind(Backbone.fetchCache.setCache, null, this, opts) )
// Reject the promise on fail
.fail( _.bind(promise.reject, this, this) );
// return a promise which provides the same methods as a jqXHR object
return promise;
};
// Override Model.prototype.sync and try to clear cache items if it looks
// like they are being updated.
Backbone.Model.prototype.sync = function(method, model, options) {
// Only empty the cache if we're doing a create, update, patch or delete.
if (method === 'read') {
return superMethods.modelSync.apply(this, arguments);
}
var collection = model.collection,
keys = [],
i, len;
// Build up a list of keys to delete from the cache, starting with this
keys.push(Backbone.fetchCache.getCacheKey(model));
// If this model has a collection, also try to delete the cache for that
if (!!collection) {
keys.push(Backbone.fetchCache.getCacheKey(collection));
}
// Empty cache for all found keys
for (i = 0, len = keys.length; i < len; i++) { clearItem(keys[i]); }
return superMethods.modelSync.apply(this, arguments);
};
Backbone.Collection.prototype.fetch = function(opts) {
opts = (opts || {});
var key = Backbone.fetchCache.getCacheKey(this, opts),
data = Backbone.fetchCache._cache[key],
expired = false,
attributes = false,
promise = new $.Deferred();
if (data) {
expired = data.expires;
expired = expired && data.expires < (new Date()).getTime();
attributes = data.value;
}
if (!expired && (opts.cache || opts.prefill) && attributes) {
this[opts.reset ? 'reset' : 'set'](this.parse(attributes), opts);
if (_.isFunction(opts.prefillSuccess)) { opts.prefillSuccess(this); }
// Trigger sync events
this.trigger('cachesync', this, attributes, opts);
this.trigger('sync', this, attributes, opts);
// Notify progress if we're still waiting for an AJAX call to happen...
if (opts.prefill) { promise.notify(this); }
// ...finish and return if we're not
else {
if (_.isFunction(opts.success)) { opts.success(this); }
// Mimic actual fetch behaviour buy returning a fulfilled promise
return promise.resolve(this);
}
}
// Delegate to the actual fetch method and store the attributes in the cache
superMethods.collectionFetch.apply(this, arguments)
// resolve the returned promise when the AJAX call completes
.done( _.bind(promise.resolve, this, this) )
// Set the new data in the cache
.done( _.bind(Backbone.fetchCache.setCache, null, this, opts) )
// Reject the promise on fail
.fail( _.bind(promise.reject, this, this) );
// return a promise which provides the same methods as a jqXHR object
return promise;
};
// Prime the cache from localStorage on initialization
getLocalStorage();
// Exports
Backbone.fetchCache._superMethods = superMethods;
Backbone.fetchCache.setCache = setCache;
Backbone.fetchCache.getCacheKey = getCacheKey;
Backbone.fetchCache.clearItem = clearItem;
Backbone.fetchCache.setLocalStorage = setLocalStorage;
Backbone.fetchCache.getLocalStorage = getLocalStorage;
return Backbone;
}));
| ksaitor/cdnjs | ajax/libs/backbone.fetch-cache/0.1.10/backbone.fetch-cache.js | JavaScript | mit | 8,288 |
// Underscore.js 1.1.7
// (c) 2011 Jeremy Ashkenas, DocumentCloud Inc.
// Underscore is freely distributable under the MIT license.
// Portions of Underscore are inspired or borrowed from Prototype,
// Oliver Steele's Functional, and John Resig's Micro-Templating.
// For all details and documentation:
// http://documentcloud.github.com/underscore
(function() {
// Baseline setup
// --------------
// Establish the root object, `window` in the browser, or `global` on the server.
var root = this;
// Save the previous value of the `_` variable.
var previousUnderscore = root._;
// Establish the object that gets returned to break out of a loop iteration.
var breaker = {};
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
// Create quick reference variables for speed access to core prototypes.
var slice = ArrayProto.slice,
unshift = ArrayProto.unshift,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
// All **ECMAScript 5** native function implementations that we hope to use
// are declared here.
var
nativeForEach = ArrayProto.forEach,
nativeMap = ArrayProto.map,
nativeReduce = ArrayProto.reduce,
nativeReduceRight = ArrayProto.reduceRight,
nativeFilter = ArrayProto.filter,
nativeEvery = ArrayProto.every,
nativeSome = ArrayProto.some,
nativeIndexOf = ArrayProto.indexOf,
nativeLastIndexOf = ArrayProto.lastIndexOf,
nativeIsArray = Array.isArray,
nativeKeys = Object.keys,
nativeBind = FuncProto.bind;
// Create a safe reference to the Underscore object for use below.
var _ = function(obj) { return new wrapper(obj); };
// Export the Underscore object for **CommonJS**, with backwards-compatibility
// for the old `require()` API. If we're not in CommonJS, add `_` to the
// global object.
if (typeof module !== 'undefined' && module.exports) {
module.exports = _;
_._ = _;
} else {
// Exported as a string, for Closure Compiler "advanced" mode.
root['_'] = _;
}
// Current version.
_.VERSION = '1.1.7';
// Collection Functions
// --------------------
// The cornerstone, an `each` implementation, aka `forEach`.
// Handles objects with the built-in `forEach`, arrays, and raw objects.
// Delegates to **ECMAScript 5**'s native `forEach` if available.
var each = _.each = _.forEach = function(obj, iterator, context) {
if (obj == null) return;
if (nativeForEach && obj.forEach === nativeForEach) {
obj.forEach(iterator, context);
} else if (obj.length === +obj.length) {
for (var i = 0, l = obj.length; i < l; i++) {
if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
// Return the results of applying the iterator to each element.
// Delegates to **ECMAScript 5**'s native `map` if available.
_.map = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
each(obj, function(value, index, list) {
results[results.length] = iterator.call(context, value, index, list);
});
return results;
};
// **Reduce** builds up a single result from a list of values, aka `inject`,
// or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
_.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = memo !== void 0;
if (obj == null) obj = [];
if (nativeReduce && obj.reduce === nativeReduce) {
if (context) iterator = _.bind(iterator, context);
return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
}
each(obj, function(value, index, list) {
if (!initial) {
memo = value;
initial = true;
} else {
memo = iterator.call(context, memo, value, index, list);
}
});
if (!initial) throw new TypeError("Reduce of empty array with no initial value");
return memo;
};
// The right-associative version of reduce, also known as `foldr`.
// Delegates to **ECMAScript 5**'s native `reduceRight` if available.
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return memo !== void 0 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var reversed = (_.isArray(obj) ? obj.slice() : _.toArray(obj)).reverse();
return _.reduce(reversed, iterator, memo, context);
};
// Return the first value which passes a truth test. Aliased as `detect`.
_.find = _.detect = function(obj, iterator, context) {
var result;
any(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Return all the elements that pass a truth test.
// Delegates to **ECMAScript 5**'s native `filter` if available.
// Aliased as `select`.
_.filter = _.select = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
each(obj, function(value, index, list) {
if (iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Return all the elements for which a truth test fails.
_.reject = function(obj, iterator, context) {
var results = [];
if (obj == null) return results;
each(obj, function(value, index, list) {
if (!iterator.call(context, value, index, list)) results[results.length] = value;
});
return results;
};
// Determine whether all of the elements match a truth test.
// Delegates to **ECMAScript 5**'s native `every` if available.
// Aliased as `all`.
_.every = _.all = function(obj, iterator, context) {
var result = true;
if (obj == null) return result;
if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
each(obj, function(value, index, list) {
if (!(result = result && iterator.call(context, value, index, list))) return breaker;
});
return result;
};
// Determine if at least one element in the object matches a truth test.
// Delegates to **ECMAScript 5**'s native `some` if available.
// Aliased as `any`.
var any = _.some = _.any = function(obj, iterator, context) {
iterator = iterator || _.identity;
var result = false;
if (obj == null) return result;
if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
each(obj, function(value, index, list) {
if (result |= iterator.call(context, value, index, list)) return breaker;
});
return !!result;
};
// Determine if a given value is included in the array or object using `===`.
// Aliased as `contains`.
_.include = _.contains = function(obj, target) {
var found = false;
if (obj == null) return found;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
any(obj, function(value) {
if (found = value === target) return true;
});
return found;
};
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
return _.map(obj, function(value) {
return (method.call ? method || value : value[method]).apply(value, args);
});
};
// Convenience version of a common use case of `map`: fetching a property.
_.pluck = function(obj, key) {
return _.map(obj, function(value){ return value[key]; });
};
// Return the maximum element or (element-based computation).
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
var result = {computed : -Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed >= result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Return the minimum element (or element-based computation).
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
var result = {computed : Infinity};
each(obj, function(value, index, list) {
var computed = iterator ? iterator.call(context, value, index, list) : value;
computed < result.computed && (result = {value : value, computed : computed});
});
return result.value;
};
// Sort the object's values by a criterion produced by an iterator.
_.sortBy = function(obj, iterator, context) {
return _.pluck(_.map(obj, function(value, index, list) {
return {
value : value,
criteria : iterator.call(context, value, index, list)
};
}).sort(function(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}), 'value');
};
// Groups the object's values by a criterion produced by an iterator
_.groupBy = function(obj, iterator) {
var result = {};
each(obj, function(value, index) {
var key = iterator(value, index);
(result[key] || (result[key] = [])).push(value);
});
return result;
};
// Use a comparator function to figure out at what index an object should
// be inserted so as to maintain order. Uses binary search.
_.sortedIndex = function(array, obj, iterator) {
iterator || (iterator = _.identity);
var low = 0, high = array.length;
while (low < high) {
var mid = (low + high) >> 1;
iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
}
return low;
};
// Safely convert anything iterable into a real, live array.
_.toArray = function(iterable) {
if (!iterable) return [];
if (iterable.toArray) return iterable.toArray();
if (_.isArray(iterable)) return slice.call(iterable);
if (_.isArguments(iterable)) return slice.call(iterable);
return _.values(iterable);
};
// Return the number of elements in an object.
_.size = function(obj) {
return _.toArray(obj).length;
};
// Array Functions
// ---------------
// Get the first element of an array. Passing **n** will return the first N
// values in the array. Aliased as `head`. The **guard** check allows it to work
// with `_.map`.
_.first = _.head = function(array, n, guard) {
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
// Returns everything but the first entry of the array. Aliased as `tail`.
// Especially useful on the arguments object. Passing an **index** will return
// the rest of the values in the array from that index onward. The **guard**
// check allows it to work with `_.map`.
_.rest = _.tail = function(array, index, guard) {
return slice.call(array, (index == null) || guard ? 1 : index);
};
// Get the last element of an array.
_.last = function(array) {
return array[array.length - 1];
};
// Trim out all falsy values from an array.
_.compact = function(array) {
return _.filter(array, function(value){ return !!value; });
};
// Return a completely flattened version of an array.
_.flatten = function(array) {
return _.reduce(array, function(memo, value) {
if (_.isArray(value)) return memo.concat(_.flatten(value));
memo[memo.length] = value;
return memo;
}, []);
};
// Return a version of the array that does not contain the specified value(s).
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
// Produce a duplicate-free version of the array. If the array has already
// been sorted, you have the option of using a faster algorithm.
// Aliased as `unique`.
_.uniq = _.unique = function(array, isSorted) {
return _.reduce(array, function(memo, el, i) {
if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) memo[memo.length] = el;
return memo;
}, []);
};
// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
return _.uniq(_.flatten(arguments));
};
// Produce an array that contains every item shared between all the
// passed-in arrays. (Aliased as "intersect" for back-compat.)
_.intersection = _.intersect = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
// Take the difference between one array and another.
// Only the elements present in just the first array will remain.
_.difference = function(array, other) {
return _.filter(array, function(value){ return !_.include(other, value); });
};
// Zip together multiple lists into a single array -- elements that share
// an index go together.
_.zip = function() {
var args = slice.call(arguments);
var length = _.max(_.pluck(args, 'length'));
var results = new Array(length);
for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
return results;
};
// If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
// we need this function. Return the position of the first occurrence of an
// item in an array, or -1 if the item is not included in the array.
// Delegates to **ECMAScript 5**'s native `indexOf` if available.
// If the array is large and already in sort order, pass `true`
// for **isSorted** to use binary search.
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i, l;
if (isSorted) {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
for (i = 0, l = array.length; i < l; i++) if (array[i] === item) return i;
return -1;
};
// Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
_.lastIndexOf = function(array, item) {
if (array == null) return -1;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
var i = array.length;
while (i--) if (array[i] === item) return i;
return -1;
};
// Generate an integer Array containing an arithmetic progression. A port of
// the native Python `range()` function. See
// [the Python documentation](http://docs.python.org/library/functions.html#range).
_.range = function(start, stop, step) {
if (arguments.length <= 1) {
stop = start || 0;
start = 0;
}
step = arguments[2] || 1;
var len = Math.max(Math.ceil((stop - start) / step), 0);
var idx = 0;
var range = new Array(len);
while(idx < len) {
range[idx++] = start;
start += step;
}
return range;
};
// Function (ahem) Functions
// ------------------
// Create a function bound to a given object (assigning `this`, and arguments,
// optionally). Binding with arguments is also known as `curry`.
// Delegates to **ECMAScript 5**'s native `Function.bind` if available.
// We check for `func.bind` first, to fail fast when `func` is undefined.
_.bind = function(func, obj) {
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
var args = slice.call(arguments, 2);
return function() {
return func.apply(obj, args.concat(slice.call(arguments)));
};
};
// Bind all of an object's methods to that object. Useful for ensuring that
// all callbacks defined on an object belong to it.
_.bindAll = function(obj) {
var funcs = slice.call(arguments, 1);
if (funcs.length == 0) funcs = _.functions(obj);
each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
return obj;
};
// Memoize an expensive function by storing its results.
_.memoize = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return hasOwnProperty.call(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
// Delays a function for the given number of milliseconds, and then calls
// it with the arguments supplied.
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function(){ return func.apply(func, args); }, wait);
};
// Defers a function, scheduling it to run after the current call stack has
// cleared.
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
// Internal function used to implement `_.throttle` and `_.debounce`.
var limit = function(func, wait, debounce) {
var timeout;
return function() {
var context = this, args = arguments;
var throttler = function() {
timeout = null;
func.apply(context, args);
};
if (debounce) clearTimeout(timeout);
if (debounce || !timeout) timeout = setTimeout(throttler, wait);
};
};
// Returns a function, that, when invoked, will only be triggered at most once
// during a given window of time.
_.throttle = function(func, wait) {
return limit(func, wait, false);
};
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds.
_.debounce = function(func, wait) {
return limit(func, wait, true);
};
// Returns a function that will be executed at most one time, no matter how
// often you call it. Useful for lazy initialization.
_.once = function(func) {
var ran = false, memo;
return function() {
if (ran) return memo;
ran = true;
return memo = func.apply(this, arguments);
};
};
// Returns the first function passed as an argument to the second,
// allowing you to adjust arguments, run code before and after, and
// conditionally execute the original function.
_.wrap = function(func, wrapper) {
return function() {
var args = [func].concat(slice.call(arguments));
return wrapper.apply(this, args);
};
};
// Returns a function that is the composition of a list of functions, each
// consuming the return value of the function that follows.
_.compose = function() {
var funcs = slice.call(arguments);
return function() {
var args = slice.call(arguments);
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
// Returns a function that will only be executed after being called N times.
_.after = function(times, func) {
return function() {
if (--times < 1) { return func.apply(this, arguments); }
};
};
// Object Functions
// ----------------
// Retrieve the names of an object's properties.
// Delegates to **ECMAScript 5**'s native `Object.keys`
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (hasOwnProperty.call(obj, key)) keys[keys.length] = key;
return keys;
};
// Retrieve the values of an object's properties.
_.values = function(obj) {
return _.map(obj, _.identity);
};
// Return a sorted list of the function names available on the object.
// Aliased as `methods`
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
// Extend a given object with all the properties in passed-in object(s).
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (source[prop] !== void 0) obj[prop] = source[prop];
}
});
return obj;
};
// Fill in a given object with default properties.
_.defaults = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
if (obj[prop] == null) obj[prop] = source[prop];
}
});
return obj;
};
// Create a (shallow-cloned) duplicate of an object.
_.clone = function(obj) {
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
// Invokes interceptor with the obj, and then returns obj.
// The primary purpose of this method is to "tap into" a method chain, in
// order to perform operations on intermediate results within the chain.
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
// Perform a deep comparison to check if two objects are equal.
_.isEqual = function(a, b) {
// Check object identity.
if (a === b) return true;
// Different types?
var atype = typeof(a), btype = typeof(b);
if (atype != btype) return false;
// Basic equality test (watch out for coercions).
if (a == b) return true;
// One is falsy and the other truthy.
if ((!a && b) || (a && !b)) return false;
// Unwrap any wrapped objects.
if (a._chain) a = a._wrapped;
if (b._chain) b = b._wrapped;
// One of them implements an isEqual()?
if (a.isEqual) return a.isEqual(b);
if (b.isEqual) return b.isEqual(a);
// Check dates' integer values.
if (_.isDate(a) && _.isDate(b)) return a.getTime() === b.getTime();
// Both are NaN?
if (_.isNaN(a) && _.isNaN(b)) return false;
// Compare regular expressions.
if (_.isRegExp(a) && _.isRegExp(b))
return a.source === b.source &&
a.global === b.global &&
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline;
// If a is not an object by this point, we can't handle it.
if (atype !== 'object') return false;
// Check for different array lengths before comparing contents.
if (a.length && (a.length !== b.length)) return false;
// Nothing else worked, deep compare the contents.
var aKeys = _.keys(a), bKeys = _.keys(b);
// Different object sizes?
if (aKeys.length != bKeys.length) return false;
// Recursive comparison of contents.
for (var key in a) if (!(key in b) || !_.isEqual(a[key], b[key])) return false;
return true;
};
// Is a given array or object empty?
_.isEmpty = function(obj) {
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (hasOwnProperty.call(obj, key)) return false;
return true;
};
// Is a given value a DOM element?
_.isElement = function(obj) {
return !!(obj && obj.nodeType == 1);
};
// Is a given value an array?
// Delegates to ECMA5's native Array.isArray
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) === '[object Array]';
};
// Is a given variable an object?
_.isObject = function(obj) {
return obj === Object(obj);
};
// Is a given variable an arguments object?
_.isArguments = function(obj) {
return !!(obj && hasOwnProperty.call(obj, 'callee'));
};
// Is a given value a function?
_.isFunction = function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
// Is a given value a string?
_.isString = function(obj) {
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
};
// Is a given value a number?
_.isNumber = function(obj) {
return !!(obj === 0 || (obj && obj.toExponential && obj.toFixed));
};
// Is the given value `NaN`? `NaN` happens to be the only value in JavaScript
// that does not equal itself.
_.isNaN = function(obj) {
return obj !== obj;
};
// Is a given value a boolean?
_.isBoolean = function(obj) {
return obj === true || obj === false;
};
// Is a given value a date?
_.isDate = function(obj) {
return !!(obj && obj.getTimezoneOffset && obj.setUTCFullYear);
};
// Is the given value a regular expression?
_.isRegExp = function(obj) {
return !!(obj && obj.test && obj.exec && (obj.ignoreCase || obj.ignoreCase === false));
};
// Is a given value equal to null?
_.isNull = function(obj) {
return obj === null;
};
// Is a given variable undefined?
_.isUndefined = function(obj) {
return obj === void 0;
};
// Utility Functions
// -----------------
// Run Underscore.js in *noConflict* mode, returning the `_` variable to its
// previous owner. Returns a reference to the Underscore object.
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
// Keep the identity function around for default iterators.
_.identity = function(value) {
return value;
};
// Run a function **n** times.
_.times = function (n, iterator, context) {
for (var i = 0; i < n; i++) iterator.call(context, i);
};
// Add your own custom functions to the Underscore object, ensuring that
// they're correctly added to the OOP wrapper as well.
_.mixin = function(obj) {
each(_.functions(obj), function(name){
addToWrapper(name, _[name] = obj[name]);
});
};
// Generate a unique integer id (unique within the entire client session).
// Useful for temporary DOM ids.
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = idCounter++;
return prefix ? prefix + id : id;
};
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
_.templateSettings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%=([\s\S]+?)%>/g
};
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
_.template = function(str, data) {
var c = _.templateSettings;
var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
'with(obj||{}){__p.push(\'' +
str.replace(/\\/g, '\\\\')
.replace(/'/g, "\\'")
.replace(c.interpolate, function(match, code) {
return "'," + code.replace(/\\'/g, "'") + ",'";
})
.replace(c.evaluate || null, function(match, code) {
return "');" + code.replace(/\\'/g, "'")
.replace(/[\r\n\t]/g, ' ') + "__p.push('";
})
.replace(/\r/g, '\\r')
.replace(/\n/g, '\\n')
.replace(/\t/g, '\\t')
+ "');}return __p.join('');";
var func = new Function('obj', tmpl);
return data ? func(data) : func;
};
// The OOP Wrapper
// ---------------
// If Underscore is called as a function, it returns a wrapped object that
// can be used OO-style. This wrapper holds altered versions of all the
// underscore functions. Wrapped objects may be chained.
var wrapper = function(obj) { this._wrapped = obj; };
// Expose `wrapper.prototype` as `_.prototype`
_.prototype = wrapper.prototype;
// Helper function to continue chaining intermediate results.
var result = function(obj, chain) {
return chain ? _(obj).chain() : obj;
};
// A method to easily add functions to the OOP wrapper.
var addToWrapper = function(name, func) {
wrapper.prototype[name] = function() {
var args = slice.call(arguments);
unshift.call(args, this._wrapped);
return result(func.apply(_, args), this._chain);
};
};
// Add all of the Underscore functions to the wrapper object.
_.mixin(_);
// Add all mutator Array functions to the wrapper.
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
method.apply(this._wrapped, arguments);
return result(this._wrapped, this._chain);
};
});
// Add all accessor Array functions to the wrapper.
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
wrapper.prototype[name] = function() {
return result(method.apply(this._wrapped, arguments), this._chain);
};
});
// Start chaining a wrapped Underscore object.
wrapper.prototype.chain = function() {
this._chain = true;
return this;
};
// Extracts the result from a wrapped and chained object.
wrapper.prototype.value = function() {
return this._wrapped;
};
})();
| ilangorajagopal/ilangorajagopal.github.io | node_modules/nomnom/node_modules/underscore/underscore.js | JavaScript | mit | 29,079 |
(function(){var a={months:"一月_二月_三月_四月_五月_六月_七月_八月_九月_十月_十一月_十二月".split("_"),monthsShort:"1月_2月_3月_4月_5月_6月_7月_8月_9月_10月_11月_12月".split("_"),weekdays:"星期日_星期一_星期二_星期三_星期四_星期五_星期六".split("_"),weekdaysShort:"周日_周一_周二_周三_周四_周五_周六".split("_"),longDateFormat:{LT:"Ah:mm",L:"YYYY/MM/DD",LL:"YYYY年M月D日",LLL:"YYYY年M月D日 LT",LLLL:"YYYY年M月D日 dddd LT"},meridiem:{AM:"上午",am:"上午",PM:"下午",pm:"下午"},calendar:{sameDay:"[今天] LT",nextDay:"[明天] LT",nextWeek:"[下]dddd LT",lastDay:"[昨天] LT",lastWeek:"[上]dddd LT",sameElse:"L"},relativeTime:{future:"%s后",past:"%s前",s:"几秒",m:"1分钟",mm:"%d分钟",h:"1小时",hh:"%d小时",d:"1天",dd:"%d天",M:"1个月",MM:"%d个月",y:"1年",yy:"%d年"},ordinal:function(a){return""}};typeof module!="undefined"&&(module.exports=a),typeof window!="undefined"&&this.moment&&this.moment.lang&&this.moment.lang("zh-cn",a)})(); | eduardo-costa/cdnjs | ajax/libs/moment.js/1.6.0/lang/zh-cn.min.js | JavaScript | mit | 1,043 |
.hljs{display:block;overflow-x:auto;padding:0.5em;background:#002b36;color:#839496;-webkit-text-size-adjust:none}.hljs-comment,.diff .hljs-header,.hljs-doctype,.hljs-pi,.lisp .hljs-string{color:#586e75}.hljs-keyword,.hljs-winutils,.method,.hljs-addition,.css .hljs-tag,.hljs-request,.hljs-status,.nginx .hljs-title{color:#859900}.hljs-number,.hljs-command,.hljs-string,.hljs-tag .hljs-value,.hljs-rule .hljs-value,.hljs-doctag,.tex .hljs-formula,.hljs-regexp,.hljs-hexcolor,.hljs-link_url{color:#2aa198}.hljs-title,.hljs-localvars,.hljs-chunk,.hljs-decorator,.hljs-built_in,.hljs-identifier,.vhdl .hljs-literal,.hljs-id,.css .hljs-function,.hljs-name{color:#268bd2}.hljs-attribute,.hljs-variable,.lisp .hljs-body,.smalltalk .hljs-number,.hljs-constant,.hljs-class .hljs-title,.hljs-parent,.hljs-type,.hljs-link_reference{color:#b58900}.hljs-preprocessor,.hljs-preprocessor .hljs-keyword,.hljs-pragma,.hljs-shebang,.hljs-symbol,.hljs-symbol .hljs-string,.diff .hljs-change,.hljs-special,.hljs-attr_selector,.hljs-subst,.hljs-cdata,.css .hljs-pseudo,.hljs-header{color:#cb4b16}.hljs-deletion,.hljs-important{color:#dc322f}.hljs-link_label{color:#6c71c4}.tex .hljs-formula{background:#073642} | sashberd/cdnjs | ajax/libs/highlight.js/8.8.0/styles/solarized_dark.min.css | CSS | mit | 1,189 |
YUI.add("io-nodejs",function(e,t){e.IO.request||(e.IO.request=require("request").defaults({jar:!1}));var n=require("http").STATUS_CODES,r=function(e){var t=[];return Object.keys(e).forEach(function(n){t.push(n+": "+e[n])}),t.join("\n")};e.IO.transports.nodejs=function(){return{send:function(t,i,s){s.notify("start",t,s),s.method=s.method||"GET",s.method=s.method.toUpperCase();var o={method:s.method,uri:i};s.data&&(e.Lang.isObject(s.data)?e.QueryString&&e.QueryString.stringify&&(o.body=e.QueryString.stringify(s.data)):e.Lang.isString(s.data)&&(o.body=s.data),o.method==="GET"&&(o.uri+=(o.uri.indexOf("?")>-1?"&":"?")+o.body,o.body="")),s.headers&&(o.headers=s.headers),s.timeout&&(o.timeout=s.timeout),s.request&&e.mix(o,s.request),e.IO.request(o,function(e,i){if(e){t.c=e,s.notify(e.code==="ETIMEDOUT"?"timeout":"failure",t,s);return}i&&(t.c={status:i.statusCode,statusCode:i.statusCode,statusText:n[i.statusCode],headers:i.headers,responseText:i.body,responseXML:null,getResponseHeader:function(e){return this.headers[e]},getAllResponseHeaders:function(){return r(this.headers)}}),s.notify("complete",t,s),s.notify(i&&i.statusCode>=200&&i.statusCode<=299?"success":"failure",t,s)});var u={io:t};return u}}},e.IO.defaultTransport("nodejs")},"@VERSION@",{requires:["io-base"]});
| svvitale/cdnjs | ajax/libs/yui/3.7.0/io-nodejs/io-nodejs-min.js | JavaScript | mit | 1,283 |
YUI.add("graphics-canvas",function(e,t){function T(){}function N(e){N.superclass.constructor.apply(this,arguments)}var n="canvas",r="shape",i=/[a-z][^a-z]*/ig,s=/[-]?[0-9]*[0-9|\.][0-9]*/g,o=e.config.doc,u=e.Lang,a=e.AttributeLite,f,l,c,h,p,d,v=e.DOM,m=e.Color,g=parseInt,y=parseFloat,b=u.isNumber,w=RegExp,E=m.toRGB,S=m.toHex,x=e.ClassNameManager.getClassName;T.prototype={_pathSymbolToMethod:{M:"moveTo",m:"relativeMoveTo",L:"lineTo",l:"relativeLineTo",C:"curveTo",c:"relativeCurveTo",Q:"quadraticCurveTo",q:"relativeQuadraticCurveTo",z:"closePath",Z:"closePath"},_currentX:0,_currentY:0,_toRGBA:function(e,t){return t=t!==undefined?t:1,m.re_RGB.test(e)||(e=S(e)),m.re_hex.exec(e)&&(e="rgba("+[g(w.$1,16),g(w.$2,16),g(w.$3,16)].join(",")+","+t+")"),e},_toRGB:function(e){return E(e)},setSize:function(e,t){this.get("autoSize")&&(e>this.node.getAttribute("width")&&(this.node.style.width=e+"px",this.node.setAttribute("width",e)),t>this.node.getAttribute("height")&&(this.node.style.height=t+"px",this.node.setAttribute("height",t)))},_updateCoords:function(e,t){this._xcoords.push(e),this._ycoords.push(t),this._currentX=e,this._currentY=t},_clearAndUpdateCoords:function(){var e=this._xcoords.pop()||0,t=this._ycoords.pop()||0;this._updateCoords(e,t)},_updateNodePosition:function(){var e=this.get("node"),t=this.get("x"),n=this.get("y");e.style.position="absolute",e.style.left=t+this._left+"px",e.style.top=n+this._top+"px"},_updateDrawingQueue:function(e){this._methods.push(e)},lineTo:function(){this._lineTo.apply(this,[e.Array(arguments),!1])},relativeLineTo:function(){this._lineTo.apply(this,[e.Array(arguments),!0])},_lineTo:function(e,t){var n=e[0],r,i,s,o,u=this._stroke&&this._strokeWeight?this._strokeWeight:0,a=t?parseFloat(this._currentX):0,f=t?parseFloat(this._currentY):0;this._lineToMethods||(this._lineToMethods=[]),i=e.length-1;if(typeof n=="string"||typeof n=="number")for(r=0;r<i;r+=2)s=parseFloat(e[r]),o=parseFloat(e[r+1]),s+=a,o+=f,this._updateDrawingQueue(["lineTo",s,o]),this._trackSize(s-u,o-u),this._trackSize(s+u,o+u),this._updateCoords(s,o);else for(r=0;r<i;r+=1)s=parseFloat(e[r][0]),o=parseFloat(e[r][1]),this._updateDrawingQueue(["lineTo",s,o]),this._lineToMethods[this._lineToMethods.length]=this._methods[this._methods.length-1],this._trackSize(s-u,o-u),this._trackSize(s+u,o+u),this._updateCoords(s,o);return this._drawingComplete=!1,this},moveTo:function(){this._moveTo.apply(this,[e.Array(arguments),!1])},relativeMoveTo:function(){this._moveTo.apply(this,[e.Array(arguments),!0])},_moveTo:function(e,t){var n=this._stroke&&this._strokeWeight?this._strokeWeight:0,r=t?parseFloat(this._currentX):0,i=t?parseFloat(this._currentY):0,s=parseFloat(e[0])+r,o=parseFloat(e[1])+i;return this._updateDrawingQueue(["moveTo",s,o]),this._trackSize(s-n,o-n),this._trackSize(s+n,o+n),this._updateCoords(s,o),this._drawingComplete=!1,this},curveTo:function(){this._curveTo.apply(this,[e.Array(arguments),!1])},relativeCurveTo:function(){this._curveTo.apply(this,[e.Array(arguments),!0])},_curveTo:function(e,t){var n,r,i,s,o,u,a,f,l,c,h,p,d,v,m,g=t?parseFloat(this._currentX):0,y=t?parseFloat(this._currentY):0;m=e.length-5;for(v=0;v<m;v+=6)i=parseFloat(e[v])+g,s=parseFloat(e[v+1])+y,o=parseFloat(e[v+2])+g,u=parseFloat(e[v+3])+y,a=parseFloat(e[v+4])+g,f=parseFloat(e[v+5])+y,this._updateDrawingQueue(["bezierCurveTo",i,s,o,u,a,f]),this._drawingComplete=!1,c=Math.max(a,Math.max(i,o)),p=Math.max(f,Math.max(s,u)),h=Math.min(a,Math.min(i,o)),d=Math.min(f,Math.min(s,u)),n=Math.abs(c-h),r=Math.abs(p-d),l=[[this._currentX,this._currentY],[i,s],[o,u],[a,f]],this._setCurveBoundingBox(l,n,r),this._currentX=a,this._currentY=f},quadraticCurveTo:function(){this._quadraticCurveTo.apply(this,[e.Array(arguments),!1])},relativeQuadraticCurveTo:function(){this._quadraticCurveTo.apply(this,[e.Array(arguments),!0])},_quadraticCurveTo:function(e,t){var n,r,i,s,o,u,a,f,l,c,h,p,d=e.length-3,v=this._stroke&&this._strokeWeight?this._strokeWeight:0,m=t?parseFloat(this._currentX):0,g=t?parseFloat(this._currentY):0;for(p=0;p<d;p+=4)n=parseFloat(e[p])+m,r=parseFloat(e[p+1])+g,i=parseFloat(e[p+2])+m,s=parseFloat(e[p+3])+g,this._drawingComplete=!1,f=Math.max(i,n),c=Math.max(s,r),l=Math.min(i,n),h=Math.min(s,r),o=Math.abs(f-l),u=Math.abs(c-h),a=[[this._currentX,this._currentY],[n,r],[i,s]],this._setCurveBoundingBox(a,o,u),this._updateDrawingQueue(["quadraticCurveTo",n,r,i,s]),this._updateCoords(i,s);return this},drawCircle:function(e,t,n){var r=0,i=2*Math.PI,s=this._stroke&&this._strokeWeight?this._strokeWeight:0,o=n*2;return o+=s,this._drawingComplete=!1,this._trackSize(e+o,t+o),this._trackSize(e-s,t-s),this._updateCoords(e,t),this._updateDrawingQueue(["arc",e+n,t+n,n,r,i,!1]),this},drawDiamond:function(e,t,n,r){var i=n*.5,s=r*.5;return this.moveTo(e+i,t),this.lineTo(e+n,t+s),this.lineTo(e+i,t+r),this.lineTo(e,t+s),this.lineTo(e+i,t),this},drawEllipse:function(e,t,n,r){var i=8,s=-0.25*Math.PI,o=0,u,a=n/2,f=r/2,l,c=e+a,h=t+f,p,d,v,m,g,y,b=this._stroke&&this._strokeWeight?this._strokeWeight:0;p=c+Math.cos(0)*a,d=h+Math.sin(0)*f,this.moveTo(p,d);for(l=0;l<i;l++)o+=s,u=o-s/2,v=c+Math.cos(o)*a,m=h+Math.sin(o)*f,g=c+Math.cos(u)*(a/Math.cos(s/2)),y=h+Math.sin(u)*(f/Math.cos(s/2)),this._updateDrawingQueue(["quadraticCurveTo",g,y,v,m]);return this._trackSize(e+n+b,t+r+b),this._trackSize(e-b,t-b),this._updateCoords(e,t),this},drawRect:function(e,t,n,r){var i=this._stroke&&this._strokeWeight?this._strokeWeight:0;return this._drawingComplete=!1,this.moveTo(e,t),this.lineTo(e+n,t),this.lineTo(e+n,t+r),this.lineTo(e,t+r),this.lineTo(e,t),this},drawRoundRect:function(e,t,n,r,i,s){var o=this._stroke&&this._strokeWeight?this._strokeWeight:0;return this._drawingComplete=!1,this.moveTo(e,t+s),this.lineTo(e,t+r-s),this.quadraticCurveTo(e,t+r,e+i,t+r),this.lineTo(e+n-i,t+r),this.quadraticCurveTo(e+n,t+r,e+n,t+r-s),this.lineTo(e+n,t+s),this.quadraticCurveTo(e+n,t,e+n-i,t),this.lineTo(e+i,t),this.quadraticCurveTo(e,t,e,t+s),this},drawWedge:function(e,t,n,r,i,s){var o=this._stroke&&this._strokeWeight?this._strokeWeight:0,u,a,f,l,c,h,p,d,v,m,g,y=0;s=s||i,this._drawingComplete=!1,this._updateDrawingQueue(["moveTo",e,t]),s=s||i,Math.abs(r)>360&&(r=360),u=Math.ceil(Math.abs(r)/45),a=r/u,f=-(a/180)*Math.PI,l=n/180*Math.PI;if(u>0){h=e+Math.cos(n/180*Math.PI)*i,p=t+Math.sin(n/180*Math.PI)*s,this.lineTo(h,p);for(y=0;y<u;++y)l+=f,c=l-f/2,d=e+Math.cos(l)*i,v=t+Math.sin(l)*s,m=e+Math.cos(c)*(i/Math.cos(f/2)),g=t+Math.sin(c)*(s/Math.cos(f/2)),this._updateDrawingQueue(["quadraticCurveTo",m,g,d,v]);this._updateDrawingQueue(["lineTo",e,t])}return this._trackSize(-o,-o),this._trackSize(i*2+o,i*2+o),this},end:function(){return this._closePath(),this},closePath:function(){this._updateDrawingQueue(["closePath"]),this._updateDrawingQueue(["beginPath"])},_getLinearGradient:function(){var t=e.Lang.isNumber,n=this.get("fill"),r=n.stops,i,s,o,u,a=r.length,f,l=0,c=0,h=this.get("width"),p=this.get("height"),d=n.rotation||0,v,m,g,y,b=l+h/2,w=c+p/2,S,x=Math.PI/180,T=parseFloat(parseFloat(Math.tan(d*x)).toFixed(8));Math.abs(T)*h/2>=p/2?(d<180?(g=c,y=c+p):(g=c+p,y=c),v=b-(w-g)/T,m=b-(w-y)/T):(d>90&&d<270?(v=l+h,m=l):(v=l,m=l+h),g=(T*(b-v)-w)*-1,y=(T*(b-m)-w)*-1),f=this._context.createLinearGradient(v,g,m,y);for(u=0;u<a;++u)o=r[u],i=o.opacity,s=o.color,S=o.offset,t(i)?(i=Math.max(0,Math.min(1,i)),s=this._toRGBA(s,i)):s=E(s),S=o.offset||u/(a-1),f.addColorStop(S,s);return f},_getRadialGradient:function(){var t=e.Lang.isNumber,n=this.get("fill"),r=n.r,i=n.fx,s=n.fy,o=n.stops,u,a,f,l,c=o.length,h,p=0,d=0,v=this.get("width"),m=this.get("height"),g,y,b,w,S,x,T,N,C,k,L,A,O;x=p+v/2,T=d+m/2,g=v*i,b=m*s,y=p+v/2,w=d+m/2,S=v*r,k=Math.sqrt(Math.pow(Math.abs(x-g),2)+Math.pow(Math.abs(T-b),2)),k>=S&&(A=k/S,A===1&&(A=1.01),N=(g-x)/A,C=(b-T)/A,N=N>0?Math.floor(N):Math.ceil(N),C=C>0?Math.floor(C):Math.ceil(C),g=x+N,b=T+C),r>=.5?(h=this._context.createRadialGradient(g,b,r,y,w,r*v),O=1):(h=this._context.createRadialGradient(g,b,r,y,w,v/2),O=r*2);for(l=0;l<c;++l)f=o[l],u=f.opacity,a=f.color,L=f.offset,t(u)?(u=Math.max(0,Math.min(1,u)),a=this._toRGBA(a,u)):a=E(a),L=f.offset||l/(c-1),L*=O,L<=1&&h.addColorStop(L,a);return h},_initProps:function(){this._methods=[],this._lineToMethods=[],this._xcoords=[0],this._ycoords=[0],this._width=0,this._height=0,this._left=0,this._top=0,this._right=0,this._bottom=0,this._currentX=0,this._currentY=0},_drawingComplete:!1,_createGraphic:function(t){var n=e.config.doc.createElement("canvas");return n},getBezierData:function(e,t){var n=e.length,r=[],i,s;for(i=0;i<n;++i)r[i]=[e[i][0],e[i][1]];for(s=1;s<n;++s)for(i=0;i<n-s;++i)r[i][0]=(1-t)*r[i][0]+t*r[parseInt(i+1,10)][0],r[i][1]=(1-t)*r[i][1]+t*r[parseInt(i+1,10)][1];return[r[0][0],r[0][1]]},_setCurveBoundingBox:function(e,t,n){var r=0,i=this._currentX,s=i,o=this._currentY,u=o,a=Math.round(Math.sqrt(t*t+n*n)),f=1/a,l=this._stroke&&this._strokeWeight?this._strokeWeight:0,c;for(r=0;r<a;++r)c=this.getBezierData(e,f*r),i=isNaN(i)?c[0]:Math.min(c[0],i),s=isNaN(s)?c[0]:Math.max(c[0],s),o=isNaN(o)?c[1]:Math.min(c[1],o),u=isNaN(u)?c[1]:Math.max(c[1],u);i=Math.round(i*10)/10,s=Math.round(s*10)/10,o=Math.round(o*10)/10,u=Math.round(u*10)/10,this._trackSize(s+l,u+l),this._trackSize(i-l,o-l)},_trackSize:function(e,t){e>this._right&&(this._right=e),e<this._left&&(this._left=e),t<this._top&&(this._top=t),t>this._bottom&&(this._bottom=t),this._width=this._right-this._left,this._height=this._bottom-this._top}},e.CanvasDrawing=T,f=function(t){this._transforms=[],this.matrix=new e.Matrix,f.superclass.constructor.apply(this,arguments)},f.NAME="shape",e.extend(f,e.GraphicBase,e.mix({init:function(){this.initializer.apply(this,arguments)},initializer:function(e){var t=this,n=e.graphic,r=this.get("data");t._initProps(),t.createNode(),t._xcoords=[0],t._ycoords=[0],n&&this._setGraphic(n),r&&t._parsePathData(r),t._updateHandler()},_setGraphic:function(t){var n;t instanceof e.CanvasGraphic?this._graphic=t:(t=e.one(t),n=new e.CanvasGraphic({render:t}),n._appendShape(this),this._graphic=n)},addClass:function(t){var n=e.one(this.get("node"));n.addClass(t)},removeClass:function(t){var n=e.one(this.get("node"));n.removeClass(t)},getXY:function(){var e=this.get("graphic"),t=e.getXY(),n=this.get("x"),r=this.get("y");return[t[0]+n,t[1]+r]},setXY:function(e){var t=this.get("graphic"),n=t.getXY(),r=e[0]-n[0],i=e[1]-n[1];this._set("x",r),this._set("y",i),this._updateNodePosition(r,i)},contains:function(t){return t===e.one(this.node)},test:function(t){return e.one(this.get("node")).test(t)},compareTo:function(e){var t=this.node;return t===e},_getDefaultFill:function(){return{type:"solid",opacity:1,cx:.5,cy:.5,fx:.5,fy:.5,r:.5}},_getDefaultStroke:function(){return{weight:1,dashstyle:"none",color:"#000",opacity:1}},_left:0,_right:0,_top:0,_bottom:0,createNode:function(){var t=this,i=e.config.doc.createElement("canvas"),s=t.get("id"),o=t._camelCaseConcat,u=t.name;t._context=i.getContext("2d"),i.setAttribute("overflow","visible"),i.style.overflow="visible",t.get("visible")||(i.style.visibility="hidden"),i.setAttribute("id",s),s="#"+s,t.node=i,t.addClass(x(r)+" "+x(o(n,r))+" "+x(u)+" "+x(o(n,u)))},on:function(t,n){return e.Node.DOM_EVENTS[t]?e.one("#"+this.get("id")).on(t,n):e.on.apply(this,arguments)},_setStrokeProps:function(t){var n,r,i,s,o,u;t?(n=t.color,r=y(t.weight),i=y(t.opacity),s=t.linejoin||"round",o=t.linecap||"butt",u=t.dashstyle,this._miterlimit=null,this._dashstyle=u&&e.Lang.isArray(u)&&u.length>1?u:null,this._strokeWeight=r,b(r)&&r>0?this._stroke=1:this._stroke=0,b(i)?this._strokeStyle=this._toRGBA(n,i):this._strokeStyle=n,this._linecap=o,s=="round"||s=="bevel"?this._linejoin=s:(s=parseInt(s,10),b(s)&&(this._miterlimit=Math.max(s,1),this._linejoin="miter"))):this._stroke=0},set:function(){var e=this,t=arguments[0];a.prototype.set.apply(e,arguments),e.initialized&&e._updateHandler()},_setFillProps:function(e){var t=b,n,r,i;e?(n=e.color,i=e.type,i=="linear"||i=="radial"?this._fillType=i:n?(r=e.opacity,t(r)?(r=Math.max(0,Math.min(1,r)),n=this._toRGBA(n,r)):n=E(n),this._fillColor=n,this._fillType="solid"):this._fillColor=null):(this._fillType=null,this._fillColor=null)},translate:function(e,t){this._translateX+=e,this._translateY+=t,this._addTransform("translate",arguments)},translateX:function(e){this._translateX+=e,this._addTransform("translateX",arguments)},translateY:function(e){this._translateY+=e,this._addTransform("translateY",arguments)},skew:function(e,t){this._addTransform("skew",arguments)},skewX:function(e){this._addTransform("skewX",arguments)},skewY:function(e){this._addTransform("skewY",arguments)},rotate:function(e){this._rotation=e,this._addTransform("rotate",arguments)},scale:function(e,t){this._addTransform("scale",arguments)},_rotation:0,_transform:"",_addTransform:function(t,n){n=e.Array(n),this._transform=u.trim(this._transform+" "+t+"("+n.join(", ")+")"),n.unshift(t),this._transforms.push(n),this.initialized&&this._updateTransform()},_updateTransform:function(){var e=this.node,t,n,r=this.get("transformOrigin"),i=this.matrix,s,o=this._transforms.length;if(this._transforms&&this._transforms.length>0){for(s=0;s<o;++s)t=this._transforms[s].shift(),t&&i[t].apply(i,this._transforms[s]);n=i.toCSSText()}this._graphic.addToRedrawQueue(this),r=100*r[0]+"% "+100*r[1]+"%",v.setStyle(e,"transformOrigin",r),n&&v.setStyle(e,"transform",n),this._transforms=[]},_updateHandler:function(){this._draw(),this._updateTransform()},_draw:function(){var e=this.node;this.clear(),this._closePath(),e.style.left=this.get("x")+"px",e.style.top=this.get("y")+"px"},_closePath:function(){if(!this._methods)return;var e=this.get("node"),t=this._right-this._left,n=this._bottom-this._top,r=this._context,i=[],s=this._methods.concat(),o,u,a,f,l,c=0;this._context.clearRect(0,0,e.width,e.height);if(this._methods){c=s.length;if(!c||c<1)return;for(o=0;o<c;++o){i[o]=s[o].concat(),f=i[o],l=f[0]=="quadraticCurveTo"||f[0]=="bezierCurveTo"?f.length:3;for(u=1;u<l;++u)u%2===0?f[u]=f[u]-this._top:f[u]=f[u]-this._left}e.setAttribute("width",Math.min(t,2e3)),e.setAttribute("height",Math.min(2e3,n)),r.beginPath();for(o=0;o<c;++o)f=i[o].concat(),f&&f.length>0&&(a=f.shift(),a&&(a=="closePath"?(r.closePath(),this._strokeAndFill(r)):a&&a=="lineTo"&&this._dashstyle?(f.unshift(this._xcoords[o]-this._left,this._ycoords[o]-this._top),this._drawDashedLine.apply(this,f)):r[a].apply(r,f)));this._strokeAndFill(r),this._drawingComplete=!0,this._clearAndUpdateCoords(),this._updateNodePosition(),this._methods=s}},_strokeAndFill:function(e){this._fillType&&(this._fillType=="linear"?e.fillStyle=this._getLinearGradient():this._fillType=="radial"?e.fillStyle=this._getRadialGradient():e.fillStyle=this._fillColor,e.closePath(),e.fill()),this._stroke&&(this._strokeWeight&&(e.lineWidth=this._strokeWeight),e.lineCap=this._linecap,e.lineJoin=this._linejoin,this._miterlimit&&(e.miterLimit=this._miterlimit),e.strokeStyle=this._strokeStyle,e.stroke())},_drawDashedLine:function(e,t,n,r){var i=this._context,s=this._dashstyle[0],o=this._dashstyle[1],u=s+o,a=n-e,f=r-t,l=Math.sqrt(Math.pow(a,2)+Math.pow(f,2)),c=Math.floor(Math.abs(l/u)),h=Math.atan2(f,a),p=e,d=t,v;a=Math.cos(h)*u,f=Math.sin(h)*u;for(v=0;v<c;++v)i.moveTo(p,d),i.lineTo(p+Math.cos(h)*s,d+Math.sin(h)*s),p+=a,d+=f;i.moveTo(p,d),l=Math.sqrt((n-p)*(n-p)+(r-d)*(r-d)),l>s?i.lineTo(p+Math.cos(h)*s,d+Math.sin(h)*s):l>0&&i.lineTo(p+Math.cos(h)*l,d+Math.sin(h)*l),i.moveTo(n,r)},clear:function(){return this._initProps(),this.node&&this._context.clearRect(0,0,this.node.width,this.node.height),this},getBounds:function(){var e=this._type,t=this.get("width"),n=this.get("height"),r=this.get("x"),i=this.get("y");return e=="path"&&(r+=this._left,i+=this._top,t=this._right-this._left,n=this._bottom-this._top),this._getContentRect(t,n,r,i)},_getContentRect:function(t,n,r,i){var s=this.get("transformOrigin"),o=s[0]*t,u=s[1]*n,a=this.matrix.getTransformArray(this.get("transform")),f=new e.Matrix,l,c=a.length,h,p,d;this._type=="path"&&(o+=r,u+=i),o=isNaN(o)?0:o,u=isNaN(u)?0:u,f.translate(o,u);for(l=0;l<c;l+=1)h=a[l],p=h.shift(),p&&f[p].apply(f,h);return f.translate(-o,-u),d=f.getContentRect(t,n,r,i),d},toFront:function(){var e=this.get("graphic");e&&e._toFront(this)},toBack:function(){var e=this.get("graphic");e&&e._toBack(this)},_parsePathData:function(t){var n,r,o,u=e.Lang.trim(t.match(i)),a,f,l,c=this._pathSymbolToMethod;if(u){this.clear(),f=u.length||0;for(a=0;a<f;a+=1)l=u[a],r=l.substr(0,1),o=l.substr(1).match(s),n=c[r],n&&(o?this[n].apply(this,o):this[n].apply(this));this.end()}},destroy:function(){var e=this.get("graphic");e?e.removeShape(this):this._destroy()},_destroy:function(){this.node&&(e.one(this.node).remove(!0),this._context=null,this.node=null)}},e.CanvasDrawing.prototype)),f.ATTRS={transformOrigin:{valueFn:function(){return[.5,.5]}},transform:{setter:function(e){return this.matrix.init(),this._transforms=this.matrix.getTransformArray(e),this._transform=e,e},getter:function(){return this._transform}},node:{readOnly:!0,getter:function(){return this.node}},id:{valueFn:function(){return e.guid()},setter:function(e){var t=this.node;return t&&t.setAttribute("id",e),e}},width:{value:0},height:{value:0},x:{value:0},y:{value:0},visible:{value:!0,setter:function(e){var t=this.get("node"),n=e?"visible":"hidden";return t&&(t.style.visibility=n),e}},fill:{valueFn:"_getDefaultFill",setter:function(t){var n,r=this.get("fill")||this._getDefaultFill();return n=t?e.merge(r,t):null,n&&n.color&&(n.color===undefined||n.color=="none")&&(n.color=null),this._setFillProps(n),n}},stroke:{valueFn:"_getDefaultStroke",setter:function(t){var n=this.get("stroke")||this._getDefaultStroke(),r;return t&&t.hasOwnProperty("weight")&&(r=parseInt(t.weight,10),isNaN(r)||(t.weight=r)),t=t?e.merge(n,t):null,this._setStrokeProps(t),t}},autoSize:{value:!1},pointerEvents:{value:"visiblePainted"},data:{setter:function(e){return this.get("node")&&this._parsePathData(e),e}},graphic:{readOnly:!0,getter:function(){return this._graphic}}},e.CanvasShape=f,l=function(e){l.superclass.constructor.apply(this,arguments)},l.NAME="path",e.extend(l,e.CanvasShape,{_type:"path",_draw:function(){this._closePath(),this._updateTransform()},createNode:function(){var t=this,i=e.config.doc.createElement("canvas"),s=t.name,o=t._camelCaseConcat,u=t.get("id");t._context=i.getContext("2d"),i.setAttribute("overflow","visible"),i.setAttribute("pointer-events","none"),i.style.pointerEvents="none",i.style.overflow="visible",i.setAttribute("id",u),u="#"+u,t.node=i,t.addClass(x(r)+" "+x(o(n,r))+" "+x(s)+" "+x(o(n,s)))},end:function(){this._draw()}}),l.ATTRS=e.merge(e.CanvasShape.ATTRS,{width:{getter:function(){var e=this._stroke&&this._strokeWeight?this._strokeWeight*2:0;return this._width-e},setter:function(e){return this._width=e,e}},height:{getter:function(){var e=this._stroke&&this._strokeWeight?this._strokeWeight*2:0;return this._height-e},setter:function(e){return this._height=e,e}},path:{readOnly:!0,getter:function(){return this._path}}}),e.CanvasPath=l,c=function(){c.superclass.constructor.apply(this,arguments)},c.NAME="rect",e.extend(c,e.CanvasShape,{_type:"rect",_draw:function(){var e=this.get("width"),t=this.get("height");this.clear(),this.drawRect(0,0,e,t),this._closePath()}}),c.ATTRS=e.CanvasShape.ATTRS,e.CanvasRect=c,h=function(e){h.superclass.constructor.apply(this,arguments)},h.NAME="ellipse",e.extend(h,f,{_type:"ellipse",_draw:function(){var e=this.get("width"),t=this.get("height");this.clear(),this.drawEllipse(0,0,e,t),this._closePath()}}),h.ATTRS=e.merge(f.ATTRS,{xRadius:{setter:function(e){this.set("width",e*2)},getter:function(){var e=this.get("width");return e&&(e*=.5),e}},yRadius:{setter:function(e){this.set("height",e*2)},getter:function(){var e=this.get("height");return e&&(e*=.5),e}}}),e.CanvasEllipse=h,p=function(e){p.superclass.constructor.apply(this,arguments)},p.NAME="circle",e.extend(p,e.CanvasShape,{_type:"circle",_draw:function(){var e=this.get("radius");e&&(this.clear(),this.drawCircle(0,0,e),this._closePath())}}),p.ATTRS=e.merge(e.CanvasShape.ATTRS,{width:{setter:function(e){return this.set("radius",e/2),e},getter:function(){return this.get("radius")*2}},height:{setter:function(e){return this.set("radius",e/2),e},getter:function(){return this.get("radius")*2}},radius:{lazyAdd:!1}}),e.CanvasCircle=p,d=function(){d.superclass.constructor.apply(this,arguments)},d.NAME="canvasPieSlice",e.extend(d,e.CanvasShape,{_type:"path",_draw:function(e){var t=this.get("cx"),n=this.get("cy"),r=this.get("startAngle"),i=this.get("arc"),s=this.get("radius");this.clear(),this._left=t,this._right=s,this._top=n,this._bottom=s,this.drawWedge(t,n,r,i,s),this.end()}}),d.ATTRS=e.mix({cx:{value:0},cy:{value:0},startAngle:{value:0},arc:{value:0},radius:{value:0}},e.CanvasShape.ATTRS),e.CanvasPieSlice=d,N.NAME="canvasGraphic",N.ATTRS={render:{},id:{valueFn:function(){return e.guid()},setter:function(e){var t=this._node;return t&&t.setAttribute("id",e),e}},shapes:{readOnly:!0,getter:function(){return this._shapes}},contentBounds:{readOnly:!0,getter:function(){return this._contentBounds}},node:{readOnly:!0,getter:function(){return this._node}},width:{setter:function(e){return this._node&&(this._node.style.width=e+"px"),e}},height:{setter:function(e){return this._node&&(this._node.style.height=e+"px"),e}},autoSize:{value:!1},preserveAspectRatio:{value:"xMidYMid"},resizeDown:{value:!1},x:{getter:function(){return this._x},setter:function(e){return this._x=e,this._node&&(this._node.style.left=e+"px"),e}},y:{getter:function(){return this._y},setter:function(e){return this._y=e,this._node&&(this._node.style.top=e+"px"),e}},autoDraw:{value:!0},visible:{value:!0,setter:function(e){return this._toggleVisible(e),e}}},e.extend(N,e.GraphicBase,{set:function(t,n){var r=this,i={autoDraw:!0,autoSize:!0,preserveAspectRatio:!0,resizeDown:!0},s,o=!1;a.prototype.set.apply(r,arguments);if(r._state.autoDraw===!0&&e.Object.size(this._shapes)>0)if(u.isString&&i[t])o=!0;else if(u.isObject(t))for(s in i)if(i.hasOwnProperty(s)&&t[s]){o=!0;break}o&&r._redraw()},_x:0,_y:0,getXY:function(){var t=e.one(this._node),n;return t&&(n=t.getXY()),n},initializer:function(e){var t=this.get("render"),n=this.get("visible")?"visible":"hidden",r=this.get("width")||0,i=this.get("height")||0;this._shapes={},this._redrawQueue={},this._contentBounds={left:0,top:0,right:0,bottom:0},this._node=o.createElement("div"),this._node.style.position="absolute",this._node.style.visibility=n,this.set("width",r),this.set("height",i),t&&this.render(t)},render:function(t){var n=e.one(t),r=this._node,i=this.get("width")||parseInt(n.getComputedStyle("width"),10),s=this.get("height")||parseInt(n.getComputedStyle("height"),10);return n=n||o.body,n.appendChild(r),r.style.display="block",r.style.position="absolute",r.style.left="0px",r.style.top="0px",this.set("width",i),this.set("height",s),this.parentNode=n,this},destroy:function(){this.removeAllShapes(),this._node&&(this._removeChildren(this._node),e.one(this._node).destroy())},addShape:function(e){e.graphic=this,this.get("visible")||(e.visible=!1);var t=this._getShapeClass(e.type),n=new t(e);return this._appendShape(n),n},_appendShape:function(e){var t=e.node,n=this._frag||this._node;this.get("autoDraw")?n.appendChild(t):this._getDocFrag().appendChild(t)},removeShape:function(e){return e instanceof f||u.isString(e)&&(e=this._shapes[e]),e&&e instanceof f&&(e._destroy(),delete this._shapes[e.get("id")]),this.get("autoDraw")&&this._redraw(),e},removeAllShapes:function(){var e=this._shapes,t;for(t in e)e.hasOwnProperty(t)&&e[t].destroy();this._shapes={}},clear:function(){this.removeAllShapes()},_removeChildren:function(e){if(e&&e.hasChildNodes()){var t;while(e.firstChild)t=e.firstChild,this._removeChildren(t),e.removeChild(t)}},_toggleVisible:function(e){var t,n=this._shapes,r=e?"visible":"hidden";if(n)for(t in n)n.hasOwnProperty(t)&&n[t].set("visible",e);this._node&&(this._node.style.visibility=r)},_getShapeClass:function(e){var t=this._shapeClass[e];return t?t:e},_shapeClass:{circle:e.CanvasCircle,rect:e.CanvasRect,path:e.CanvasPath,ellipse:e.CanvasEllipse,pieslice:e.CanvasPieSlice},getShapeById:function(e){var t=this._shapes[e];return t},batch:function(e){var t=this.get("autoDraw");this.set("autoDraw",!1),e(),this.set("autoDraw",t)},_getDocFrag:function(){return this._frag||(this._frag=o.createDocumentFragment()),this._frag},_redraw:function(){var t=this.get("autoSize"),n=this.get("preserveAspectRatio"),r=this.get("resizeDown")?this._getUpdatedContentBounds():this._contentBounds,i,s,o,u,a,f,l=0,c=0,h,p=this.get("node");t&&(t=="sizeContentToGraphic"?(i=r.right-r.left,s=r.bottom-r.top,o=parseFloat(v.getComputedStyle(p,"width")),u=parseFloat(v.getComputedStyle(p,"height")),h=new e.Matrix,n=="none"?(a=o/i,f=u/s):i/s!==o/u&&(i*u/s>o?(a=f=o/i,c=this._calculateTranslate(n.slice(5).toLowerCase(),s*o/i,u)):(a=f=u/s,l=this._calculateTranslate(n.slice(1,4).toLowerCase(),i*u/s,o))),v.setStyle(p,"transformOrigin","0% 0%"),l-=r.left*a,c-=r.top*f,h.translate(l,c),h.scale(a,f),v.setStyle(p,"transform",h.toCSSText())):(this.set("width",r.right),this.set("height",r.bottom))),this._frag&&(this._node.appendChild(this._frag),this._frag=null)},_calculateTranslate:function(e,t,n){var r=n-t,i;switch(e){case"mid":i=r*.5;break;case"max":i=r;break;default:i=0}return i},addToRedrawQueue:function(e){var t,n;this._shapes[e.get("id")]=e,this.get("resizeDown")||(t=e.getBounds(),n=this._contentBounds,n.left=n.left<t.left?n.left:t.left,n.top=n.top<t.top?n.top:t.top,n.right=n.right>t.right?n.right:t.right,n.bottom=n.bottom>t.bottom?n.bottom:t.bottom,this._contentBounds=n),this.get("autoDraw")&&this._redraw()},_getUpdatedContentBounds:function(){var e,t,n,r=this._shapes,i={};for(t in r)r.hasOwnProperty(t)&&(n=r[t],e=n.getBounds(),i.left=u.isNumber(i.left)?Math.min(i.left,e.left):e.left,i.top=u.isNumber(i.top)?Math.min(i.top,e.top):e.top,i.right=u.isNumber(i.right)?Math.max(i.right,e.right):e.right,i.bottom=u.isNumber(i.bottom)?Math.max(i.bottom,e.bottom):e.bottom);return i.left=u.isNumber(i.left)?i.left:0,i.top=u.isNumber(i.top)?i.top:0,i.right=u.isNumber(i.right)?i.right:0,i.bottom=u.isNumber(i.bottom)?i.bottom:0,this._contentBounds=i,i},_toFront:function(t){var n=this.get("node");t instanceof e.CanvasShape&&(t=t.get("node")),n&&t&&n.appendChild(t)},_toBack:function(t){var n=this.get("node"),r;t instanceof e.CanvasShape&&(t=t.get("node")),n&&t&&(r=n.firstChild,r?n.insertBefore(t,r):n.appendChild(t))}}),e.CanvasGraphic=N},"@VERSION@",{requires:["graphics"]});
| advancedpartnerships/cdnjs | ajax/libs/yui/3.8.0/graphics-canvas/graphics-canvas-min.js | JavaScript | mit | 26,459 |
<?php
/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Symfony\Component\Translation\Tests\Loader;
use Symfony\Component\Translation\Loader\CsvFileLoader;
use Symfony\Component\Config\Resource\FileResource;
class CsvFileLoaderTest extends \PHPUnit_Framework_TestCase
{
public function testLoad()
{
$loader = new CsvFileLoader();
$resource = __DIR__.'/../fixtures/resources.csv';
$catalogue = $loader->load($resource, 'en', 'domain1');
$this->assertEquals(array('foo' => 'bar'), $catalogue->all('domain1'));
$this->assertEquals('en', $catalogue->getLocale());
$this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
}
public function testLoadDoesNothingIfEmpty()
{
$loader = new CsvFileLoader();
$resource = __DIR__.'/../fixtures/empty.csv';
$catalogue = $loader->load($resource, 'en', 'domain1');
$this->assertEquals(array(), $catalogue->all('domain1'));
$this->assertEquals('en', $catalogue->getLocale());
$this->assertEquals(array(new FileResource($resource)), $catalogue->getResources());
}
/**
* @expectedException \Symfony\Component\Translation\Exception\NotFoundResourceException
*/
public function testLoadNonExistingResource()
{
$loader = new CsvFileLoader();
$resource = __DIR__.'/../fixtures/not-exists.csv';
$loader->load($resource, 'en', 'domain1');
}
/**
* @expectedException \Symfony\Component\Translation\Exception\InvalidResourceException
*/
public function testLoadNonLocalResource()
{
$loader = new CsvFileLoader();
$resource = 'http://example.com/resources.csv';
$loader->load($resource, 'en', 'domain1');
}
}
| innova-re/_input | vendor/symfony/symfony/src/Symfony/Component/Translation/Tests/Loader/CsvFileLoaderTest.php | PHP | mit | 1,978 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.