Skip to content

Instantly share code, notes, and snippets.

@alejandro
Created January 18, 2013 22:42
Show Gist options
  • Select an option

  • Save alejandro/4569323 to your computer and use it in GitHub Desktop.

Select an option

Save alejandro/4569323 to your computer and use it in GitHub Desktop.
var Store = (function() {
var USE_LOCAL_STORAGE = true;
var _store = USE_LOCAL_STORAGE && window.localStorage || {};
return {
get: function(key) {
if (_store[key] !== undefined) {
try {
return JSON.parse(_store[key]);
} catch (e) {}
}
},
set: function(key, val) {
_store[key] = JSON.stringify(val);
},
clear: function() {
if (window.localStorage && _store === window.localStorage && window.localStorage.clear) {
window.localStorage.clear();
} else {
_store = {};
}
}
};
})();
(function() {
var method;
var noop = function noop() {};
var methods = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'];
var length = methods.length;
var console = (window.console = window.console || {});
while (length--) {
method = methods[length];
if (!console[method]) {
console[method] = noop;
}
}
}());
var util = {
stringToBytes: function(s) {
return encodeURI(s)
.split(/%..|./)
.length - 1;
},
prettyFileSize: function(bytes) {
var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / Math.pow(1024, Math.floor(e)))
.toFixed(2) + " " + s[e];
}
};
function guid() {
function S4() {
return (((1 + Math.random()) * 0x10000) | 0)
.toString(16)
.substring(1);
}
return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
window.log = function() {
if (typeof console != 'undefined' && typeof console.log == 'function') {
if ((Array.prototype.slice.call(arguments))
.length === 1 && typeof Array.prototype.slice.call(arguments)[0] === 'string') {
console.log((Array.prototype.slice.call(arguments))
.toString());
} else {
console.log(Array.prototype.slice.call(arguments));
}
}
};
(function() {
var test = document.createElement('input');
try {
test.type = 'range';
if (test.type == 'range') return;
} catch (e) {
return;
}
if (!document.mozSetImageElement || !('MozAppearance' in test.style)) return;
var scale;
var isMac = navigator.platform == 'MacIntel';
var thumb = {
radius: isMac ? 9 : 6,
width: isMac ? 22 : 12,
height: isMac ? 16 : 20
};
var track = '-moz-linear-gradient(top, transparent ' + (isMac ? '6px, #999 6px, #999 7px, #ccc 9px, #bbb 11px, #bbb 12px, transparent 12px' : '9px, #999 9px, #bbb 10px, #fff 11px, transparent 11px') + ', transparent)';
var styles = {
'min-width': thumb.width + 'px',
'min-height': thumb.height + 'px',
'max-height': thumb.height + 'px',
padding: 0,
border: 0,
'border-radius': 0,
cursor: 'default',
'text-indent': '-999999px'
};
var onChange = document.createEvent('HTMLEvents');
onChange.initEvent('change', true, false);
if (document.readyState == 'loading') document.addEventListener('DOMContentLoaded', initialize, true);
else initialize();
function initialize() {
Array.forEach(document.querySelectorAll('input[type=range]'), transform);
document.addEventListener('DOMNodeInserted', onNodeInserted, true);
}
function onNodeInserted(e) {
check(e.target);
if (e.target.querySelectorAll) Array.forEach(e.target.querySelectorAll('input'), check);
}
function check(input, async) {
if (input.localName != 'input' || input.type == 'range');
else if (input.getAttribute('type') == 'range') transform(input);
else if (!async) setTimeout(check, 0, input, true);
}
function transform(slider) {
var isValueSet, areAttrsSet, isChanged, isClick, prevValue, rawValue, prevX;
var min, max, step, range, value = slider.value;
if (!scale) {
scale = document.body.appendChild(document.createElement('hr'));
style(scale, {
'-moz-appearance': isMac ? 'scale-horizontal' : 'scalethumb-horizontal',
display: 'block',
visibility: 'visible',
opacity: 1,
position: 'fixed',
top: '-999999px'
});
document.mozSetImageElement('__sliderthumb__', scale);
}
var getValue = function() {
return '' + value;
};
var setValue = function setValue(val) {
value = '' + val;
isValueSet = true;
draw();
delete slider.value;
slider.value = value;
slider.__defineGetter__('value', getValue);
slider.__defineSetter__('value', setValue);
};
slider.__defineGetter__('value', getValue);
slider.__defineSetter__('value', setValue);
slider.__defineGetter__('type', function() {
return 'range';
});
['min', 'max', 'step'].forEach(function(prop) {
if (slider.hasAttribute(prop)) areAttrsSet = true;
slider.__defineGetter__(prop, function() {
return this.hasAttribute(prop) ? this.getAttribute(prop) : '';
});
slider.__defineSetter__(prop, function(val) {
val === null ? this.removeAttribute(prop) : this.setAttribute(prop, val);
});
});
slider.readOnly = true;
style(slider, styles);
update();
slider.addEventListener('DOMAttrModified', function(e) {
if (e.attrName == 'value' && !isValueSet) {
value = e.newValue;
draw();
} else if (~ ['min', 'max', 'step'].indexOf(e.attrName)) {
update();
areAttrsSet = true;
}
}, true);
slider.addEventListener('mousedown', onDragStart, true);
slider.addEventListener('keydown', onKeyDown, true);
slider.addEventListener('focus', onFocus, true);
slider.addEventListener('blur', onBlur, true);
function onDragStart(e) {
isClick = true;
setTimeout(function() {
isClick = false;
}, 0);
if (e.button || !range) return;
var width = parseFloat(getComputedStyle(this, 0)
.width);
var multiplier = (width - thumb.width) / range;
if (!multiplier) return;
var dev = e.clientX - this.getBoundingClientRect()
.left - thumb.width / 2 - (value - min) * multiplier;
if (Math.abs(dev) > thumb.radius) {
isChanged = true;
this.value -= -dev / multiplier;
}
rawValue = value;
prevX = e.clientX;
this.addEventListener('mousemove', onDrag, true);
this.addEventListener('mouseup', onDragEnd, true);
}
function onDrag(e) {
var width = parseFloat(getComputedStyle(this, 0)
.width);
var multiplier = (width - thumb.width) / range;
if (!multiplier) return;
rawValue += (e.clientX - prevX) / multiplier;
prevX = e.clientX;
isChanged = true;
this.value = rawValue;
}
function onDragEnd() {
this.removeEventListener('mousemove', onDrag, true);
this.removeEventListener('mouseup', onDragEnd, true);
}
function onKeyDown(e) {
if (e.keyCode > 36 && e.keyCode < 41) {
onFocus.call(this);
isChanged = true;
this.value = value + (e.keyCode == 38 || e.keyCode == 39 ? step : -step);
}
}
function onFocus() {
if (!isClick) this.style.boxShadow = !isMac ? '0 0 0 2px #fb0' : '0 0 2px 1px -moz-mac-focusring, inset 0 0 1px -moz-mac-focusring';
}
function onBlur() {
this.style.boxShadow = '';
}
function isAttrNum(value) {
return !isNaN(value) && +value == parseFloat(value);
}
function update() {
min = isAttrNum(slider.min) ? +slider.min : 0;
max = isAttrNum(slider.max) ? +slider.max : 100;
if (max < min) max = min > 100 ? min : 100;
step = isAttrNum(slider.step) && slider.step > 0 ? +slider.step : 1;
range = max - min;
draw(true);
}
function calc() {
if (!isValueSet && !areAttrsSet) value = slider.getAttribute('value');
if (!isAttrNum(value)) value = (min + max) / 2;;
value = Math.round((value - min) / step) * step + min;
if (value < min) value = min;
else if (value > max) value = min + ~~ (range / step) * step;
}
function draw(attrsModified) {
calc();
if (isChanged && value != prevValue) slider.dispatchEvent(onChange);
isChanged = false;
if (!attrsModified && value == prevValue) return;
prevValue = value;
var position = range ? (value - min) / range * 100 : 0;
var bg = '-moz-element(#__sliderthumb__) ' + position + '% no-repeat, ';
style(slider, {
background: bg + track
});
}
}
function style(element, styles) {
for (var prop in styles)
element.style.setProperty(prop, styles[prop], 'important');
}
})();
/*!
jQuery JavaScript Library v1.8.2
http://jquery.com/
Includes Sizzle.js
http://sizzlejs.com/
Copyright 2012 jQuery Foundation and other contributors
Released under the MIT license
http://jquery.org/license
Date: Thu Sep 20 2012 21:13:05 GMT-0400 (Eastern Daylight Time)
*/
(function(window, undefined) {
var
rootjQuery, readyList, document = window.document,
location = window.location,
navigator = window.navigator,
_jQuery = window.jQuery,
_$ = window.$,
core_push = Array.prototype.push,
core_slice = Array.prototype.slice,
core_indexOf = Array.prototype.indexOf,
core_toString = Object.prototype.toString,
core_hasOwn = Object.prototype.hasOwnProperty,
core_trim = String.prototype.trim,
jQuery = function(selector, context) {
return new jQuery.fn.init(selector, context, rootjQuery);
}, core_pnum = /[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,
core_rnotwhite = /\S/,
core_rspace = /\s+/,
rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
rquickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/,
rvalidchars = /^[\],:{}\s]*$/,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,
rmsPrefix = /^-ms-/,
rdashAlpha = /-([\da-z])/gi,
fcamelCase = function(all, letter) {
return (letter + "")
.toUpperCase();
}, DOMContentLoaded = function() {
if (document.addEventListener) {
document.removeEventListener("DOMContentLoaded", DOMContentLoaded, false);
jQuery.ready();
} else if (document.readyState === "complete") {
document.detachEvent("onreadystatechange", DOMContentLoaded);
jQuery.ready();
}
}, class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function(selector, context, rootjQuery) {
var match, elem, ret, doc;
if (!selector) {
return this;
}
if (selector.nodeType) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
if (typeof selector === "string") {
if (selector.charAt(0) === "<" && selector.charAt(selector.length - 1) === ">" && selector.length >= 3) {
match = [null, selector, null];
} else {
match = rquickExpr.exec(selector);
}
if (match && (match[1] || !context)) {
if (match[1]) {
context = context instanceof jQuery ? context[0] : context;
doc = (context && context.nodeType ? context.ownerDocument || context : document);
selector = jQuery.parseHTML(match[1], doc, true);
if (rsingleTag.test(match[1]) && jQuery.isPlainObject(context)) {
this.attr.call(selector, context, true);
}
return jQuery.merge(this, selector);
} else {
elem = document.getElementById(match[2]);
if (elem && elem.parentNode) {
if (elem.id !== match[2]) {
return rootjQuery.find(selector);
}
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
} else if (!context || context.jquery) {
return (context || rootjQuery)
.find(selector);
} else {
return this.constructor(context)
.find(selector);
}
} 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);
},
selector: "",
jquery: "1.8.2",
length: 0,
size: function() {
return this.length;
},
toArray: function() {
return core_slice.call(this);
},
get: function(num) {
return num == null ? this.toArray() : (num < 0 ? this[this.length + num] : this[num]);
},
pushStack: function(elems, name, selector) {
var ret = jQuery.merge(this.constructor(), elems);
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 ret;
},
each: function(callback, args) {
return jQuery.each(this, callback, args);
},
ready: function(fn) {
jQuery.ready.promise()
.done(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(core_slice.apply(this, arguments), "slice", core_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);
},
push: core_push,
sort: [].sort,
splice: [].splice
};
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;
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
i = 2;
}
if (typeof target !== "object" && !jQuery.isFunction(target)) {
target = {};
}
if (length === i) {
target = this;
--i;
}
for (; i < length; i++) {
if ((options = arguments[i]) != null) {
for (name in options) {
src = target[name];
copy = options[name];
if (target === copy) {
continue;
}
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 : {};
}
target[name] = jQuery.extend(deep, clone, copy);
} else if (copy !== undefined) {
target[name] = copy;
}
}
}
}
return target;
};
jQuery.extend({
noConflict: function(deep) {
if (window.$ === jQuery) {
window.$ = _$;
}
if (deep && window.jQuery === jQuery) {
window.jQuery = _jQuery;
}
return jQuery;
},
isReady: false,
readyWait: 1,
holdReady: function(hold) {
if (hold) {
jQuery.readyWait++;
} else {
jQuery.ready(true);
}
},
ready: function(wait) {
if (wait === true ? --jQuery.readyWait : jQuery.isReady) {
return;
}
if (!document.body) {
return setTimeout(jQuery.ready, 1);
}
jQuery.isReady = true;
if (wait !== true && --jQuery.readyWait > 0) {
return;
}
readyList.resolveWith(document, [jQuery]);
if (jQuery.fn.trigger) {
jQuery(document)
.trigger("ready")
.off("ready");
}
},
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[core_toString.call(obj)] || "object";
},
isPlainObject: function(obj) {
if (!obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow(obj)) {
return false;
}
try {
if (obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
return false;
}
} catch (e) {
return false;
}
var key;
for (key in obj) {}
return key === undefined || core_hasOwn.call(obj, key);
},
isEmptyObject: function(obj) {
var name;
for (name in obj) {
return false;
}
return true;
},
error: function(msg) {
throw new Error(msg);
},
parseHTML: function(data, context, scripts) {
var parsed;
if (!data || typeof data !== "string") {
return null;
}
if (typeof context === "boolean") {
scripts = context;
context = 0;
}
context = context || document;
if ((parsed = rsingleTag.exec(data))) {
return [context.createElement(parsed[1])];
}
parsed = jQuery.buildFragment([data], context, scripts ? null : []);
return jQuery.merge([], (parsed.cacheable ? jQuery.clone(parsed.fragment) : parsed.fragment)
.childNodes);
},
parseJSON: function(data) {
if (!data || typeof data !== "string") {
return null;
}
data = jQuery.trim(data);
if (window.JSON && window.JSON.parse) {
return window.JSON.parse(data);
}
if (rvalidchars.test(data.replace(rvalidescape, "@")
.replace(rvalidtokens, "]")
.replace(rvalidbraces, ""))) {
return (new Function("return " + data))();
}
jQuery.error("Invalid JSON: " + data);
},
parseXML: function(data) {
var xml, tmp;
if (!data || typeof data !== "string") {
return null;
}
try {
if (window.DOMParser) {
tmp = new DOMParser();
xml = tmp.parseFromString(data, "text/xml");
} else {
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() {},
globalEval: function(data) {
if (data && core_rnotwhite.test(data)) {
(window.execScript || function(data) {
window["eval"].call(window, data);
})(data);
}
},
camelCase: function(string) {
return string.replace(rmsPrefix, "ms-")
.replace(rdashAlpha, fcamelCase);
},
nodeName: function(elem, name) {
return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
},
each: function(obj, callback, args) {
var name, i = 0,
length = obj.length,
isObj = length === undefined || jQuery.isFunction(obj);
if (args) {
if (isObj) {
for (name in obj) {
if (callback.apply(obj[name], args) === false) {
break;
}
}
} else {
for (; i < length;) {
if (callback.apply(obj[i++], args) === false) {
break;
}
}
}
} else {
if (isObj) {
for (name in obj) {
if (callback.call(obj[name], name, obj[name]) === false) {
break;
}
}
} else {
for (; i < length;) {
if (callback.call(obj[i], i, obj[i++]) === false) {
break;
}
}
}
}
return obj;
},
trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function(text) {
return text == null ? "" : core_trim.call(text);
} : function(text) {
return text == null ? "" : (text + "")
.replace(rtrim, "");
},
makeArray: function(arr, results) {
var type, ret = results || [];
if (arr != null) {
type = jQuery.type(arr);
if (arr.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow(arr)) {
core_push.call(ret, arr);
} else {
jQuery.merge(ret, arr);
}
}
return ret;
},
inArray: function(elem, arr, i) {
var len;
if (arr) {
if (core_indexOf) {
return core_indexOf.call(arr, elem, i);
}
len = arr.length;
i = i ? i < 0 ? Math.max(0, len + i) : i : 0;
for (; i < len; i++) {
if (i in arr && arr[i] === elem) {
return i;
}
}
}
return -1;
},
merge: function(first, second) {
var l = second.length,
i = first.length,
j = 0;
if (typeof l === "number") {
for (; 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 retVal, ret = [],
i = 0,
length = elems.length;
inv = !! inv;
for (; i < length; i++) {
retVal = !! callback(elems[i], i);
if (inv !== retVal) {
ret.push(elems[i]);
}
}
return ret;
},
map: function(elems, callback, arg) {
var value, key, ret = [],
i = 0,
length = elems.length,
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ((length > 0 && elems[0] && elems[length - 1]) || length === 0 || jQuery.isArray(elems));
if (isArray) {
for (; i < length; i++) {
value = callback(elems[i], i, arg);
if (value != null) {
ret[ret.length] = value;
}
}
} else {
for (key in elems) {
value = callback(elems[key], key, arg);
if (value != null) {
ret[ret.length] = value;
}
}
}
return ret.concat.apply([], ret);
},
guid: 1,
proxy: function(fn, context) {
var tmp, args, proxy;
if (typeof context === "string") {
tmp = fn[context];
context = fn;
fn = tmp;
}
if (!jQuery.isFunction(fn)) {
return undefined;
}
args = core_slice.call(arguments, 2);
proxy = function() {
return fn.apply(context, args.concat(core_slice.call(arguments)));
};
proxy.guid = fn.guid = fn.guid || jQuery.guid++;
return proxy;
},
access: function(elems, fn, key, value, chainable, emptyGet, pass) {
var exec, bulk = key == null,
i = 0,
length = elems.length;
if (key && typeof key === "object") {
for (i in key) {
jQuery.access(elems, fn, i, key[i], 1, emptyGet, value);
}
chainable = 1;
} else if (value !== undefined) {
exec = pass === undefined && jQuery.isFunction(value);
if (bulk) {
if (exec) {
exec = fn;
fn = function(elem, key, value) {
return exec.call(jQuery(elem), value);
};
} 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 : bulk ? fn.call(elems) : length ? fn(elems[0], key) : emptyGet;
},
now: function() {
return (new Date())
.getTime();
}
});
jQuery.ready.promise = function(obj) {
if (!readyList) {
readyList = jQuery.Deferred();
if (document.readyState === "complete") {
setTimeout(jQuery.ready, 1);
} else if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", DOMContentLoaded, false);
window.addEventListener("load", jQuery.ready, false);
} else {
document.attachEvent("onreadystatechange", DOMContentLoaded);
window.attachEvent("onload", jQuery.ready);
var top = false;
try {
top = window.frameElement == null && document.documentElement;
} catch (e) {}
if (top && top.doScroll) {
(function doScrollCheck() {
if (!jQuery.isReady) {
try {
top.doScroll("left");
} catch (e) {
return setTimeout(doScrollCheck, 50);
}
jQuery.ready();
}
})();
}
}
}
return readyList.promise(obj);
};
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type["[object " + name + "]"] = name.toLowerCase();
});
rootjQuery = jQuery(document);
var optionsCache = {};
function createOptions(options) {
var object = optionsCache[options] = {};
jQuery.each(options.split(core_rspace), function(_, flag) {
object[flag] = true;
});
return object;
}
jQuery.Callbacks = function(options) {
options = typeof options === "string" ? (optionsCache[options] || createOptions(options)) : jQuery.extend({}, options);
var
memory, fired, firing, firingStart, firingLength, firingIndex, list = [],
stack = !options.once && [],
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;
break;
}
}
firing = false;
if (list) {
if (stack) {
if (stack.length) {
fire(stack.shift());
}
} else if (memory) {
list = [];
} else {
self.disable();
}
}
}, self = {
add: function() {
if (list) {
var start = list.length;
(function add(args) {
jQuery.each(args, function(_, arg) {
var type = jQuery.type(arg);
if (type === "function" && (!options.unique || !self.has(arg))) {
list.push(arg);
} else if (arg && arg.length && type !== "string") {
add(arg);
}
});
})(arguments);
if (firing) {
firingLength = list.length;
} else if (memory) {
firingStart = start;
fire(memory);
}
}
return this;
},
remove: function() {
if (list) {
jQuery.each(arguments, function(_, arg) {
var index;
while ((index = jQuery.inArray(arg, list, index)) > -1) {
list.splice(index, 1);
if (firing) {
if (index <= firingLength) {
firingLength--;
}
if (index <= firingIndex) {
firingIndex--;
}
}
}
});
}
return this;
},
has: function(fn) {
return jQuery.inArray(fn, list) > -1;
},
empty: function() {
list = [];
return this;
},
disable: function() {
list = stack = memory = undefined;
return this;
},
disabled: function() {
return !list;
},
lock: function() {
stack = undefined;
if (!memory) {
self.disable();
}
return this;
},
locked: function() {
return !stack;
},
fireWith: function(context, args) {
args = args || [];
args = [context, args.slice ? args.slice() : args];
if (list && (!fired || stack)) {
if (firing) {
stack.push(args);
} else {
fire(args);
}
}
return this;
},
fire: function() {
self.fireWith(this, arguments);
return this;
},
fired: function() {
return !!fired;
}
};
return self;
};
jQuery.extend({
Deferred: function(func) {
var tuples = [
["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() {
var fns = arguments;
return jQuery.Deferred(function(newDefer) {
jQuery.each(tuples, function(i, tuple) {
var action = tuple[0],
fn = fns[i];
deferred[tuple[1]](jQuery.isFunction(fn) ? function() {
var returned = fn.apply(this, arguments);
if (returned && jQuery.isFunction(returned.promise)) {
returned.promise()
.done(newDefer.resolve)
.fail(newDefer.reject)
.progress(newDefer.notify);
} else {
newDefer[action + "With"](this === deferred ? newDefer : this, [returned]);
}
} : newDefer[action]);
});
fns = null;
})
.promise();
},
promise: function(obj) {
return obj != null ? jQuery.extend(obj, promise) : promise;
}
}, deferred = {};
promise.pipe = promise.then;
jQuery.each(tuples, function(i, tuple) {
var list = tuple[2],
stateString = tuple[3];
promise[tuple[1]] = list.add;
if (stateString) {
list.add(function() {
state = stateString;
}, tuples[i ^ 1][2].disable, tuples[2][2].lock);
}
deferred[tuple[0]] = list.fire;
deferred[tuple[0] + "With"] = list.fireWith;
});
promise.promise(deferred);
if (func) {
func.call(deferred, deferred);
}
return deferred;
},
when: function(subordinate) {
var i = 0,
resolveValues = core_slice.call(arguments),
length = resolveValues.length,
remaining = length !== 1 || (subordinate && jQuery.isFunction(subordinate.promise)) ? length : 0,
deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
updateFunc = function(i, contexts, values) {
return function(value) {
contexts[i] = this;
values[i] = arguments.length > 1 ? core_slice.call(arguments) : value;
if (values === progressValues) {
deferred.notifyWith(contexts, values);
} else if (!(--remaining)) {
deferred.resolveWith(contexts, values);
}
};
}, progressValues, progressContexts, resolveContexts;
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 (!remaining) {
deferred.resolveWith(resolveContexts, resolveValues);
}
return deferred.promise();
}
});
jQuery.support = (function() {
var support, all, a, select, opt, input, fragment, eventName, i, isSupported, clickFn, div = document.createElement("div");
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName("*");
a = div.getElementsByTagName("a")[0];
a.style.cssText = "top:1px;float:left;opacity:.5";
if (!all || !all.length) {
return {};
}
select = document.createElement("select");
opt = select.appendChild(document.createElement("option"));
input = div.getElementsByTagName("input")[0];
support = {
leadingWhitespace: (div.firstChild.nodeType === 3),
tbody: !div.getElementsByTagName("tbody")
.length,
htmlSerialize: !! div.getElementsByTagName("link")
.length,
style: /top/.test(a.getAttribute("style")),
hrefNormalized: (a.getAttribute("href") === "/a"),
opacity: /^0.5/.test(a.style.opacity),
cssFloat: !! a.style.cssFloat,
checkOn: (input.value === "on"),
optSelected: opt.selected,
getSetAttribute: div.className !== "t",
enctype: !! document.createElement("form")
.enctype,
html5Clone: document.createElement("nav")
.cloneNode(true)
.outerHTML !== "<:nav></:nav>",
boxModel: (document.compatMode === "CSS1Compat"),
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
boxSizingReliable: true,
pixelPosition: false
};
input.checked = true;
support.noCloneChecked = input.cloneNode(true)
.checked;
select.disabled = true;
support.optDisabled = !opt.disabled;
try {
delete div.test;
} catch (e) {
support.deleteExpando = false;
}
if (!div.addEventListener && div.attachEvent && div.fireEvent) {
div.attachEvent("onclick", clickFn = function() {
support.noCloneEvent = false;
});
div.cloneNode(true)
.fireEvent("onclick");
div.detachEvent("onclick", clickFn);
}
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked");
input.setAttribute("name", "t");
div.appendChild(input);
fragment = document.createDocumentFragment();
fragment.appendChild(div.lastChild);
support.checkClone = fragment.cloneNode(true)
.cloneNode(true)
.lastChild.checked;
support.appendChecked = input.checked;
fragment.removeChild(input);
fragment.appendChild(div);
if (div.attachEvent) {
for (i in {
submit: true,
change: true,
focusin: true
}) {
eventName = "on" + i;
isSupported = (eventName in div);
if (!isSupported) {
div.setAttribute(eventName, "return;");
isSupported = (typeof div[eventName] === "function");
}
support[i + "Bubbles"] = isSupported;
}
}
jQuery(function() {
var container, div, tds, marginDiv, divReset = "padding:0;margin:0;border:0;display:block;overflow:hidden;",
body = document.getElementsByTagName("body")[0];
if (!body) {
return;
}
container = document.createElement("div");
container.style.cssText = "visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";
body.insertBefore(container, body.firstChild);
div = document.createElement("div");
container.appendChild(div);
div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
tds = div.getElementsByTagName("td");
tds[0].style.cssText = "padding:0;margin:0;border:0;display:none";
isSupported = (tds[0].offsetHeight === 0);
tds[0].style.display = "";
tds[1].style.display = "none";
support.reliableHiddenOffsets = isSupported && (tds[0].offsetHeight === 0);
div.innerHTML = "";
div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;";
support.boxSizing = (div.offsetWidth === 4);
support.doesNotIncludeMarginInBodyOffset = (body.offsetTop !== 1);
if (window.getComputedStyle) {
support.pixelPosition = (window.getComputedStyle(div, null) || {})
.top !== "1%";
support.boxSizingReliable = (window.getComputedStyle(div, null) || {
width: "4px"
})
.width === "4px";
marginDiv = document.createElement("div");
marginDiv.style.cssText = div.style.cssText = divReset;
marginDiv.style.marginRight = marginDiv.style.width = "0";
div.style.width = "1px";
div.appendChild(marginDiv);
support.reliableMarginRight = !parseFloat((window.getComputedStyle(marginDiv, null) || {})
.marginRight);
}
if (typeof div.style.zoom !== "undefined") {
div.innerHTML = "";
div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1";
support.inlineBlockNeedsLayout = (div.offsetWidth === 3);
div.style.display = "block";
div.style.overflow = "visible";
div.innerHTML = "<div></div>";
div.firstChild.style.width = "5px";
support.shrinkWrapBlocks = (div.offsetWidth !== 3);
container.style.zoom = 1;
}
body.removeChild(container);
container = div = tds = marginDiv = null;
});
fragment.removeChild(div);
all = a = select = opt = input = fragment = div = null;
return support;
})();
var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
deletedIds: [],
uuid: 0,
expando: "jQuery" + (jQuery.fn.jquery + Math.random())
.replace(/\D/g, ""),
noData: {
"embed": true,
"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) {
if (!jQuery.acceptData(elem)) {
return;
}
var thisCache, ret, internalKey = jQuery.expando,
getByName = typeof name === "string",
isNode = elem.nodeType,
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[internalKey] : elem[internalKey] && internalKey;
if ((!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined) {
return;
}
if (!id) {
if (isNode) {
elem[internalKey] = id = jQuery.deletedIds.pop() || jQuery.guid++;
} else {
id = internalKey;
}
}
if (!cache[id]) {
cache[id] = {};
if (!isNode) {
cache[id].toJSON = jQuery.noop;
}
}
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);
}
}
thisCache = cache[id];
if (!pvt) {
if (!thisCache.data) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if (data !== undefined) {
thisCache[jQuery.camelCase(name)] = data;
}
if (getByName) {
ret = thisCache[name];
if (ret == null) {
ret = thisCache[jQuery.camelCase(name)];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function(elem, name, pvt) {
if (!jQuery.acceptData(elem)) {
return;
}
var thisCache, i, l, isNode = elem.nodeType,
cache = isNode ? jQuery.cache : elem,
id = isNode ? elem[jQuery.expando] : jQuery.expando;
if (!cache[id]) {
return;
}
if (name) {
thisCache = pvt ? cache[id] : cache[id].data;
if (thisCache) {
if (!jQuery.isArray(name)) {
if (name in thisCache) {
name = [name];
} else {
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 (!(pvt ? isEmptyDataObject : jQuery.isEmptyObject)(thisCache)) {
return;
}
}
}
if (!pvt) {
delete cache[id].data;
if (!isEmptyDataObject(cache[id])) {
return;
}
}
if (isNode) {
jQuery.cleanData([elem], true);
} else if (jQuery.support.deleteExpando || cache != cache.window) {
delete cache[id];
} else {
cache[id] = null;
}
},
_data: function(elem, name, data) {
return jQuery.data(elem, name, data, true);
},
acceptData: function(elem) {
var noData = elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()];
return !noData || noData !== true && elem.getAttribute("classid") === noData;
}
});
jQuery.fn.extend({
data: function(key, value) {
var parts, part, attr, name, l, elem = this[0],
i = 0,
data = null;
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-")) {
name = jQuery.camelCase(name.substring(5));
dataAttr(elem, name, data[name]);
}
}
jQuery._data(elem, "parsedAttrs", true);
}
}
return data;
}
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]]);
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 (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 : +data + "" === data ? +data : rbrace.test(data) ? jQuery.parseJSON(data) : data;
} catch (e) {}
jQuery.data(elem, key, data);
} else {
data = undefined;
}
}
return data;
}
function isEmptyDataObject(obj) {
var name;
for (name in obj) {
if (name === "data" && jQuery.isEmptyObject(obj[name])) {
continue;
}
if (name !== "toJSON") {
return false;
}
}
return true;
}
jQuery.extend({
queue: function(elem, type, data) {
var queue;
if (elem) {
type = (type || "fx") + "queue";
queue = jQuery._data(elem, type);
if (data) {
if (!queue || jQuery.isArray(data)) {
queue = jQuery._data(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 (fn === "inprogress") {
fn = queue.shift();
startLength--;
}
if (fn) {
if (type === "fx") {
queue.unshift("inprogress");
}
delete hooks.stop;
fn.call(elem, next, hooks);
}
if (!startLength && hooks) {
hooks.empty.fire();
}
},
_queueHooks: function(elem, type) {
var key = type + "queueHooks";
return jQuery._data(elem, key) || jQuery._data(elem, key, {
empty: jQuery.Callbacks("once memory")
.add(function() {
jQuery.removeData(elem, type + "queue", true);
jQuery.removeData(elem, key, true);
})
});
}
});
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);
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);
});
},
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", []);
},
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 = jQuery._data(elements[i], type + "queueHooks");
if (tmp && tmp.empty) {
count++;
tmp.empty.add(resolve);
}
}
resolve();
return defer.promise(obj);
}
});
var nodeHook, boolHook, fixSpecified, rclass = /[\t\r\n]/g,
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;
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 {
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(core_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] + " ") < 0) {
setClass += classNames[c] + " ";
}
}
elem.className = jQuery.trim(setClass);
}
}
}
}
return this;
},
removeClass: function(value) {
var removes, className, elem, c, cl, i, l;
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) {
removes = (value || "")
.split(core_rspace);
for (i = 0, l = this.length; i < l; i++) {
elem = this[i];
if (elem.nodeType === 1 && elem.className) {
className = (" " + elem.className + " ")
.replace(rclass, " ");
for (c = 0, cl = removes.length; c < cl; c++) {
while (className.indexOf(" " + removes[c] + " ") >= 0) {
className = className.replace(" " + removes[c] + " ", " ");
}
}
elem.className = value ? jQuery.trim(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") {
var className, i = 0,
self = jQuery(this),
state = stateVal,
classNames = value.split(core_rspace);
while ((className = classNames[i++])) {
state = isBool ? state : !self.hasClass(className);
self[state ? "addClass" : "removeClass"](className);
}
} else if (type === "undefined" || type === "boolean") {
if (this.className) {
jQuery._data(this, "__className__", this.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) >= 0) {
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" ? ret.replace(rreturn, "") : ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction(value);
return this.each(function(i) {
var val, self = jQuery(this);
if (this.nodeType !== 1) {
return;
}
if (isFunction) {
val = value.call(this, i, self.val());
} else {
val = value;
}
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 (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === undefined) {
this.value = val;
}
});
}
});
jQuery.extend({
valHooks: {
option: {
get: function(elem) {
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";
if (index < 0) {
return null;
}
i = one ? index : 0;
max = one ? index + 1 : options.length;
for (; i < max; i++) {
option = options[i];
if (option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) && (!option.parentNode.disabled || !jQuery.nodeName(option.parentNode, "optgroup"))) {
value = jQuery(option)
.val();
if (one) {
return value;
}
values.push(value);
}
}
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: {},
attr: function(elem, name, value, pass) {
var ret, hooks, notxml, nType = elem.nodeType;
if (!elem || nType === 3 || nType === 8 || nType === 2) {
return;
}
if (pass && jQuery.isFunction(jQuery.fn[name])) {
return jQuery(elem)[name](value);
}
if (typeof elem.getAttribute === "undefined") {
return jQuery.prop(elem, name, value);
}
notxml = nType !== 1 || !jQuery.isXMLDoc(elem);
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);
return ret === null ? undefined : ret;
}
},
removeAttr: function(elem, value) {
var propName, attrNames, name, isBool, i = 0;
if (value && elem.nodeType === 1) {
attrNames = value.split(core_rspace);
for (; i < attrNames.length; i++) {
name = attrNames[i];
if (name) {
propName = jQuery.propFix[name] || name;
isBool = rboolean.test(name);
if (!isBool) {
jQuery.attr(elem, name, "");
}
elem.removeAttribute(getSetAttribute ? name : propName);
if (isBool && propName in elem) {
elem[propName] = false;
}
}
}
}
},
attrHooks: {
type: {
set: function(elem, value) {
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")) {
var val = elem.value;
elem.setAttribute("type", value);
if (val) {
elem.value = val;
}
return value;
}
}
},
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);
}
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;
if (!elem || nType === 3 || nType === 8 || nType === 2) {
return;
}
notxml = nType !== 1 || !jQuery.isXMLDoc(elem);
if (notxml) {
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) {
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;
}
}
}
});
boolHook = {
get: function(elem, name) {
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) {
jQuery.removeAttr(elem, name);
} else {
propName = jQuery.propFix[name] || name;
if (propName in elem) {
elem[propName] = true;
}
elem.setAttribute(name, name.toLowerCase());
}
return name;
}
};
if (!getSetAttribute) {
fixSpecified = {
name: true,
id: true,
coords: true
};
nodeHook = jQuery.valHooks.button = {
get: function(elem, name) {
var ret;
ret = elem.getAttributeNode(name);
return ret && (fixSpecified[name] ? ret.value !== "" : ret.specified) ? ret.value : undefined;
},
set: function(elem, value, name) {
var ret = elem.getAttributeNode(name);
if (!ret) {
ret = document.createAttribute(name);
elem.setAttributeNode(ret);
}
return (ret.value = value + "");
}
};
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;
}
}
});
});
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function(elem, value, name) {
if (value === "") {
value = "false";
}
nodeHook.set(elem, value, name);
}
};
}
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 elem.style.cssText.toLowerCase() || undefined;
},
set: function(elem, value) {
return (elem.style.cssText = value + "");
}
};
}
if (!jQuery.support.optSelected) {
jQuery.propHooks.selected = jQuery.extend(jQuery.propHooks.selected, {
get: function(elem) {
var parent = elem.parentNode;
if (parent) {
parent.selectedIndex;
if (parent.parentNode) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
if (!jQuery.support.enctype) {
jQuery.propFix.enctype = "encoding";
}
if (!jQuery.support.checkOn) {
jQuery.each(["radio", "checkbox"], function() {
jQuery.valHooks[this] = {
get: function(elem) {
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)$/,
hoverHack = function(events) {
return jQuery.event.special.hover ? events : events.replace(rhoverHack, "mouseenter$1 mouseleave$1");
};
jQuery.event = {
add: function(elem, types, handler, data, selector) {
var elemData, eventHandle, events, t, tns, type, namespaces, handleObj, handleObjIn, handlers, special;
if (elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data(elem))) {
return;
}
if (handler.handler) {
handleObjIn = handler;
handler = handleObjIn.handler;
selector = handleObjIn.selector;
}
if (!handler.guid) {
handler.guid = jQuery.guid++;
}
events = elemData.events;
if (!events) {
elemData.events = events = {};
}
eventHandle = elemData.handle;
if (!eventHandle) {
elemData.handle = eventHandle = function(e) {
return typeof jQuery !== "undefined" && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply(eventHandle.elem, arguments) : undefined;
};
eventHandle.elem = elem;
}
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();
special = jQuery.event.special[type] || {};
type = (selector ? special.delegateType : special.bindType) || type;
special = jQuery.event.special[type] || {};
handleObj = jQuery.extend({
type: type,
origType: tns[1],
data: data,
handler: handler,
guid: handler.guid,
selector: selector,
needsContext: selector && jQuery.expr.match.needsContext.test(selector),
namespace: namespaces.join(".")
}, handleObjIn);
handlers = events[type];
if (!handlers) {
handlers = events[type] = [];
handlers.delegateCount = 0;
if (!special.setup || special.setup.call(elem, data, namespaces, eventHandle) === false) {
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;
}
}
if (selector) {
handlers.splice(handlers.delegateCount++, 0, handleObj);
} else {
handlers.push(handleObj);
}
jQuery.event.global[type] = true;
}
elem = null;
},
global: {},
remove: function(elem, types, handler, selector, mappedTypes) {
var t, tns, type, origType, namespaces, origCount, j, events, special, eventType, handleObj, elemData = jQuery.hasData(elem) && jQuery._data(elem);
if (!elemData || !(events = elemData.events)) {
return;
}
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];
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;
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);
}
}
}
if (eventType.length === 0 && origCount !== eventType.length) {
if (!special.teardown || special.teardown.call(elem, namespaces, elemData.handle) === false) {
jQuery.removeEvent(elem, type, elemData.handle);
}
delete events[type];
}
}
if (jQuery.isEmptyObject(events)) {
delete elemData.handle;
jQuery.removeData(elem, "events", true);
}
},
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function(event, data, elem, onlyHandlers) {
if (elem && (elem.nodeType === 3 || elem.nodeType === 8)) {
return;
}
var cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType, type = event.type || event,
namespaces = [];
if (rfocusMorph.test(type + jQuery.event.triggered)) {
return;
}
if (type.indexOf("!") >= 0) {
type = type.slice(0, - 1);
exclusive = true;
}
if (type.indexOf(".") >= 0) {
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ((!elem || jQuery.event.customEvent[type]) && !jQuery.event.global[type]) {
return;
}
event = typeof event === "object" ? event[jQuery.expando] ? event : new jQuery.Event(type, event) : 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 : "";
if (!elem) {
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;
}
event.result = undefined;
if (!event.target) {
event.target = elem;
}
data = data != null ? jQuery.makeArray(data) : [];
data.unshift(event);
special = jQuery.event.special[type] || {};
if (special.trigger && special.trigger.apply(elem, data) === false) {
return;
}
eventPath = [
[elem, special.bindType || type]
];
if (!onlyHandlers && !special.noBubble && !jQuery.isWindow(elem)) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test(bubbleType + type) ? elem : elem.parentNode;
for (old = elem; cur; cur = cur.parentNode) {
eventPath.push([cur, bubbleType]);
old = cur;
}
if (old === (elem.ownerDocument || document)) {
eventPath.push([old.defaultView || old.parentWindow || window, bubbleType]);
}
}
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);
}
handle = ontype && cur[ontype];
if (handle && jQuery.acceptData(cur) && handle.apply && handle.apply(cur, data) === false) {
event.preventDefault();
}
}
event.type = type;
if (!onlyHandlers && !event.isDefaultPrevented()) {
if ((!special._default || special._default.apply(elem.ownerDocument, data) === false) && !(type === "click" && jQuery.nodeName(elem, "a")) && jQuery.acceptData(elem)) {
if (ontype && elem[type] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow(elem)) {
old = elem[ontype];
if (old) {
elem[ontype] = null;
}
jQuery.event.triggered = type;
elem[type]();
jQuery.event.triggered = undefined;
if (old) {
elem[ontype] = old;
}
}
}
}
return event.result;
},
dispatch: function(event) {
event = jQuery.event.fix(event || window.event);
var i, j, cur, ret, selMatch, matched, matches, handleObj, sel, related, handlers = ((jQuery._data(this, "events") || {})[event.type] || []),
delegateCount = handlers.delegateCount,
args = core_slice.call(arguments),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[event.type] || {}, handlerQueue = [];
args[0] = event;
event.delegateTarget = this;
if (special.preDispatch && special.preDispatch.call(this, event) === false) {
return;
}
if (delegateCount && !(event.button && event.type === "click")) {
for (cur = event.target; cur != this; cur = cur.parentNode || this) {
if (cur.disabled !== true || event.type !== "click") {
selMatch = {};
matches = [];
for (i = 0; i < delegateCount; i++) {
handleObj = handlers[i];
sel = handleObj.selector;
if (selMatch[sel] === undefined) {
selMatch[sel] = handleObj.needsContext ? jQuery(sel, this)
.index(cur) >= 0 : jQuery.find(sel, this, null, [cur])
.length;
}
if (selMatch[sel]) {
matches.push(handleObj);
}
}
if (matches.length) {
handlerQueue.push({
elem: cur,
matches: matches
});
}
}
}
}
if (handlers.length > delegateCount) {
handlerQueue.push({
elem: this,
matches: handlers.slice(delegateCount)
});
}
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];
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();
}
}
}
}
}
if (special.postDispatch) {
special.postDispatch.call(this, event);
}
return event.result;
},
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) {
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;
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);
}
if (!event.relatedTarget && fromElement) {
event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
}
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;
}
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];
}
if (!event.target) {
event.target = originalEvent.srcElement || document;
}
if (event.target.nodeType === 3) {
event.target = event.target.parentNode;
}
event.metaKey = !! event.metaKey;
return fixHook.filter ? fixHook.filter(event, originalEvent) : event;
},
special: {
load: {
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function(data, namespaces, eventHandle) {
if (jQuery.isWindow(this)) {
this.onbeforeunload = eventHandle;
}
},
teardown: function(namespaces, eventHandle) {
if (this.onbeforeunload === eventHandle) {
this.onbeforeunload = null;
}
}
}
},
simulate: function(type, elem, event, bubble) {
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.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) {
var name = "on" + type;
if (elem.detachEvent) {
if (typeof elem[name] === "undefined") {
elem[name] = null;
}
elem.detachEvent(name, handle);
}
};
jQuery.Event = function(src, props) {
if (!(this instanceof jQuery.Event)) {
return new jQuery.Event(src, props);
}
if (src && src.type) {
this.originalEvent = src;
this.type = src.type;
this.isDefaultPrevented = (src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault()) ? returnTrue : returnFalse;
} else {
this.type = src;
}
if (props) {
jQuery.extend(this, props);
}
this.timeStamp = src && src.timeStamp || jQuery.now();
this[jQuery.expando] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if (!e) {
return;
}
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if (!e) {
return;
}
if (e.stopPropagation) {
e.stopPropagation();
}
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function(orig, fix) {
jQuery.event.special[orig] = {
delegateType: fix,
bindType: fix,
handle: function(event) {
var ret, target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector;
if (!related || (related !== target && !jQuery.contains(target, related))) {
event.type = handleObj.origType;
ret = handleObj.handler.apply(this, arguments);
event.type = fix;
}
return ret;
}
};
});
if (!jQuery.support.submitBubbles) {
jQuery.event.special.submit = {
setup: function() {
if (jQuery.nodeName(this, "form")) {
return false;
}
jQuery.event.add(this, "click._submit keypress._submit", function(e) {
var elem = e.target,
form = jQuery.nodeName(elem, "input") || jQuery.nodeName(elem, "button") ? elem.form : undefined;
if (form && !jQuery._data(form, "_submit_attached")) {
jQuery.event.add(form, "submit._submit", function(event) {
event._submit_bubble = true;
});
jQuery._data(form, "_submit_attached", true);
}
});
},
postDispatch: function(event) {
if (event._submit_bubble) {
delete event._submit_bubble;
if (this.parentNode && !event.isTrigger) {
jQuery.event.simulate("submit", this.parentNode, event, true);
}
}
},
teardown: function() {
if (jQuery.nodeName(this, "form")) {
return false;
}
jQuery.event.remove(this, "._submit");
}
};
}
if (!jQuery.support.changeBubbles) {
jQuery.event.special.change = {
setup: function() {
if (rformElems.test(this.nodeName)) {
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;
}
jQuery.event.add(this, "beforeactivate._change", function(e) {
var elem = e.target;
if (rformElems.test(elem.nodeName) && !jQuery._data(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);
}
});
jQuery._data(elem, "_change_attached", true);
}
});
},
handle: function(event) {
var elem = event.target;
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);
}
};
}
if (!jQuery.support.focusinBubbles) {
jQuery.each({
focus: "focusin",
blur: "focusout"
}, function(orig, fix) {
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, one) {
var origFn, type;
if (typeof types === "object") {
if (typeof selector !== "string") {
data = data || selector;
selector = undefined;
}
for (type in types) {
this.on(type, selector, data, types[type], one);
}
return this;
}
if (data == null && fn == null) {
fn = selector;
data = selector = undefined;
} else if (fn == null) {
if (typeof selector === "string") {
fn = data;
data = undefined;
} else {
fn = data;
data = selector;
selector = undefined;
}
}
if (fn === false) {
fn = returnFalse;
} else if (!fn) {
return this;
}
if (one === 1) {
origFn = fn;
fn = function(event) {
jQuery()
.off(event);
return origFn.apply(this, arguments);
};
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) {
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") {
for (type in types) {
this.off(type, selector, types[type]);
}
return this;
}
if (selector === false || typeof selector === "function") {
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) {
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) {
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function(event) {
var lastToggle = (jQuery._data(this, "lastToggle" + fn.guid) || 0) % i;
jQuery._data(this, "lastToggle" + fn.guid, lastToggle + 1);
event.preventDefault();
return args[lastToggle].apply(this, arguments) || false;
};
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) {
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 (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 2012 jQuery Foundation and other contributors
Released under the MIT license
http://sizzlejs.com/
*/
(function(window, undefined) {
var cachedruns, assertGetIdNotName, Expr, getText, isXML, contains, compile, sortOrder, hasDuplicate, outermostContext, baseHasDuplicate = true,
strundefined = "undefined",
expando = ("sizcache" + Math.random())
.replace(".", ""),
Token = String,
document = window.document,
docElem = document.documentElement,
dirruns = 0,
done = 0,
pop = [].pop,
push = [].push,
slice = [].slice,
indexOf = [].indexOf || function(elem) {
var i = 0,
len = this.length;
for (; i < len; i++) {
if (this[i] === elem) {
return i;
}
}
return -1;
}, markFunction = function(fn, value) {
fn[expando] = value == null || value;
return fn;
}, createCache = function() {
var cache = {}, keys = [];
return markFunction(function(key, value) {
if (keys.push(key) > Expr.cacheLength) {
delete cache[keys.shift()];
}
return (cache[key] = value);
}, cache);
}, classCache = createCache(),
tokenCache = createCache(),
compilerCache = createCache(),
whitespace = "[\\x20\\t\\r\\n\\f]",
characterEncoding = "(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",
identifier = characterEncoding.replace("w", "w#"),
operators = "([*^$|!~]?=)",
attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]",
pseudos = ":(" + characterEncoding + ")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:" + attributes + ")|[^:]|\\\\.)*|.*))\\)|)",
pos = ":(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)",
rtrim = new RegExp("^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g"),
rcomma = new RegExp("^" + whitespace + "*," + whitespace + "*"),
rcombinators = new RegExp("^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*"),
rpseudo = new RegExp(pseudos),
rquickExpr = /^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,
rnot = /^:not/,
rsibling = /[\x20\t\r\n\f]*[+~]/,
rendsWithNot = /:not\($/,
rheader = /h\d/i,
rinputs = /input|select|textarea|button/i,
rbackslash = /\\(?!\\)/g,
matchExpr = {
"ID": new RegExp("^#(" + characterEncoding + ")"),
"CLASS": new RegExp("^\\.(" + characterEncoding + ")"),
"NAME": new RegExp("^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]"),
"TAG": new RegExp("^(" + characterEncoding.replace("w", "w*") + ")"),
"ATTR": new RegExp("^" + attributes),
"PSEUDO": new RegExp("^" + pseudos),
"POS": new RegExp(pos, "i"),
"CHILD": new RegExp("^:(only|nth|first|last)-child(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i"),
"needsContext": new RegExp("^" + whitespace + "*[>+~]|" + pos, "i")
}, assert = function(fn) {
var div = document.createElement("div");
try {
return fn(div);
} catch (e) {
return false;
} finally {
div = null;
}
}, assertTagNameNoComments = assert(function(div) {
div.appendChild(document.createComment(""));
return !div.getElementsByTagName("*")
.length;
}),
assertHrefNotNormalized = assert(function(div) {
div.innerHTML = "<a href='#'></a>";
return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#";
}),
assertAttributes = assert(function(div) {
div.innerHTML = "<select></select>";
var type = typeof div.lastChild.getAttribute("multiple");
return type !== "boolean" && type !== "string";
}),
assertUsableClassName = assert(function(div) {
div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>";
if (!div.getElementsByClassName || !div.getElementsByClassName("e")
.length) {
return false;
}
div.lastChild.className = "e";
return div.getElementsByClassName("e")
.length === 2;
}),
assertUsableName = assert(function(div) {
div.id = expando + 0;
div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>";
docElem.insertBefore(div, docElem.firstChild);
var pass = document.getElementsByName && document.getElementsByName(expando)
.length === 2 + document.getElementsByName(expando + 0)
.length;
assertGetIdNotName = !document.getElementById(expando);
docElem.removeChild(div);
return pass;
});
try {
slice.call(docElem.childNodes, 0)[0].nodeType;
} catch (e) {
slice = function(i) {
var elem, results = [];
for (;
(elem = this[i]); i++) {
results.push(elem);
}
return results;
};
}
function Sizzle(selector, context, results, seed) {
results = results || [];
context = context || document;
var match, elem, xml, m, nodeType = context.nodeType;
if (!selector || typeof selector !== "string") {
return results;
}
if (nodeType !== 1 && nodeType !== 9) {
return [];
}
xml = isXML(context);
if (!xml && !seed) {
if ((match = rquickExpr.exec(selector))) {
if ((m = match[1])) {
if (nodeType === 9) {
elem = context.getElementById(m);
if (elem && elem.parentNode) {
if (elem.id === m) {
results.push(elem);
return results;
}
} else {
return results;
}
} else {
if (context.ownerDocument && (elem = context.ownerDocument.getElementById(m)) && contains(context, elem) && elem.id === m) {
results.push(elem);
return results;
}
}
} else if (match[2]) {
push.apply(results, slice.call(context.getElementsByTagName(selector), 0));
return results;
} else if ((m = match[3]) && assertUsableClassName && context.getElementsByClassName) {
push.apply(results, slice.call(context.getElementsByClassName(m), 0));
return results;
}
}
}
return select(selector.replace(rtrim, "$1"), context, results, seed, xml);
}
Sizzle.matches = function(expr, elements) {
return Sizzle(expr, null, null, elements);
};
Sizzle.matchesSelector = function(elem, expr) {
return Sizzle(expr, null, null, [elem])
.length > 0;
};
function createInputPseudo(type) {
return function(elem) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === type;
};
}
function createButtonPseudo(type) {
return function(elem) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && elem.type === type;
};
}
function createPositionalPseudo(fn) {
return markFunction(function(argument) {
argument = +argument;
return markFunction(function(seed, matches) {
var j, matchIndexes = fn([], seed.length, argument),
i = matchIndexes.length;
while (i--) {
if (seed[(j = matchIndexes[i])]) {
seed[j] = !(matches[j] = seed[j]);
}
}
});
});
}
getText = Sizzle.getText = function(elem) {
var node, ret = "",
i = 0,
nodeType = elem.nodeType;
if (nodeType) {
if (nodeType === 1 || nodeType === 9 || nodeType === 11) {
if (typeof elem.textContent === "string") {
return elem.textContent;
} else {
for (elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText(elem);
}
}
} else if (nodeType === 3 || nodeType === 4) {
return elem.nodeValue;
}
} else {
for (;
(node = elem[i]); i++) {
ret += getText(node);
}
}
return ret;
};
isXML = Sizzle.isXML = function(elem) {
var documentElement = elem && (elem.ownerDocument || elem)
.documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
contains = Sizzle.contains = 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));
} : docElem.compareDocumentPosition ? function(a, b) {
return b && !! (a.compareDocumentPosition(b) & 16);
} : function(a, b) {
while ((b = b.parentNode)) {
if (b === a) {
return true;
}
}
return false;
};
Sizzle.attr = function(elem, name) {
var val, xml = isXML(elem);
if (!xml) {
name = name.toLowerCase();
}
if ((val = Expr.attrHandle[name])) {
return val(elem);
}
if (xml || assertAttributes) {
return elem.getAttribute(name);
}
val = elem.getAttributeNode(name);
return val ? typeof elem[name] === "boolean" ? elem[name] ? name : null : val.specified ? val.value : null : null;
};
Expr = Sizzle.selectors = {
cacheLength: 50,
createPseudo: markFunction,
match: matchExpr,
attrHandle: assertHrefNotNormalized ? {} : {
"href": function(elem) {
return elem.getAttribute("href", 2);
},
"type": function(elem) {
return elem.getAttribute("type");
}
},
find: {
"ID": assertGetIdNotName ? function(id, context, xml) {
if (typeof context.getElementById !== strundefined && !xml) {
var m = context.getElementById(id);
return m && m.parentNode ? [m] : [];
}
} : function(id, context, xml) {
if (typeof context.getElementById !== strundefined && !xml) {
var m = context.getElementById(id);
return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id")
.value === id ? [m] : undefined : [];
}
},
"TAG": assertTagNameNoComments ? function(tag, context) {
if (typeof context.getElementsByTagName !== strundefined) {
return context.getElementsByTagName(tag);
}
} : function(tag, context) {
var results = context.getElementsByTagName(tag);
if (tag === "*") {
var elem, tmp = [],
i = 0;
for (;
(elem = results[i]); i++) {
if (elem.nodeType === 1) {
tmp.push(elem);
}
}
return tmp;
}
return results;
},
"NAME": assertUsableName && function(tag, context) {
if (typeof context.getElementsByName !== strundefined) {
return context.getElementsByName(name);
}
},
"CLASS": assertUsableClassName && function(className, context, xml) {
if (typeof context.getElementsByClassName !== strundefined && !xml) {
return context.getElementsByClassName(className);
}
}
},
relative: {
">": {
dir: "parentNode",
first: true
},
" ": {
dir: "parentNode"
},
"+": {
dir: "previousSibling",
first: true
},
"~": {
dir: "previousSibling"
}
},
preFilter: {
"ATTR": function(match) {
match[1] = match[1].replace(rbackslash, "");
match[3] = (match[4] || match[5] || "")
.replace(rbackslash, "");
if (match[2] === "~=") {
match[3] = " " + match[3] + " ";
}
return match.slice(0, 4);
},
"CHILD": function(match) {
match[1] = match[1].toLowerCase();
if (match[1] === "nth") {
if (!match[2]) {
Sizzle.error(match[0]);
}
match[3] = +(match[3] ? match[4] + (match[5] || 1) : 2 * (match[2] === "even" || match[2] === "odd"));
match[4] = +((match[6] + match[7]) || match[2] === "odd");
} else if (match[2]) {
Sizzle.error(match[0]);
}
return match;
},
"PSEUDO": function(match) {
var unquoted, excess;
if (matchExpr["CHILD"].test(match[0])) {
return null;
}
if (match[3]) {
match[2] = match[3];
} else if ((unquoted = match[4])) {
if (rpseudo.test(unquoted) && (excess = tokenize(unquoted, true)) && (excess = unquoted.indexOf(")", unquoted.length - excess) - unquoted.length)) {
unquoted = unquoted.slice(0, excess);
match[0] = match[0].slice(0, excess);
}
match[2] = unquoted;
}
return match.slice(0, 3);
}
},
filter: {
"ID": assertGetIdNotName ? function(id) {
id = id.replace(rbackslash, "");
return function(elem) {
return elem.getAttribute("id") === id;
};
} : function(id) {
id = id.replace(rbackslash, "");
return function(elem) {
var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
return node && node.value === id;
};
},
"TAG": function(nodeName) {
if (nodeName === "*") {
return function() {
return true;
};
}
nodeName = nodeName.replace(rbackslash, "")
.toLowerCase();
return function(elem) {
return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
};
},
"CLASS": function(className) {
var pattern = classCache[expando][className];
if (!pattern) {
pattern = classCache(className, new RegExp("(^|" + whitespace + ")" + className + "(" + whitespace + "|$)"));
}
return function(elem) {
return pattern.test(elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "");
};
},
"ATTR": function(name, operator, check) {
return function(elem, context) {
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.substr(result.length - check.length) === check : operator === "~=" ? (" " + result + " ")
.indexOf(check) > -1 : operator === "|=" ? result === check || result.substr(0, check.length + 1) === check + "-" : false;
};
},
"CHILD": function(type, argument, first, last) {
if (type === "nth") {
return function(elem) {
var node, diff, parent = elem.parentNode;
if (first === 1 && last === 0) {
return true;
}
if (parent) {
diff = 0;
for (node = parent.firstChild; node; node = node.nextSibling) {
if (node.nodeType === 1) {
diff++;
if (elem === node) {
break;
}
}
}
}
diff -= last;
return diff === first || (diff % first === 0 && diff / first >= 0);
};
}
return function(elem) {
var 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;
case "last":
while ((node = node.nextSibling)) {
if (node.nodeType === 1) {
return false;
}
}
return true;
}
};
},
"PSEUDO": function(pseudo, argument) {
var args, fn = Expr.pseudos[pseudo] || Expr.setFilters[pseudo.toLowerCase()] || Sizzle.error("unsupported pseudo: " + pseudo);
if (fn[expando]) {
return fn(argument);
}
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: {
"not": markFunction(function(selector) {
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;
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;
};
}),
"enabled": function(elem) {
return elem.disabled === false;
},
"disabled": function(elem) {
return elem.disabled === true;
},
"checked": function(elem) {
var nodeName = elem.nodeName.toLowerCase();
return (nodeName === "input" && !! elem.checked) || (nodeName === "option" && !! elem.selected);
},
"selected": function(elem) {
if (elem.parentNode) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
"parent": function(elem) {
return !Expr.pseudos["empty"](elem);
},
"empty": function(elem) {
var nodeType;
elem = elem.firstChild;
while (elem) {
if (elem.nodeName > "@" || (nodeType = elem.nodeType) === 3 || nodeType === 4) {
return false;
}
elem = elem.nextSibling;
}
return true;
},
"header": function(elem) {
return rheader.test(elem.nodeName);
},
"text": function(elem) {
var type, attr;
return elem.nodeName.toLowerCase() === "input" && (type = elem.type) === "text" && ((attr = elem.getAttribute("type")) == null || attr.toLowerCase() === type);
},
"radio": createInputPseudo("radio"),
"checkbox": createInputPseudo("checkbox"),
"file": createInputPseudo("file"),
"password": createInputPseudo("password"),
"image": createInputPseudo("image"),
"submit": createButtonPseudo("submit"),
"reset": createButtonPseudo("reset"),
"button": function(elem) {
var name = elem.nodeName.toLowerCase();
return name === "input" && elem.type === "button" || name === "button";
},
"input": function(elem) {
return rinputs.test(elem.nodeName);
},
"focus": function(elem) {
var doc = elem.ownerDocument;
return elem === doc.activeElement && (!doc.hasFocus || doc.hasFocus()) && !! (elem.type || elem.href);
},
"active": function(elem) {
return elem === elem.ownerDocument.activeElement;
},
"first": createPositionalPseudo(function(matchIndexes, length, argument) {
return [0];
}),
"last": createPositionalPseudo(function(matchIndexes, length, argument) {
return [length - 1];
}),
"eq": createPositionalPseudo(function(matchIndexes, length, argument) {
return [argument < 0 ? argument + length : argument];
}),
"even": createPositionalPseudo(function(matchIndexes, length, argument) {
for (var i = 0; i < length; i += 2) {
matchIndexes.push(i);
}
return matchIndexes;
}),
"odd": createPositionalPseudo(function(matchIndexes, length, argument) {
for (var i = 1; i < length; i += 2) {
matchIndexes.push(i);
}
return matchIndexes;
}),
"lt": createPositionalPseudo(function(matchIndexes, length, argument) {
for (var i = argument < 0 ? argument + length : argument; --i >= 0;) {
matchIndexes.push(i);
}
return matchIndexes;
}),
"gt": createPositionalPseudo(function(matchIndexes, length, argument) {
for (var i = argument < 0 ? argument + length : argument; ++i < length;) {
matchIndexes.push(i);
}
return matchIndexes;
})
}
};
function siblingCheck(a, b, ret) {
if (a === b) {
return ret;
}
var cur = a.nextSibling;
while (cur) {
if (cur === b) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
}
sortOrder = docElem.compareDocumentPosition ? function(a, b) {
if (a === b) {
hasDuplicate = true;
return 0;
}
return (!a.compareDocumentPosition || !b.compareDocumentPosition ? a.compareDocumentPosition : a.compareDocumentPosition(b) & 4) ? -1 : 1;
} : function(a, b) {
if (a === b) {
hasDuplicate = true;
return 0;
} 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 (aup === bup) {
return siblingCheck(a, b);
} else if (!aup) {
return -1;
} else if (!bup) {
return 1;
}
while (cur) {
ap.unshift(cur);
cur = cur.parentNode;
}
cur = bup;
while (cur) {
bp.unshift(cur);
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
for (var i = 0; i < al && i < bl; i++) {
if (ap[i] !== bp[i]) {
return siblingCheck(ap[i], bp[i]);
}
}
return i === al ? siblingCheck(a, bp[i], - 1) : siblingCheck(ap[i], b, 1);
};
[0, 0].sort(sortOrder);
baseHasDuplicate = !hasDuplicate;
Sizzle.uniqueSort = function(results) {
var elem, i = 1;
hasDuplicate = baseHasDuplicate;
results.sort(sortOrder);
if (hasDuplicate) {
for (;
(elem = results[i]); i++) {
if (elem === results[i - 1]) {
results.splice(i--, 1);
}
}
}
return results;
};
Sizzle.error = function(msg) {
throw new Error("Syntax error, unrecognized expression: " + msg);
};
function tokenize(selector, parseOnly) {
var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[expando][selector];
if (cached) {
return parseOnly ? 0 : cached.slice(0);
}
soFar = selector;
groups = [];
preFilters = Expr.preFilter;
while (soFar) {
if (!matched || (match = rcomma.exec(soFar))) {
if (match) {
soFar = soFar.slice(match[0].length);
}
groups.push(tokens = []);
}
matched = false;
if ((match = rcombinators.exec(soFar))) {
tokens.push(matched = new Token(match.shift()));
soFar = soFar.slice(matched.length);
matched.type = match[0].replace(rtrim, " ");
}
for (type in Expr.filter) {
if ((match = matchExpr[type].exec(soFar)) && (!preFilters[type] || (match = preFilters[type](match, document, true)))) {
tokens.push(matched = new Token(match.shift()));
soFar = soFar.slice(matched.length);
matched.type = type;
matched.matches = match;
}
}
if (!matched) {
break;
}
}
return parseOnly ? soFar.length : soFar ? Sizzle.error(selector) : tokenCache(selector, groups)
.slice(0);
}
function addCombinator(matcher, combinator, base) {
var dir = combinator.dir,
checkNonElements = base && combinator.dir === "parentNode",
doneName = done++;
return combinator.first ? function(elem, context, xml) {
while ((elem = elem[dir])) {
if (checkNonElements || elem.nodeType === 1) {
return matcher(elem, context, xml);
}
}
} : function(elem, context, xml) {
if (!xml) {
var cache, dirkey = dirruns + " " + doneName + " ",
cachedkey = dirkey + cachedruns;
while ((elem = elem[dir])) {
if (checkNonElements || elem.nodeType === 1) {
if ((cache = elem[expando]) === cachedkey) {
return elem.sizset;
} else if (typeof cache === "string" && cache.indexOf(dirkey) === 0) {
if (elem.sizset) {
return elem;
}
} else {
elem[expando] = cachedkey;
if (matcher(elem, context, xml)) {
elem.sizset = true;
return elem;
}
elem.sizset = false;
}
}
}
} else {
while ((elem = elem[dir])) {
if (checkNonElements || elem.nodeType === 1) {
if (matcher(elem, context, xml)) {
return elem;
}
}
}
}
};
}
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 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) {
if (seed && postFinder) {
return;
}
var i, elem, postFilterIn, preMap = [],
postMap = [],
preexisting = results.length,
elems = seed || multipleContexts(selector || "*", context.nodeType ? [context] : context, [], seed),
matcherIn = preFilter && (seed || !selector) ? condense(elems, preMap, preFilter, context, xml) : elems,
matcherOut = matcher ? postFinder || (seed ? preFilter : preexisting || postFilter) ? [] : results : matcherIn;
if (matcher) {
matcher(matcherIn, matcherOut, context, xml);
}
if (postFilter) {
postFilterIn = condense(matcherOut, postMap);
postFilter(postFilterIn, [], context, xml);
i = postFilterIn.length;
while (i--) {
if ((elem = postFilterIn[i])) {
matcherOut[postMap[i]] = !(matcherIn[postMap[i]] = elem);
}
}
}
if (seed) {
i = preFilter && matcherOut.length;
while (i--) {
if ((elem = matcherOut[i])) {
seed[preMap[i]] = !(results[preMap[i]] = elem);
}
}
} 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,
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);
if (matcher[expando]) {
j = ++i;
for (; j < len; j++) {
if (Expr.relative[tokens[j].type]) {
break;
}
}
return setMatcher(i > 1 && elementMatcher(matchers), i > 1 && tokens.slice(0, i - 1)
.join("")
.replace(rtrim, "$1"), matcher, i < j && matcherFromTokens(tokens.slice(i, j)), j < len && matcherFromTokens((tokens = tokens.slice(j))), j < len && tokens.join(""));
}
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, expandContext) {
var elem, j, matcher, setMatched = [],
matchedCount = 0,
i = "0",
unmatched = seed && [],
outermost = expandContext != null,
contextBackup = outermostContext,
elems = seed || byElement && Expr.find["TAG"]("*", expandContext && context.parentNode || context),
dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.E);
if (outermost) {
outermostContext = context !== document && context;
cachedruns = superMatcher.el;
}
for (;
(elem = elems[i]) != null; i++) {
if (byElement && elem) {
for (j = 0;
(matcher = elementMatchers[j]); j++) {
if (matcher(elem, context, xml)) {
results.push(elem);
break;
}
}
if (outermost) {
dirruns = dirrunsUnique;
cachedruns = ++superMatcher.el;
}
}
if (bySet) {
if ((elem = !matcher && elem)) {
matchedCount--;
}
if (seed) {
unmatched.push(elem);
}
}
}
matchedCount += i;
if (bySet && i !== matchedCount) {
for (j = 0;
(matcher = setMatchers[j]); j++) {
matcher(unmatched, setMatched, context, xml);
}
if (seed) {
if (matchedCount > 0) {
while (i--) {
if (!(unmatched[i] || setMatched[i])) {
setMatched[i] = pop.call(results);
}
}
}
setMatched = condense(setMatched);
}
push.apply(results, setMatched);
if (outermost && !seed && setMatched.length > 0 && (matchedCount + setMatchers.length) > 1) {
Sizzle.uniqueSort(results);
}
}
if (outermost) {
dirruns = dirrunsUnique;
outermostContext = contextBackup;
}
return unmatched;
};
superMatcher.el = 0;
return bySet ? markFunction(superMatcher) : superMatcher;
}
compile = Sizzle.compile = function(selector, group) {
var i, setMatchers = [],
elementMatchers = [],
cached = compilerCache[expando][selector];
if (!cached) {
if (!group) {
group = tokenize(selector);
}
i = group.length;
while (i--) {
cached = matcherFromTokens(group[i]);
if (cached[expando]) {
setMatchers.push(cached);
} else {
elementMatchers.push(cached);
}
}
cached = compilerCache(selector, matcherFromGroupMatchers(elementMatchers, setMatchers));
}
return cached;
};
function multipleContexts(selector, contexts, results, seed) {
var i = 0,
len = contexts.length;
for (; i < len; i++) {
Sizzle(selector, contexts[i], results, seed);
}
return results;
}
function select(selector, context, results, seed, xml) {
var i, tokens, token, type, find, match = tokenize(selector),
j = match.length;
if (!seed) {
if (match.length === 1) {
tokens = match[0] = match[0].slice(0);
if (tokens.length > 2 && (token = tokens[0])
.type === "ID" && context.nodeType === 9 && !xml && Expr.relative[tokens[1].type]) {
context = Expr.find["ID"](token.matches[0].replace(rbackslash, ""), context, xml)[0];
if (!context) {
return results;
}
selector = selector.slice(tokens.shift()
.length);
}
for (i = matchExpr["POS"].test(selector) ? -1 : tokens.length - 1; i >= 0; i--) {
token = tokens[i];
if (Expr.relative[(type = token.type)]) {
break;
}
if ((find = Expr.find[type])) {
if ((seed = find(token.matches[0].replace(rbackslash, ""), rsibling.test(tokens[0].type) && context.parentNode || context, xml))) {
tokens.splice(i, 1);
selector = seed.length && tokens.join("");
if (!selector) {
push.apply(results, slice.call(seed, 0));
return results;
}
break;
}
}
}
}
}
compile(selector, match)(seed, context, xml, results, rsibling.test(selector));
return results;
}
if (document.querySelectorAll) {
(function() {
var disconnectedMatch, oldSelect = select,
rescape = /'|\\/g,
rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,
rbuggyQSA = [":focus"],
rbuggyMatches = [":active", ":focus"],
matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector;
assert(function(div) {
div.innerHTML = "<select><option selected=''></option></select>";
if (!div.querySelectorAll("[selected]")
.length) {
rbuggyQSA.push("\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)");
}
if (!div.querySelectorAll(":checked")
.length) {
rbuggyQSA.push(":checked");
}
});
assert(function(div) {
div.innerHTML = "<p test=''></p>";
if (div.querySelectorAll("[test^='']")
.length) {
rbuggyQSA.push("[*^$]=" + whitespace + "*(?:\"\"|'')");
}
div.innerHTML = "<input type='hidden'/>";
if (!div.querySelectorAll(":enabled")
.length) {
rbuggyQSA.push(":enabled", ":disabled");
}
});
rbuggyQSA = new RegExp(rbuggyQSA.join("|"));
select = function(selector, context, results, seed, xml) {
if (!seed && !xml && (!rbuggyQSA || !rbuggyQSA.test(selector))) {
var groups, i, old = true,
nid = expando,
newContext = context,
newSelector = context.nodeType === 9 && selector;
if (context.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 + groups[i].join("");
}
newContext = rsibling.test(selector) && context.parentNode || context;
newSelector = groups.join(",");
}
if (newSelector) {
try {
push.apply(results, slice.call(newContext.querySelectorAll(newSelector), 0));
return results;
} catch (qsaError) {} finally {
if (!old) {
context.removeAttribute("id");
}
}
}
}
return oldSelect(selector, context, results, seed, xml);
};
if (matches) {
assert(function(div) {
disconnectedMatch = matches.call(div, "div");
try {
matches.call(div, "[test!='']:sizzle");
rbuggyMatches.push("!=", pseudos);
} catch (e) {}
});
rbuggyMatches = new RegExp(rbuggyMatches.join("|"));
Sizzle.matchesSelector = function(elem, expr) {
expr = expr.replace(rattributeQuotes, "='$1']");
if (!isXML(elem) && !rbuggyMatches.test(expr) && (!rbuggyQSA || !rbuggyQSA.test(expr))) {
try {
var ret = matches.call(elem, expr);
if (ret || disconnectedMatch || elem.document && elem.document.nodeType !== 11) {
return ret;
}
} catch (e) {}
}
return Sizzle(expr, null, null, [elem])
.length > 0;
};
}
})();
}
Expr.pseudos["nth"] = Expr.pseudos["eq"];
function setFilters() {}
Expr.filters = setFilters.prototype = Expr.pseudos;
Expr.setFilters = new setFilters();
Sizzle.attr = jQuery.attr;
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;
})(window);
var runtil = /Until$/,
rparentsprev = /^(?:parents|prev(?:Until|All))/,
isSimple = /^.[^:#\[\.,]*$/,
rneedsContext = jQuery.expr.match.needsContext,
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function(selector) {
var i, l, length, n, r, ret, self = this;
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;
}
}
});
}
ret = this.pushStack("", "find", selector);
for (i = 0, l = this.length; i < l; i++) {
length = ret.length;
jQuery.find(selector, this[i], ret);
if (i > 0) {
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 i, targets = jQuery(target, this),
len = targets.length;
return this.filter(function() {
for (i = 0; i < len; 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" ? rneedsContext.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 cur, i = 0,
l = this.length,
ret = [],
pos = rneedsContext.test(selectors) || typeof selectors !== "string" ? jQuery(selectors, context || this.context) : 0;
for (; i < l; i++) {
cur = this[i];
while (cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11) {
if (pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors)) {
ret.push(cur);
break;
}
cur = cur.parentNode;
}
}
ret = ret.length > 1 ? jQuery.unique(ret) : ret;
return this.pushStack(ret, "closest", selectors);
},
index: function(elem) {
if (!elem) {
return (this[0] && this[0].parentNode) ? this.prevAll()
.length : -1;
}
if (typeof elem === "string") {
return jQuery.inArray(this[0], jQuery(elem));
}
return jQuery.inArray(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));
},
addBack: function(selector) {
return this.add(selector == null ? this.prevObject : this.prevObject.filter(selector));
}
});
jQuery.fn.andSelf = jQuery.fn.addBack;
function isDisconnected(node) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
function sibling(cur, dir) {
do {
cur = cur[dir];
} while (cur && 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 jQuery.nodeName(elem, "iframe") ? elem.contentDocument || elem.contentWindow.document : jQuery.merge([], 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 && rparentsprev.test(name)) {
ret = ret.reverse();
}
return this.pushStack(ret, name, core_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;
},
sibling: function(n, elem) {
var r = [];
for (; n; n = n.nextSibling) {
if (n.nodeType === 1 && n !== elem) {
r.push(n);
}
}
return r;
}
});
function winnow(elements, qualifier, keep) {
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+="(?:null|\d+)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style|link)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
rcheckableType = /^(?:checkbox|radio)$/,
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,
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),
fragmentDiv = safeFragment.appendChild(document.createElement("div"));
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
if (!jQuery.support.htmlSerialize) {
wrapMap._default = [1, "X<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]) {
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.nodeType === 11) {
this.appendChild(elem);
}
});
},
prepend: function() {
return this.domManip(arguments, true, function(elem) {
if (this.nodeType === 1 || this.nodeType === 11) {
this.insertBefore(elem, this.firstChild);
}
});
},
before: function() {
if (!isDisconnected(this[0])) {
return this.domManip(arguments, false, function(elem) {
this.parentNode.insertBefore(elem, this);
});
}
if (arguments.length) {
var set = jQuery.clean(arguments);
return this.pushStack(jQuery.merge(set, this), "before", this.selector);
}
},
after: function() {
if (!isDisconnected(this[0])) {
return this.domManip(arguments, false, function(elem) {
this.parentNode.insertBefore(elem, this.nextSibling);
});
}
if (arguments.length) {
var set = jQuery.clean(arguments);
return this.pushStack(jQuery.merge(this, set), "after", this.selector);
}
},
remove: function(selector, keepData) {
var elem, i = 0;
for (;
(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() {
var elem, i = 0;
for (;
(elem = this[i]) != null; i++) {
if (elem.nodeType === 1) {
jQuery.cleanData(elem.getElementsByTagName("*"));
}
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, "") : undefined;
}
if (typeof value === "string" && !rnoInnerhtml.test(value) && (jQuery.support.htmlSerialize || !rnoshimcache.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++) {
elem = this[i] || {};
if (elem.nodeType === 1) {
jQuery.cleanData(elem.getElementsByTagName("*"));
elem.innerHTML = value;
}
}
elem = 0;
} catch (e) {}
}
if (elem) {
this.empty()
.append(value);
}
}, null, value, arguments.length);
},
replaceWith: function(value) {
if (!isDisconnected(this[0])) {
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);
}
});
}
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) {
args = [].concat.apply([], args);
var results, first, fragment, iNoClone, i = 0,
value = args[0],
scripts = [],
l = this.length;
if (!jQuery.support.checkClone && l > 1 && typeof value === "string" && rchecked.test(value)) {
return this.each(function() {
jQuery(this)
.domManip(args, table, callback);
});
}
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]) {
results = jQuery.buildFragment(args, this, scripts);
fragment = results.fragment;
first = fragment.firstChild;
if (fragment.childNodes.length === 1) {
fragment = first;
}
if (first) {
table = table && jQuery.nodeName(first, "tr");
for (iNoClone = results.cacheable || l - 1; i < l; i++) {
callback.call(table && jQuery.nodeName(this[i], "table") ? findOrAppend(this[i], "tbody") : this[i], i === iNoClone ? fragment : jQuery.clone(fragment, true, true));
}
}
fragment = first = null;
if (scripts.length) {
jQuery.each(scripts, function(i, elem) {
if (elem.src) {
if (jQuery.ajax) {
jQuery.ajax({
url: elem.src,
type: "GET",
dataType: "script",
async: false,
global: false,
"throws": true
});
} else {
jQuery.error("no ajax");
}
} else {
jQuery.globalEval((elem.text || elem.textContent || elem.innerHTML || "")
.replace(rcleanScript, ""));
}
if (elem.parentNode) {
elem.parentNode.removeChild(elem);
}
});
}
}
return this;
}
});
function findOrAppend(elem, tag) {
return elem.getElementsByTagName(tag)[0] || elem.appendChild(elem.ownerDocument.createElement(tag));
}
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]);
}
}
}
if (curData.data) {
curData.data = jQuery.extend({}, curData.data);
}
}
function cloneFixAttributes(src, dest) {
var nodeName;
if (dest.nodeType !== 1) {
return;
}
if (dest.clearAttributes) {
dest.clearAttributes();
}
if (dest.mergeAttributes) {
dest.mergeAttributes(src);
}
nodeName = dest.nodeName.toLowerCase();
if (nodeName === "object") {
if (dest.parentNode) {
dest.outerHTML = src.outerHTML;
}
if (jQuery.support.html5Clone && (src.innerHTML && !jQuery.trim(dest.innerHTML))) {
dest.innerHTML = src.innerHTML;
}
} else if (nodeName === "input" && rcheckableType.test(src.type)) {
dest.defaultChecked = dest.checked = src.checked;
if (dest.value !== src.value) {
dest.value = src.value;
}
} else if (nodeName === "option") {
dest.selected = src.defaultSelected;
} else if (nodeName === "input" || nodeName === "textarea") {
dest.defaultValue = src.defaultValue;
} else if (nodeName === "script" && dest.text !== src.text) {
dest.text = src.text;
}
dest.removeAttribute(jQuery.expando);
}
jQuery.buildFragment = function(args, context, scripts) {
var fragment, cacheable, cachehit, first = args[0];
context = context || document;
context = !context.nodeType && context[0] || context;
context = context.ownerDocument || context;
if (args.length === 1 && typeof first === "string" && first.length < 512 && context === document && first.charAt(0) === "<" && !rnocache.test(first) && (jQuery.support.checkClone || !rchecked.test(first)) && (jQuery.support.html5Clone || !rnoshimcache.test(first))) {
cacheable = true;
fragment = jQuery.fragments[first];
cachehit = fragment !== undefined;
}
if (!fragment) {
fragment = context.createDocumentFragment();
jQuery.clean(args, context, fragment, scripts);
if (cacheable) {
jQuery.fragments[first] = cachehit && fragment;
}
}
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 elems, i = 0,
ret = [],
insert = jQuery(selector),
l = insert.length,
parent = this.length === 1 && this[0].parentNode;
if ((parent == null || parent && parent.nodeType === 11 && parent.childNodes.length === 1) && l === 1) {
insert[original](this[0]);
return this;
} else {
for (; i < l; i++) {
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 [];
}
}
function fixDefaultChecked(elem) {
if (rcheckableType.test(elem.type)) {
elem.defaultChecked = elem.checked;
}
}
jQuery.extend({
clone: function(elem, dataAndEvents, deepDataAndEvents) {
var srcElements, destElements, i, clone;
if (jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test("<" + elem.nodeName + ">")) {
clone = elem.cloneNode(true);
} else {
fragmentDiv.innerHTML = elem.outerHTML;
fragmentDiv.removeChild(clone = fragmentDiv.firstChild);
}
if ((!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem)) {
cloneFixAttributes(elem, clone);
srcElements = getAll(elem);
destElements = getAll(clone);
for (i = 0; srcElements[i]; ++i) {
if (destElements[i]) {
cloneFixAttributes(srcElements[i], destElements[i]);
}
}
}
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 clone;
},
clean: function(elems, context, fragment, scripts) {
var i, j, elem, tag, wrap, depth, div, hasBody, tbody, len, handleScript, jsTags, safe = context === document && safeFragment,
ret = [];
if (!context || typeof context.createDocumentFragment === "undefined") {
context = document;
}
for (i = 0;
(elem = elems[i]) != null; i++) {
if (typeof elem === "number") {
elem += "";
}
if (!elem) {
continue;
}
if (typeof elem === "string") {
if (!rhtml.test(elem)) {
elem = context.createTextNode(elem);
} else {
safe = safe || createSafeFragment(context);
div = context.createElement("div");
safe.appendChild(div);
elem = elem.replace(rxhtmlTag, "<$1></$2>");
tag = (rtagName.exec(elem) || ["", ""])[1].toLowerCase();
wrap = wrapMap[tag] || wrapMap._default;
depth = wrap[0];
div.innerHTML = wrap[1] + elem + wrap[2];
while (depth--) {
div = div.lastChild;
}
if (!jQuery.support.tbody) {
hasBody = rtbody.test(elem);
tbody = tag === "table" && !hasBody ? div.firstChild && div.firstChild.childNodes : 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]);
}
}
}
if (!jQuery.support.leadingWhitespace && rleadingWhitespace.test(elem)) {
div.insertBefore(context.createTextNode(rleadingWhitespace.exec(elem)[0]), div.firstChild);
}
elem = div.childNodes;
div.parentNode.removeChild(div);
}
}
if (elem.nodeType) {
ret.push(elem);
} else {
jQuery.merge(ret, elem);
}
}
if (div) {
elem = div = safe = null;
}
if (!jQuery.support.appendChecked) {
for (i = 0;
(elem = ret[i]) != null; i++) {
if (jQuery.nodeName(elem, "input")) {
fixDefaultChecked(elem);
} else if (typeof elem.getElementsByTagName !== "undefined") {
jQuery.grep(elem.getElementsByTagName("input"), fixDefaultChecked);
}
}
}
if (fragment) {
handleScript = function(elem) {
if (!elem.type || rscriptType.test(elem.type)) {
return scripts ? scripts.push(elem.parentNode ? elem.parentNode.removeChild(elem) : elem) : fragment.appendChild(elem);
}
};
for (i = 0;
(elem = ret[i]) != null; i++) {
if (!(jQuery.nodeName(elem, "script") && handleScript(elem))) {
fragment.appendChild(elem);
if (typeof elem.getElementsByTagName !== "undefined") {
jsTags = jQuery.grep(jQuery.merge([], elem.getElementsByTagName("script")), handleScript);
ret.splice.apply(ret, [i + 1, 0].concat(jsTags));
i += jsTags.length;
}
}
}
}
return ret;
},
cleanData: function(elems, acceptData) {
var data, id, elem, type, i = 0,
internalKey = jQuery.expando,
cache = jQuery.cache,
deleteExpando = jQuery.support.deleteExpando,
special = jQuery.event.special;
for (;
(elem = elems[i]) != null; i++) {
if (acceptData || jQuery.acceptData(elem)) {
id = elem[internalKey];
data = id && cache[id];
if (data) {
if (data.events) {
for (type in data.events) {
if (special[type]) {
jQuery.event.remove(elem, type);
} else {
jQuery.removeEvent(elem, type, data.handle);
}
}
}
if (cache[id]) {
delete cache[id];
if (deleteExpando) {
delete elem[internalKey];
} else if (elem.removeAttribute) {
elem.removeAttribute(internalKey);
} else {
elem[internalKey] = null;
}
jQuery.deletedIds.push(id);
}
}
}
}
}
});
(function() {
var matched, browser;
jQuery.uaMatch = function(ua) {
ua = ua.toLowerCase();
var match = /(chrome)[ \/]([\w.]+)/.exec(ua) || /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) || /(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) || [];
return {
browser: match[1] || "",
version: match[2] || "0"
};
};
matched = jQuery.uaMatch(navigator.userAgent);
browser = {};
if (matched.browser) {
browser[matched.browser] = true;
browser.version = matched.version;
}
if (browser.chrome) {
browser.webkit = true;
} else if (browser.webkit) {
browser.safari = true;
}
jQuery.browser = browser;
jQuery.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;
};
})();
var curCSS, iframe, iframeDoc, ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
rposition = /^(top|right|bottom|left)$/,
rdisplayswap = /^(none|table(?!-c[ea]).+)/,
rmargin = /^margin/,
rnumsplit = new RegExp("^(" + core_pnum + ")(.*)$", "i"),
rnumnonpx = new RegExp("^(" + core_pnum + ")(?!px)[a-z%]+$", "i"),
rrelNum = new RegExp("^([-+])=(" + core_pnum + ")", "i"),
elemdisplay = {}, cssShow = {
position: "absolute",
visibility: "hidden",
display: "block"
}, cssNormalTransform = {
letterSpacing: 0,
fontWeight: 400
}, cssExpand = ["Top", "Right", "Bottom", "Left"],
cssPrefixes = ["Webkit", "O", "Moz", "ms"],
eventsToggle = jQuery.fn.toggle;
function vendorPropName(style, name) {
if (name in style) {
return name;
}
var capName = name.charAt(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 isHidden(elem, el) {
elem = el || elem;
return jQuery.css(elem, "display") === "none" || !jQuery.contains(elem.ownerDocument, elem);
}
function showHide(elements, show) {
var elem, display, values = [],
index = 0,
length = elements.length;
for (; index < length; index++) {
elem = elements[index];
if (!elem.style) {
continue;
}
values[index] = jQuery._data(elem, "olddisplay");
if (show) {
if (!values[index] && elem.style.display === "none") {
elem.style.display = "";
}
if (elem.style.display === "" && isHidden(elem)) {
values[index] = jQuery._data(elem, "olddisplay", css_defaultDisplay(elem.nodeName));
}
} else {
display = curCSS(elem, "display");
if (!values[index] && display !== "none") {
jQuery._data(elem, "olddisplay", display);
}
}
}
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.fn.extend({
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);
},
show: function() {
return showHide(this, true);
},
hide: function() {
return showHide(this);
},
toggle: function(state, fn2) {
var bool = typeof state === "boolean";
if (jQuery.isFunction(state) && jQuery.isFunction(fn2)) {
return eventsToggle.apply(this, arguments);
}
return this.each(function() {
if (bool ? state : isHidden(this)) {
jQuery(this)
.show();
} else {
jQuery(this)
.hide();
}
});
}
});
jQuery.extend({
cssHooks: {
opacity: {
get: function(elem, computed) {
if (computed) {
var ret = curCSS(elem, "opacity");
return ret === "" ? "1" : ret;
}
}
}
},
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
cssProps: {
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
style: function(elem, name, value, extra) {
if (!elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style) {
return;
}
var ret, type, hooks, origName = jQuery.camelCase(name),
style = elem.style;
name = jQuery.cssProps[origName] || (jQuery.cssProps[origName] = vendorPropName(style, origName));
hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName];
if (value !== undefined) {
type = typeof value;
if (type === "string" && (ret = rrelNum.exec(value))) {
value = (ret[1] + 1) * ret[2] + parseFloat(jQuery.css(elem, name));
type = "number";
}
if (value == null || type === "number" && isNaN(value)) {
return;
}
if (type === "number" && !jQuery.cssNumber[origName]) {
value += "px";
}
if (!hooks || !("set" in hooks) || (value = hooks.set(elem, value, extra)) !== undefined) {
try {
style[name] = value;
} catch (e) {}
}
} else {
if (hooks && "get" in hooks && (ret = hooks.get(elem, false, extra)) !== undefined) {
return ret;
}
return style[name];
}
},
css: function(elem, name, numeric, extra) {
var val, num, hooks, origName = jQuery.camelCase(name);
name = jQuery.cssProps[origName] || (jQuery.cssProps[origName] = vendorPropName(elem.style, origName));
hooks = jQuery.cssHooks[name] || jQuery.cssHooks[origName];
if (hooks && "get" in hooks) {
val = hooks.get(elem, true, extra);
}
if (val === undefined) {
val = curCSS(elem, name);
}
if (val === "normal" && name in cssNormalTransform) {
val = cssNormalTransform[name];
}
if (numeric || extra !== undefined) {
num = parseFloat(val);
return numeric || jQuery.isNumeric(num) ? num || 0 : val;
}
return val;
},
swap: function(elem, options, callback) {
var ret, name, old = {};
for (name in options) {
old[name] = elem.style[name];
elem.style[name] = options[name];
}
ret = callback.call(elem);
for (name in options) {
elem.style[name] = old[name];
}
return ret;
}
});
if (window.getComputedStyle) {
curCSS = function(elem, name) {
var ret, width, minWidth, maxWidth, computed = window.getComputedStyle(elem, null),
style = elem.style;
if (computed) {
ret = computed[name];
if (ret === "" && !jQuery.contains(elem.ownerDocument, elem)) {
ret = jQuery.style(elem, name);
}
if (rnumnonpx.test(ret) && rmargin.test(name)) {
width = style.width;
minWidth = style.minWidth;
maxWidth = style.maxWidth;
style.minWidth = style.maxWidth = style.width = ret;
ret = computed.width;
style.width = width;
style.minWidth = minWidth;
style.maxWidth = maxWidth;
}
}
return ret;
};
} else if (document.documentElement.currentStyle) {
curCSS = function(elem, name) {
var left, rsLeft, ret = elem.currentStyle && elem.currentStyle[name],
style = elem.style;
if (ret == null && style && style[name]) {
ret = style[name];
}
if (rnumnonpx.test(ret) && !rposition.test(name)) {
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
if (rsLeft) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
ret = style.pixelLeft + "px";
style.left = left;
if (rsLeft) {
elem.runtimeStyle.left = rsLeft;
}
}
return ret === "" ? "auto" : ret;
};
}
function setPositiveNumber(elem, value, subtract) {
var matches = rnumsplit.exec(value);
return matches ? Math.max(0, matches[1] - (subtract || 0)) + (matches[2] || "px") : value;
}
function augmentWidthOrHeight(elem, name, extra, isBorderBox) {
var i = extra === (isBorderBox ? "border" : "content") ? 4 : name === "width" ? 1 : 0,
val = 0;
for (; i < 4; i += 2) {
if (extra === "margin") {
val += jQuery.css(elem, extra + cssExpand[i], true);
}
if (isBorderBox) {
if (extra === "content") {
val -= parseFloat(curCSS(elem, "padding" + cssExpand[i])) || 0;
}
if (extra !== "margin") {
val -= parseFloat(curCSS(elem, "border" + cssExpand[i] + "Width")) || 0;
}
} else {
val += parseFloat(curCSS(elem, "padding" + cssExpand[i])) || 0;
if (extra !== "padding") {
val += parseFloat(curCSS(elem, "border" + cssExpand[i] + "Width")) || 0;
}
}
}
return val;
}
function getWidthOrHeight(elem, name, extra) {
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
valueIsBorderBox = true,
isBorderBox = jQuery.support.boxSizing && jQuery.css(elem, "boxSizing") === "border-box";
if (val <= 0 || val == null) {
val = curCSS(elem, name);
if (val < 0 || val == null) {
val = elem.style[name];
}
if (rnumnonpx.test(val)) {
return val;
}
valueIsBorderBox = isBorderBox && (jQuery.support.boxSizingReliable || val === elem.style[name]);
val = parseFloat(val) || 0;
}
return (val + augmentWidthOrHeight(elem, name, extra || (isBorderBox ? "border" : "content"), valueIsBorderBox)) + "px";
}
function css_defaultDisplay(nodeName) {
if (elemdisplay[nodeName]) {
return elemdisplay[nodeName];
}
var elem = jQuery("<" + nodeName + ">")
.appendTo(document.body),
display = elem.css("display");
elem.remove();
if (display === "none" || display === "") {
iframe = document.body.appendChild(iframe || jQuery.extend(document.createElement("iframe"), {
frameBorder: 0,
width: 0,
height: 0
}));
if (!iframeDoc || !iframe.createElement) {
iframeDoc = (iframe.contentWindow || iframe.contentDocument)
.document;
iframeDoc.write("<!doctype html><html><body>");
iframeDoc.close();
}
elem = iframeDoc.body.appendChild(iframeDoc.createElement(nodeName));
display = curCSS(elem, "display");
document.body.removeChild(iframe);
}
elemdisplay[nodeName] = display;
return display;
}
jQuery.each(["height", "width"], function(i, name) {
jQuery.cssHooks[name] = {
get: function(elem, computed, extra) {
if (computed) {
if (elem.offsetWidth === 0 && rdisplayswap.test(curCSS(elem, "display"))) {
return jQuery.swap(elem, cssShow, function() {
return getWidthOrHeight(elem, name, extra);
});
} else {
return getWidthOrHeight(elem, name, extra);
}
}
},
set: function(elem, value, extra) {
return setPositiveNumber(elem, value, extra ? augmentWidthOrHeight(elem, name, extra, jQuery.support.boxSizing && jQuery.css(elem, "boxSizing") === "border-box") : 0);
}
};
});
if (!jQuery.support.opacity) {
jQuery.cssHooks.opacity = {
get: function(elem, computed) {
return ropacity.test((computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "") ? (0.01 * parseFloat(RegExp.$1)) + "" : 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 || "";
style.zoom = 1;
if (value >= 1 && jQuery.trim(filter.replace(ralpha, "")) === "" && style.removeAttribute) {
style.removeAttribute("filter");
if (currentStyle && !currentStyle.filter) {
return;
}
}
style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : filter + " " + opacity;
}
};
}
jQuery(function() {
if (!jQuery.support.reliableMarginRight) {
jQuery.cssHooks.marginRight = {
get: function(elem, computed) {
return jQuery.swap(elem, {
"display": "inline-block"
}, function() {
if (computed) {
return curCSS(elem, "marginRight");
}
});
}
};
}
if (!jQuery.support.pixelPosition && jQuery.fn.position) {
jQuery.each(["top", "left"], function(i, prop) {
jQuery.cssHooks[prop] = {
get: function(elem, computed) {
if (computed) {
var ret = curCSS(elem, prop);
return rnumnonpx.test(ret) ? jQuery(elem)
.position()[prop] + "px" : ret;
}
}
};
});
}
});
if (jQuery.expr && jQuery.expr.filters) {
jQuery.expr.filters.hidden = function(elem) {
return (elem.offsetWidth === 0 && elem.offsetHeight === 0) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || curCSS(elem, "display")) === "none");
};
jQuery.expr.filters.visible = function(elem) {
return !jQuery.expr.filters.hidden(elem);
};
}
jQuery.each({
margin: "",
padding: "",
border: "Width"
}, function(prefix, suffix) {
jQuery.cssHooks[prefix + suffix] = {
expand: function(value) {
var i, 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;
}
};
if (!rmargin.test(prefix)) {
jQuery.cssHooks[prefix + suffix].set = setPositiveNumber;
}
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
rselectTextarea = /^(?:select|textarea)/i;
jQuery.fn.extend({
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();
}
});
jQuery.param = function(a, traditional) {
var prefix, s = [],
add = function(key, value) {
value = jQuery.isFunction(value) ? value() : (value == null ? "" : value);
s[s.length] = encodeURIComponent(key) + "=" + encodeURIComponent(value);
};
if (traditional === undefined) {
traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
}
if (jQuery.isArray(a) || (a.jquery && !jQuery.isPlainObject(a))) {
jQuery.each(a, function() {
add(this.name, this.value);
});
} else {
for (prefix in a) {
buildParams(prefix, a[prefix], traditional, add);
}
}
return s.join("&")
.replace(r20, "+");
};
function buildParams(prefix, obj, traditional, add) {
var name;
if (jQuery.isArray(obj)) {
jQuery.each(obj, function(i, v) {
if (traditional || rbracket.test(prefix)) {
add(prefix, v);
} else {
buildParams(prefix + "[" + (typeof v === "object" ? i : "") + "]", v, traditional, add);
}
});
} else if (!traditional && jQuery.type(obj) === "object") {
for (name in obj) {
buildParams(prefix + "[" + name + "]", obj[name], traditional, add);
}
} else {
add(prefix, obj);
}
}
var
ajaxLocParts, ajaxLocation, rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg,
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,
_load = jQuery.fn.load,
prefilters = {}, transports = {}, allTypes = ["*/"] + ["*"];
try {
ajaxLocation = location.href;
} catch (e) {
ajaxLocation = document.createElement("a");
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
ajaxLocParts = rurl.exec(ajaxLocation.toLowerCase()) || [];
function addToPrefiltersOrTransports(structure) {
return function(dataTypeExpression, func) {
if (typeof dataTypeExpression !== "string") {
func = dataTypeExpression;
dataTypeExpression = "*";
}
var dataType, list, placeBefore, dataTypes = dataTypeExpression.toLowerCase()
.split(core_rspace),
i = 0,
length = dataTypes.length;
if (jQuery.isFunction(func)) {
for (; i < length; i++) {
dataType = dataTypes[i];
placeBefore = /^\+/.test(dataType);
if (placeBefore) {
dataType = dataType.substr(1) || "*";
}
list = structure[dataType] = structure[dataType] || [];
list[placeBefore ? "unshift" : "push"](func);
}
}
};
}
function inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR, dataType, inspected) {
dataType = dataType || options.dataTypes[0];
inspected = inspected || {};
inspected[dataType] = true;
var selection, list = structure[dataType],
i = 0,
length = list ? list.length : 0,
executeOnly = (structure === prefilters);
for (; i < length && (executeOnly || !selection); i++) {
selection = list[i](options, originalOptions, jqXHR);
if (typeof selection === "string") {
if (!executeOnly || inspected[selection]) {
selection = undefined;
} else {
options.dataTypes.unshift(selection);
selection = inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR, selection, inspected);
}
}
}
if ((executeOnly || !selection) && !inspected["*"]) {
selection = inspectPrefiltersOrTransports(structure, options, originalOptions, jqXHR, "*", inspected);
}
return selection;
}
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.load = function(url, params, callback) {
if (typeof url !== "string" && _load) {
return _load.apply(this, arguments);
}
if (!this.length) {
return this;
}
var selector, type, response, self = this,
off = url.indexOf(" ");
if (off >= 0) {
selector = url.slice(off, url.length);
url = url.slice(0, off);
}
if (jQuery.isFunction(params)) {
callback = params;
params = undefined;
} else if (params && typeof params === "object") {
type = "POST";
}
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
complete: function(jqXHR, status) {
if (callback) {
self.each(callback, response || [jqXHR.responseText, status, jqXHR]);
}
}
})
.done(function(responseText) {
response = arguments;
self.html(selector ? jQuery("<div>")
.append(responseText.replace(rscript, ""))
.find(selector) : responseText);
});
return this;
};
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) {
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");
},
ajaxSetup: function(target, settings) {
if (settings) {
ajaxExtend(target, jQuery.ajaxSettings);
} else {
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,
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"
},
converters: {
"* text": window.String,
"text html": true,
"text json": jQuery.parseJSON,
"text xml": jQuery.parseXML
},
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports(prefilters),
ajaxTransport: addToPrefiltersOrTransports(transports),
ajax: function(url, options) {
if (typeof url === "object") {
options = url;
url = undefined;
}
options = options || {};
var
ifModifiedKey, responseHeadersString, responseHeaders, transport, timeoutTimer, parts, fireGlobals, i, s = jQuery.ajaxSetup({}, options),
callbackContext = s.context || s,
globalEventContext = callbackContext !== s && (callbackContext.nodeType || callbackContext instanceof jQuery) ? jQuery(callbackContext) : jQuery.event,
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks("once memory"),
statusCode = s.statusCode || {}, requestHeaders = {}, requestHeadersNames = {}, state = 0,
strAbort = "canceled",
jqXHR = {
readyState: 0,
setRequestHeader: function(name, value) {
if (!state) {
var lname = name.toLowerCase();
name = requestHeadersNames[lname] = requestHeadersNames[lname] || name;
requestHeaders[name] = value;
}
return this;
},
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
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;
},
overrideMimeType: function(type) {
if (!state) {
s.mimeType = type;
}
return this;
},
abort: function(statusText) {
statusText = statusText || strAbort;
if (transport) {
transport.abort(statusText);
}
done(0, statusText);
return this;
}
};
function done(status, nativeStatusText, responses, headers) {
var isSuccess, success, error, response, modified, statusText = nativeStatusText;
if (state === 2) {
return;
}
state = 2;
if (timeoutTimer) {
clearTimeout(timeoutTimer);
}
transport = undefined;
responseHeadersString = headers || "";
jqXHR.readyState = status > 0 ? 4 : 0;
if (responses) {
response = ajaxHandleResponses(s, jqXHR, responses);
}
if (status >= 200 && status < 300 || status === 304) {
if (s.ifModified) {
modified = jqXHR.getResponseHeader("Last-Modified");
if (modified) {
jQuery.lastModified[ifModifiedKey] = modified;
}
modified = jqXHR.getResponseHeader("Etag");
if (modified) {
jQuery.etag[ifModifiedKey] = modified;
}
}
if (status === 304) {
statusText = "notmodified";
isSuccess = true;
} else {
isSuccess = ajaxConvert(s, response);
statusText = isSuccess.state;
success = isSuccess.data;
error = isSuccess.error;
isSuccess = !error;
}
} else {
error = statusText;
if (!statusText || status) {
statusText = "error";
if (status < 0) {
status = 0;
}
}
}
jqXHR.status = status;
jqXHR.statusText = (nativeStatusText || statusText) + "";
if (isSuccess) {
deferred.resolveWith(callbackContext, [success, statusText, jqXHR]);
} else {
deferred.rejectWith(callbackContext, [jqXHR, statusText, error]);
}
jqXHR.statusCode(statusCode);
statusCode = undefined;
if (fireGlobals) {
globalEventContext.trigger("ajax" + (isSuccess ? "Success" : "Error"), [jqXHR, s, isSuccess ? success : error]);
}
completeDeferred.fireWith(callbackContext, [jqXHR, statusText]);
if (fireGlobals) {
globalEventContext.trigger("ajaxComplete", [jqXHR, s]);
if (!(--jQuery.active)) {
jQuery.event.trigger("ajaxStop");
}
}
}
deferred.promise(jqXHR);
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
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.always(tmp);
}
}
return this;
};
s.url = ((url || s.url) + "")
.replace(rhash, "")
.replace(rprotocol, ajaxLocParts[1] + "//");
s.dataTypes = jQuery.trim(s.dataType || "*")
.toLowerCase()
.split(core_rspace);
if (s.crossDomain == null) {
parts = rurl.exec(s.url.toLowerCase()) || false;
s.crossDomain = parts && (parts.join(":") + (parts[3] ? "" : parts[1] === "http:" ? 80 : 443)) !== (ajaxLocParts.join(":") + (ajaxLocParts[3] ? "" : ajaxLocParts[1] === "http:" ? 80 : 443));
}
if (s.data && s.processData && typeof s.data !== "string") {
s.data = jQuery.param(s.data, s.traditional);
}
inspectPrefiltersOrTransports(prefilters, s, options, jqXHR);
if (state === 2) {
return jqXHR;
}
fireGlobals = s.global;
s.type = s.type.toUpperCase();
s.hasContent = !rnoContent.test(s.type);
if (fireGlobals && jQuery.active++ === 0) {
jQuery.event.trigger("ajaxStart");
}
if (!s.hasContent) {
if (s.data) {
s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
delete s.data;
}
ifModifiedKey = s.url;
if (s.cache === false) {
var ts = jQuery.now(),
ret = s.url.replace(rts, "$1_=" + ts);
s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
}
}
if (s.data && s.hasContent && s.contentType !== false || options.contentType) {
jqXHR.setRequestHeader("Content-Type", s.contentType);
}
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]);
}
}
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["*"]);
for (i in s.headers) {
jqXHR.setRequestHeader(i, s.headers[i]);
}
if (s.beforeSend && (s.beforeSend.call(callbackContext, jqXHR, s) === false || state === 2)) {
return jqXHR.abort();
}
strAbort = "abort";
for (i in {
success: 1,
error: 1,
complete: 1
}) {
jqXHR[i](s[i]);
}
transport = inspectPrefiltersOrTransports(transports, s, options, jqXHR);
if (!transport) {
done(-1, "No Transport");
} else {
jqXHR.readyState = 1;
if (fireGlobals) {
globalEventContext.trigger("ajaxSend", [jqXHR, s]);
}
if (s.async && s.timeout > 0) {
timeoutTimer = setTimeout(function() {
jqXHR.abort("timeout");
}, s.timeout);
}
try {
state = 1;
transport.send(requestHeaders, done);
} catch (e) {
if (state < 2) {
done(-1, e);
} else {
throw e;
}
}
}
return jqXHR;
},
active: 0,
lastModified: {},
etag: {}
});
function ajaxHandleResponses(s, jqXHR, responses) {
var ct, type, finalDataType, firstDataType, contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields;
for (type in responseFields) {
if (type in responses) {
jqXHR[responseFields[type]] = responses[type];
}
}
while (dataTypes[0] === "*") {
dataTypes.shift();
if (ct === undefined) {
ct = s.mimeType || jqXHR.getResponseHeader("content-type");
}
}
if (ct) {
for (type in contents) {
if (contents[type] && contents[type].test(ct)) {
dataTypes.unshift(type);
break;
}
}
}
if (dataTypes[0] in responses) {
finalDataType = dataTypes[0];
} else {
for (type in responses) {
if (!dataTypes[0] || s.converters[type + " " + dataTypes[0]]) {
finalDataType = type;
break;
}
if (!firstDataType) {
firstDataType = type;
}
}
finalDataType = finalDataType || firstDataType;
}
if (finalDataType) {
if (finalDataType !== dataTypes[0]) {
dataTypes.unshift(finalDataType);
}
return responses[finalDataType];
}
}
function ajaxConvert(s, response) {
var conv, conv2, current, tmp, dataTypes = s.dataTypes.slice(),
prev = dataTypes[0],
converters = {}, i = 0;
if (s.dataFilter) {
response = s.dataFilter(response, s.dataType);
}
if (dataTypes[1]) {
for (conv in s.converters) {
converters[conv.toLowerCase()] = s.converters[conv];
}
}
for (;
(current = dataTypes[++i]);) {
if (current !== "*") {
if (prev !== "*" && prev !== current) {
conv = converters[prev + " " + current] || converters["* " + current];
if (!conv) {
for (conv2 in converters) {
tmp = conv2.split(" ");
if (tmp[1] === current) {
conv = converters[prev + " " + tmp[0]] || converters["* " + tmp[0]];
if (conv) {
if (conv === true) {
conv = converters[conv2];
} else if (converters[conv2] !== true) {
current = tmp[0];
dataTypes.splice(i--, 0, current);
}
break;
}
}
}
}
if (conv !== true) {
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
};
}
}
}
}
prev = current;
}
}
return {
state: "success",
data: response
};
}
var oldCallbacks = [],
rquestion = /\?/,
rjsonp = /(=)\?(?=&|$)|\?\?/,
nonce = jQuery.now();
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
var callback = oldCallbacks.pop() || (jQuery.expando + "_" + (nonce++));
this[callback] = true;
return callback;
}
});
jQuery.ajaxPrefilter("json jsonp", function(s, originalSettings, jqXHR) {
var callbackName, overwritten, responseContainer, data = s.data,
url = s.url,
hasCallback = s.jsonp !== false,
replaceInUrl = hasCallback && rjsonp.test(url),
replaceInData = hasCallback && !replaceInUrl && typeof data === "string" && !(s.contentType || "")
.indexOf("application/x-www-form-urlencoded") && rjsonp.test(data);
if (s.dataTypes[0] === "jsonp" || replaceInUrl || replaceInData) {
callbackName = s.jsonpCallback = jQuery.isFunction(s.jsonpCallback) ? s.jsonpCallback() : s.jsonpCallback;
overwritten = window[callbackName];
if (replaceInUrl) {
s.url = url.replace(rjsonp, "$1" + callbackName);
} else if (replaceInData) {
s.data = data.replace(rjsonp, "$1" + callbackName);
} else if (hasCallback) {
s.url += (rquestion.test(url) ? "&" : "?") + s.jsonp + "=" + callbackName;
}
s.converters["script json"] = function() {
if (!responseContainer) {
jQuery.error(callbackName + " was not called");
}
return responseContainer[0];
};
s.dataTypes[0] = "json";
window[callbackName] = function() {
responseContainer = arguments;
};
jqXHR.always(function() {
window[callbackName] = overwritten;
if (s[callbackName]) {
s.jsonpCallback = originalSettings.jsonpCallback;
oldCallbacks.push(callbackName);
}
if (responseContainer && jQuery.isFunction(overwritten)) {
overwritten(responseContainer[0]);
}
responseContainer = overwritten = undefined;
});
return "script";
}
});
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;
}
}
});
jQuery.ajaxPrefilter("script", function(s) {
if (s.cache === undefined) {
s.cache = false;
}
if (s.crossDomain) {
s.type = "GET";
s.global = false;
}
});
jQuery.ajaxTransport("script", function(s) {
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;
script.onload = script.onreadystatechange = function(_, isAbort) {
if (isAbort || !script.readyState || /loaded|complete/.test(script.readyState)) {
script.onload = script.onreadystatechange = null;
if (head && script.parentNode) {
head.removeChild(script);
}
script = undefined;
if (!isAbort) {
callback(200, "success");
}
}
};
head.insertBefore(script, head.firstChild);
},
abort: function() {
if (script) {
script.onload(0, 1);
}
}
};
}
});
var xhrCallbacks, xhrOnUnloadAbort = window.ActiveXObject ? function() {
for (var key in xhrCallbacks) {
xhrCallbacks[key](0, 1);
}
} : false,
xhrId = 0;
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch (e) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
jQuery.ajaxSettings.xhr = window.ActiveXObject ? function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} : createStandardXHR;
(function(xhr) {
jQuery.extend(jQuery.support, {
ajax: !! xhr,
cors: !! xhr && ("withCredentials" in xhr)
});
})(jQuery.ajaxSettings.xhr());
if (jQuery.support.ajax) {
jQuery.ajaxTransport(function(s) {
if (!s.crossDomain || jQuery.support.cors) {
var callback;
return {
send: function(headers, complete) {
var handle, i, xhr = s.xhr();
if (s.username) {
xhr.open(s.type, s.url, s.async, s.username, s.password);
} else {
xhr.open(s.type, s.url, s.async);
}
if (s.xhrFields) {
for (i in s.xhrFields) {
xhr[i] = s.xhrFields[i];
}
}
if (s.mimeType && xhr.overrideMimeType) {
xhr.overrideMimeType(s.mimeType);
}
if (!s.crossDomain && !headers["X-Requested-With"]) {
headers["X-Requested-With"] = "XMLHttpRequest";
}
try {
for (i in headers) {
xhr.setRequestHeader(i, headers[i]);
}
} catch (_) {}
xhr.send((s.hasContent && s.data) || null);
callback = function(_, isAbort) {
var status, statusText, responseHeaders, responses, xml;
try {
if (callback && (isAbort || xhr.readyState === 4)) {
callback = undefined;
if (handle) {
xhr.onreadystatechange = jQuery.noop;
if (xhrOnUnloadAbort) {
delete xhrCallbacks[handle];
}
}
if (isAbort) {
if (xhr.readyState !== 4) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
if (xml && xml.documentElement) {
responses.xml = xml;
}
try {
responses.text = xhr.responseText;
} catch (_) {}
try {
statusText = xhr.statusText;
} catch (e) {
statusText = "";
}
if (!status && s.isLocal && !s.crossDomain) {
status = responses.text ? 200 : 404;
} else if (status === 1223) {
status = 204;
}
}
}
} catch (firefoxAccessException) {
if (!isAbort) {
complete(-1, firefoxAccessException);
}
}
if (responses) {
complete(status, statusText, responses, responseHeaders);
}
};
if (!s.async) {
callback();
} else if (xhr.readyState === 4) {
setTimeout(callback, 0);
} else {
handle = ++xhrId;
if (xhrOnUnloadAbort) {
if (!xhrCallbacks) {
xhrCallbacks = {};
jQuery(window)
.unload(xhrOnUnloadAbort);
}
xhrCallbacks[handle] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if (callback) {
callback(0, 1);
}
}
};
}
});
}
var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = new RegExp("^(?:([-+])=|)(" + core_pnum + ")([a-z%]*)$", "i"),
rrun = /queueHooks$/,
animationPrefilters = [defaultPrefilter],
tweeners = {
"*": [function(prop, value) {
var end, unit, tween = this.createTween(prop, value),
parts = rfxnum.exec(value),
target = tween.cur(),
start = +target || 0,
scale = 1,
maxIterations = 20;
if (parts) {
end = +parts[2];
unit = parts[3] || (jQuery.cssNumber[prop] ? "" : "px");
if (unit !== "px" && start) {
start = jQuery.css(tween.elem, prop, true) || end || 1;
do {
scale = scale || ".5";
start = start / scale;
jQuery.style(tween.elem, prop, start + unit);
} while (scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations);
}
tween.unit = unit;
tween.start = start;
tween.end = parts[1] ? start + (parts[1] + 1) * end : end;
}
return tween;
}]
};
function createFxNow() {
setTimeout(function() {
fxNow = undefined;
}, 0);
return (fxNow = jQuery.now());
}
function createTweens(animation, props) {
jQuery.each(props, function(prop, value) {
var collection = (tweeners[prop] || [])
.concat(tweeners["*"]),
index = 0,
length = collection.length;
for (; index < length; index++) {
if (collection[index].call(animation, prop, value)) {
return;
}
}
});
}
function Animation(elem, properties, options) {
var result, index = 0,
tweenerIndex = 0,
length = animationPrefilters.length,
deferred = jQuery.Deferred()
.always(function() {
delete tick.elem;
}),
tick = function() {
var currentTime = fxNow || createFxNow(),
remaining = Math.max(0, animation.startTime + animation.duration - currentTime),
percent = 1 - (remaining / animation.duration || 0),
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, easing) {
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,
length = gotoEnd ? animation.tweens.length : 0;
for (; index < length; index++) {
animation.tweens[index].run(1);
}
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;
}
}
createTweens(animation, props);
if (jQuery.isFunction(animation.opts.start)) {
animation.opts.start.call(elem, animation);
}
jQuery.fx.timer(jQuery.extend(tick, {
anim: animation,
queue: animation.opts.queue,
elem: elem
}));
return animation.progress(animation.opts.progress)
.done(animation.opts.done, animation.opts.complete)
.fail(animation.opts.fail)
.always(animation.opts.always);
}
function propFilter(props, specialEasing) {
var index, name, easing, value, hooks;
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];
for (index in value) {
if (!(index in props)) {
props[index] = value[index];
specialEasing[index] = easing;
}
}
} else {
specialEasing[name] = easing;
}
}
}
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);
}
}
});
function defaultPrefilter(elem, props, opts) {
var index, prop, value, length, dataShow, tween, hooks, oldfire, anim = this,
style = elem.style,
orig = {}, handled = [],
hidden = elem.nodeType && isHidden(elem);
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() {
anim.always(function() {
hooks.unqueued--;
if (!jQuery.queue(elem, "fx")
.length) {
hooks.empty.fire();
}
});
});
}
if (elem.nodeType === 1 && ("height" in props || "width" in props)) {
opts.overflow = [style.overflow, style.overflowX, style.overflowY];
if (jQuery.css(elem, "display") === "inline" && jQuery.css(elem, "float") === "none") {
if (!jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay(elem.nodeName) === "inline") {
style.display = "inline-block";
} else {
style.zoom = 1;
}
}
}
if (opts.overflow) {
style.overflow = "hidden";
if (!jQuery.support.shrinkWrapBlocks) {
anim.done(function() {
style.overflow = opts.overflow[0];
style.overflowX = opts.overflow[1];
style.overflowY = opts.overflow[2];
});
}
}
for (index in props) {
value = props[index];
if (rfxtypes.exec(value)) {
delete props[index];
if (value === (hidden ? "hide" : "show")) {
continue;
}
handled.push(index);
}
}
length = handled.length;
if (length) {
dataShow = jQuery._data(elem, "fxshow") || jQuery._data(elem, "fxshow", {});
if (hidden) {
jQuery(elem)
.show();
} else {
anim.done(function() {
jQuery(elem)
.hide();
});
}
anim.done(function() {
var prop;
jQuery.removeData(elem, "fxshow", true);
for (prop in orig) {
jQuery.style(elem, prop, orig[prop]);
}
});
for (index = 0; index < length; index++) {
prop = handled[index];
tween = anim.createTween(prop, hidden ? dataShow[prop] : 0);
orig[prop] = dataShow[prop] || jQuery.style(elem, prop);
if (!(prop in dataShow)) {
dataShow[prop] = tween.start;
if (hidden) {
tween.end = tween.start;
tween.start = prop === "width" || prop === "height" ? 1 : 0;
}
}
}
}
}
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];
}
result = jQuery.css(tween.elem, tween.prop, false, "");
return !result || result === "auto" ? 0 : result;
},
set: function(tween) {
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;
}
}
}
};
Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
set: function(tween) {
if (tween.elem.nodeType && tween.elem.parentNode) {
tween.elem[tween.prop] = tween.now;
}
}
};
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" || (!i && jQuery.isFunction(speed) && jQuery.isFunction(easing)) ? cssFn.apply(this, arguments) : this.animate(genFx(name, true), speed, easing, callback);
};
});
jQuery.fn.extend({
fadeTo: function(speed, to, easing, callback) {
return this.filter(isHidden)
.css("opacity", 0)
.show()
.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() {
var anim = Animation(this, jQuery.extend({}, prop), optall);
if (empty) {
anim.stop(true);
}
};
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 = jQuery._data(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);
}
}
if (dequeue || !gotoEnd) {
jQuery.dequeue(this, type);
}
});
}
});
function genFx(type, includeWidth) {
var which, attrs = {
height: type
}, i = 0;
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;
}
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.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;
if (opt.queue == null || opt.queue === true) {
opt.queue = "fx";
}
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.easing = {
linear: function(p) {
return p;
},
swing: function(p) {
return 0.5 - Math.cos(p * Math.PI) / 2;
}
};
jQuery.timers = [];
jQuery.fx = Tween.prototype.init;
jQuery.fx.tick = function() {
var timer, timers = jQuery.timers,
i = 0;
for (; i < timers.length; i++) {
timer = timers[i];
if (!timer() && timers[i] === timer) {
timers.splice(i--, 1);
}
}
if (!timers.length) {
jQuery.fx.stop();
}
};
jQuery.fx.timer = function(timer) {
if (timer() && jQuery.timers.push(timer) && !timerId) {
timerId = setInterval(jQuery.fx.tick, jQuery.fx.interval);
}
};
jQuery.fx.interval = 13;
jQuery.fx.stop = function() {
clearInterval(timerId);
timerId = null;
};
jQuery.fx.speeds = {
slow: 600,
fast: 200,
_default: 400
};
jQuery.fx.step = {};
if (jQuery.expr && jQuery.expr.filters) {
jQuery.expr.filters.animated = function(elem) {
return jQuery.grep(jQuery.timers, function(fn) {
return elem === fn.elem;
})
.length;
};
}
var rroot = /^(?:body|html)$/i;
jQuery.fn.offset = function(options) {
if (arguments.length) {
return options === undefined ? this : this.each(function(i) {
jQuery.offset.setOffset(this, options, i);
});
}
var docElem, body, win, clientTop, clientLeft, scrollTop, scrollLeft, box = {
top: 0,
left: 0
}, elem = this[0],
doc = elem && elem.ownerDocument;
if (!doc) {
return;
}
if ((body = doc.body) === elem) {
return jQuery.offset.bodyOffset(elem);
}
docElem = doc.documentElement;
if (!jQuery.contains(docElem, elem)) {
return box;
}
if (typeof elem.getBoundingClientRect !== "undefined") {
box = elem.getBoundingClientRect();
}
win = getWindow(doc);
clientTop = docElem.clientTop || body.clientTop || 0;
clientLeft = docElem.clientLeft || body.clientLeft || 0;
scrollTop = win.pageYOffset || docElem.scrollTop;
scrollLeft = win.pageXOffset || docElem.scrollLeft;
return {
top: box.top + scrollTop - clientTop,
left: box.left + scrollLeft - clientLeft
};
};
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");
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;
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;
}
var elem = this[0],
offsetParent = this.offsetParent(),
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? {
top: 0,
left: 0
} : offsetParent.offset();
offset.top -= parseFloat(jQuery.css(elem, "marginTop")) || 0;
offset.left -= parseFloat(jQuery.css(elem, "marginLeft")) || 0;
parentOffset.top += parseFloat(jQuery.css(offsetParent[0], "borderTopWidth")) || 0;
parentOffset.left += parseFloat(jQuery.css(offsetParent[0], "borderLeftWidth")) || 0;
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 || document.body;
});
}
});
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] : win.document.documentElement[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;
}
jQuery.each({
Height: "height",
Width: "width"
}, function(name, type) {
jQuery.each({
padding: "inner" + name,
content: type,
"": "outer" + name
}, function(defaultExtra, funcName) {
jQuery.fn[funcName] = function(margin, value) {
var chainable = arguments.length && (defaultExtra || typeof margin !== "boolean"),
extra = defaultExtra || (margin === true || value === true ? "margin" : "border");
return jQuery.access(this, function(elem, type, value) {
var doc;
if (jQuery.isWindow(elem)) {
return elem.document.documentElement["client" + name];
}
if (elem.nodeType === 9) {
doc = elem.documentElement;
return Math.max(elem.body["scroll" + name], doc["scroll" + name], elem.body["offset" + name], doc["offset" + name], doc["client" + name]);
}
return value === undefined ? jQuery.css(elem, type, value, extra) : jQuery.style(elem, type, value, extra);
}, type, chainable ? margin : undefined, chainable, null);
};
});
});
window.jQuery = window.$ = jQuery;
if (typeof define === "function" && define.amd && define.amd.jQuery) {
define("jquery", [], function() {
return jQuery;
});
}
})(window);
(function() {
var root = this;
var previousUnderscore = root._;
var breaker = {};
var ArrayProto = Array.prototype,
ObjProto = Object.prototype,
FuncProto = Function.prototype;
var push = ArrayProto.push,
slice = ArrayProto.slice,
concat = ArrayProto.concat,
unshift = ArrayProto.unshift,
toString = ObjProto.toString,
hasOwnProperty = ObjProto.hasOwnProperty;
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;
var _ = function(obj) {
if (obj instanceof _) return obj;
if (!(this instanceof _)) return new _(obj);
this._wrapped = obj;
};
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root['_'] = _;
}
_.VERSION = '1.4.2';
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 (iterator.call(context, obj[i], i, obj) === breaker) return;
}
} else {
for (var key in obj) {
if (_.has(obj, key)) {
if (iterator.call(context, obj[key], key, obj) === breaker) return;
}
}
}
};
_.map = _.collect = 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 = _.foldl = _.inject = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
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;
};
_.reduceRight = _.foldr = function(obj, iterator, memo, context) {
var initial = arguments.length > 2;
if (obj == null) obj = [];
if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
if (context) iterator = _.bind(iterator, context);
return arguments.length > 2 ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
}
var length = obj.length;
if (length !== +length) {
var keys = _.keys(obj);
length = keys.length;
}
each(obj, function(value, index, list) {
index = keys ? keys[--length] : --length;
if (!initial) {
memo = obj[index];
initial = true;
} else {
memo = iterator.call(context, memo, obj[index], index, list);
}
});
if (!initial) throw new TypeError('Reduce of empty array with no initial value');
return memo;
};
_.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;
};
_.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;
};
_.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;
};
_.every = _.all = function(obj, iterator, context) {
iterator || (iterator = _.identity);
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;
};
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 || (result = iterator.call(context, value, index, list))) return breaker;
});
return !!result;
};
_.contains = _.include = function(obj, target) {
var found = false;
if (obj == null) return found;
if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
found = any(obj, function(value) {
return value === target;
});
return found;
};
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
return _.map(obj, function(value) {
return (_.isFunction(method) ? method : value[method])
.apply(value, args);
});
};
_.pluck = function(obj, key) {
return _.map(obj, function(value) {
return value[key];
});
};
_.where = function(obj, attrs) {
if (_.isEmpty(attrs)) return [];
return _.filter(obj, function(value) {
for (var key in attrs) {
if (attrs[key] !== value[key]) return false;
}
return true;
});
};
_.max = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.max.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return -Infinity;
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;
};
_.min = function(obj, iterator, context) {
if (!iterator && _.isArray(obj) && obj[0] === +obj[0] && obj.length < 65535) {
return Math.min.apply(Math, obj);
}
if (!iterator && _.isEmpty(obj)) return Infinity;
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;
};
_.shuffle = function(obj) {
var rand;
var index = 0;
var shuffled = [];
each(obj, function(value) {
rand = _.random(index++);
shuffled[index - 1] = shuffled[rand];
shuffled[rand] = value;
});
return shuffled;
};
var lookupIterator = function(value) {
return _.isFunction(value) ? value : function(obj) {
return obj[value];
};
};
_.sortBy = function(obj, value, context) {
var iterator = lookupIterator(value);
return _.pluck(_.map(obj, function(value, index, list) {
return {
value: value,
index: index,
criteria: iterator.call(context, value, index, list)
};
})
.sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index < right.index ? -1 : 1;
}), 'value');
};
var group = function(obj, value, context, behavior) {
var result = {};
var iterator = lookupIterator(value);
each(obj, function(value, index) {
var key = iterator.call(context, value, index, obj);
behavior(result, key, value);
});
return result;
};
_.groupBy = function(obj, value, context) {
return group(obj, value, context, function(result, key, value) {
(_.has(result, key) ? result[key] : (result[key] = []))
.push(value);
});
};
_.countBy = function(obj, value, context) {
return group(obj, value, context, function(result, key, value) {
if (!_.has(result, key)) result[key] = 0;
result[key]++;
});
};
_.sortedIndex = function(array, obj, iterator, context) {
iterator = iterator == null ? _.identity : lookupIterator(iterator);
var value = iterator.call(context, obj);
var low = 0,
high = array.length;
while (low < high) {
var mid = (low + high) >>> 1;
iterator.call(context, array[mid]) < value ? low = mid + 1 : high = mid;
}
return low;
};
_.toArray = function(obj) {
if (!obj) return [];
if (obj.length === +obj.length) return slice.call(obj);
return _.values(obj);
};
_.size = function(obj) {
return (obj.length === +obj.length) ? obj.length : _.keys(obj)
.length;
};
_.first = _.head = _.take = function(array, n, guard) {
return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
};
_.initial = function(array, n, guard) {
return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
};
_.last = function(array, n, guard) {
if ((n != null) && !guard) {
return slice.call(array, Math.max(array.length - n, 0));
} else {
return array[array.length - 1];
}
};
_.rest = _.tail = _.drop = function(array, n, guard) {
return slice.call(array, (n == null) || guard ? 1 : n);
};
_.compact = function(array) {
return _.filter(array, function(value) {
return !!value;
});
};
var flatten = function(input, shallow, output) {
each(input, function(value) {
if (_.isArray(value)) {
shallow ? push.apply(output, value) : flatten(value, shallow, output);
} else {
output.push(value);
}
});
return output;
};
_.flatten = function(array, shallow) {
return flatten(array, shallow, []);
};
_.without = function(array) {
return _.difference(array, slice.call(arguments, 1));
};
_.uniq = _.unique = function(array, isSorted, iterator, context) {
var initial = iterator ? _.map(array, iterator, context) : array;
var results = [];
var seen = [];
each(initial, function(value, index) {
if (isSorted ? (!index || seen[seen.length - 1] !== value) : !_.contains(seen, value)) {
seen.push(value);
results.push(array[index]);
}
});
return results;
};
_.union = function() {
return _.uniq(concat.apply(ArrayProto, arguments));
};
_.intersection = function(array) {
var rest = slice.call(arguments, 1);
return _.filter(_.uniq(array), function(item) {
return _.every(rest, function(other) {
return _.indexOf(other, item) >= 0;
});
});
};
_.difference = function(array) {
var rest = concat.apply(ArrayProto, slice.call(arguments, 1));
return _.filter(array, function(value) {
return !_.contains(rest, value);
});
};
_.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;
};
_.object = function(list, values) {
var result = {};
for (var i = 0, l = list.length; i < l; i++) {
if (values) {
result[list[i]] = values[i];
} else {
result[list[i][0]] = list[i][1];
}
}
return result;
};
_.indexOf = function(array, item, isSorted) {
if (array == null) return -1;
var i = 0,
l = array.length;
if (isSorted) {
if (typeof isSorted == 'number') {
i = (isSorted < 0 ? Math.max(0, l + isSorted) : isSorted);
} else {
i = _.sortedIndex(array, item);
return array[i] === item ? i : -1;
}
}
if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item, isSorted);
for (; i < l; i++) if (array[i] === item) return i;
return -1;
};
_.lastIndexOf = function(array, item, from) {
if (array == null) return -1;
var hasIndex = from != null;
if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) {
return hasIndex ? array.lastIndexOf(item, from) : array.lastIndexOf(item);
}
var i = (hasIndex ? from : array.length);
while (i--) if (array[i] === item) return i;
return -1;
};
_.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;
};
var ctor = function() {};
_.bind = function bind(func, context) {
var bound, args;
if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
if (!_.isFunction(func)) throw new TypeError;
args = slice.call(arguments, 2);
return bound = function() {
if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
ctor.prototype = func.prototype;
var self = new ctor;
var result = func.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) return result;
return self;
};
};
_.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 = function(func, hasher) {
var memo = {};
hasher || (hasher = _.identity);
return function() {
var key = hasher.apply(this, arguments);
return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
};
};
_.delay = function(func, wait) {
var args = slice.call(arguments, 2);
return setTimeout(function() {
return func.apply(null, args);
}, wait);
};
_.defer = function(func) {
return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
};
_.throttle = function(func, wait) {
var context, args, timeout, throttling, more, result;
var whenDone = _.debounce(function() {
more = throttling = false;
}, wait);
return function() {
context = this;
args = arguments;
var later = function() {
timeout = null;
if (more) {
result = func.apply(context, args);
}
whenDone();
};
if (!timeout) timeout = setTimeout(later, wait);
if (throttling) {
more = true;
} else {
throttling = true;
result = func.apply(context, args);
}
whenDone();
return result;
};
};
_.debounce = function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this,
args = arguments;
var later = function() {
timeout = null;
if (!immediate) result = func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) result = func.apply(context, args);
return result;
};
};
_.once = function(func) {
var ran = false,
memo;
return function() {
if (ran) return memo;
ran = true;
memo = func.apply(this, arguments);
func = null;
return memo;
};
};
_.wrap = function(func, wrapper) {
return function() {
var args = [func];
push.apply(args, arguments);
return wrapper.apply(this, args);
};
};
_.compose = function() {
var funcs = arguments;
return function() {
var args = arguments;
for (var i = funcs.length - 1; i >= 0; i--) {
args = [funcs[i].apply(this, args)];
}
return args[0];
};
};
_.after = function(times, func) {
if (times <= 0) return func();
return function() {
if (--times < 1) {
return func.apply(this, arguments);
}
};
};
_.keys = nativeKeys || function(obj) {
if (obj !== Object(obj)) throw new TypeError('Invalid object');
var keys = [];
for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
return keys;
};
_.values = function(obj) {
var values = [];
for (var key in obj) if (_.has(obj, key)) values.push(obj[key]);
return values;
};
_.pairs = function(obj) {
var pairs = [];
for (var key in obj) if (_.has(obj, key)) pairs.push([key, obj[key]]);
return pairs;
};
_.invert = function(obj) {
var result = {};
for (var key in obj) if (_.has(obj, key)) result[obj[key]] = key;
return result;
};
_.functions = _.methods = function(obj) {
var names = [];
for (var key in obj) {
if (_.isFunction(obj[key])) names.push(key);
}
return names.sort();
};
_.extend = function(obj) {
each(slice.call(arguments, 1), function(source) {
for (var prop in source) {
obj[prop] = source[prop];
}
});
return obj;
};
_.pick = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
each(keys, function(key) {
if (key in obj) copy[key] = obj[key];
});
return copy;
};
_.omit = function(obj) {
var copy = {};
var keys = concat.apply(ArrayProto, slice.call(arguments, 1));
for (var key in obj) {
if (!_.contains(keys, key)) copy[key] = obj[key];
}
return copy;
};
_.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;
};
_.clone = function(obj) {
if (!_.isObject(obj)) return obj;
return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
};
_.tap = function(obj, interceptor) {
interceptor(obj);
return obj;
};
var eq = function(a, b, aStack, bStack) {
if (a === b) return a !== 0 || 1 / a == 1 / b;
if (a == null || b == null) return a === b;
if (a instanceof _) a = a._wrapped;
if (b instanceof _) b = b._wrapped;
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
case '[object String]':
return a == String(b);
case '[object Number]':
return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
case '[object Date]':
case '[object Boolean]':
return +a == +b;
case '[object RegExp]':
return a.source == b.source && a.global == b.global && a.multiline == b.multiline && a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
var length = aStack.length;
while (length--) {
if (aStack[length] == a) return bStack[length] == b;
}
aStack.push(a);
bStack.push(b);
var size = 0,
result = true;
if (className == '[object Array]') {
size = a.length;
result = size == b.length;
if (result) {
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
var aCtor = a.constructor,
bCtor = b.constructor;
if (aCtor !== bCtor && !(_.isFunction(aCtor) && (aCtor instanceof aCtor) && _.isFunction(bCtor) && (bCtor instanceof bCtor))) {
return false;
}
for (var key in a) {
if (_.has(a, key)) {
size++;
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
aStack.pop();
bStack.pop();
return result;
};
_.isEqual = function(a, b) {
return eq(a, b, [], []);
};
_.isEmpty = function(obj) {
if (obj == null) return true;
if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
for (var key in obj) if (_.has(obj, key)) return false;
return true;
};
_.isElement = function(obj) {
return !!(obj && obj.nodeType === 1);
};
_.isArray = nativeIsArray || function(obj) {
return toString.call(obj) == '[object Array]';
};
_.isObject = function(obj) {
return obj === Object(obj);
};
each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp'], function(name) {
_['is' + name] = function(obj) {
return toString.call(obj) == '[object ' + name + ']';
};
});
if (!_.isArguments(arguments)) {
_.isArguments = function(obj) {
return !!(obj && _.has(obj, 'callee'));
};
}
if (typeof(/./) !== 'function') {
_.isFunction = function(obj) {
return typeof obj === 'function';
};
}
_.isFinite = function(obj) {
return _.isNumber(obj) && isFinite(obj);
};
_.isNaN = function(obj) {
return _.isNumber(obj) && obj != +obj;
};
_.isBoolean = function(obj) {
return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
};
_.isNull = function(obj) {
return obj === null;
};
_.isUndefined = function(obj) {
return obj === void 0;
};
_.has = function(obj, key) {
return hasOwnProperty.call(obj, key);
};
_.noConflict = function() {
root._ = previousUnderscore;
return this;
};
_.identity = function(value) {
return value;
};
_.times = function(n, iterator, context) {
for (var i = 0; i < n; i++) iterator.call(context, i);
};
_.random = function(min, max) {
if (max == null) {
max = min;
min = 0;
}
return min + (0 | Math.random() * (max - min + 1));
};
var entityMap = {
escape: {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": ''',
'/': '/'
}
};
entityMap.unescape = _.invert(entityMap.escape);
var entityRegexes = {
escape: new RegExp('[' + _.keys(entityMap.escape)
.join('') + ']', 'g'),
unescape: new RegExp('(' + _.keys(entityMap.unescape)
.join('|') + ')', 'g')
};
_.each(['escape', 'unescape'], function(method) {
_[method] = function(string) {
if (string == null) return '';
return ('' + string)
.replace(entityRegexes[method], function(match) {
return entityMap[method][match];
});
};
});
_.result = function(object, property) {
if (object == null) return null;
var value = object[property];
return _.isFunction(value) ? value.call(object) : value;
};
_.mixin = function(obj) {
each(_.functions(obj), function(name) {
var func = _[name] = obj[name];
_.prototype[name] = function() {
var args = [this._wrapped];
push.apply(args, arguments);
return result.call(this, func.apply(_, args));
};
});
};
var idCounter = 0;
_.uniqueId = function(prefix) {
var id = idCounter++;
return prefix ? prefix + id : id;
};
_.templateSettings = {
evaluate: /<%([\s\S]+?)%>/g,
interpolate: /<%=([\s\S]+?)%>/g,
escape: /<%-([\s\S]+?)%>/g
};
var noMatch = /(.)^/;
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
_.template = function(text, data, settings) {
settings = _.defaults({}, settings, _.templateSettings);
var matcher = new RegExp([(settings.escape || noMatch)
.source, (settings.interpolate || noMatch)
.source, (settings.evaluate || noMatch)
.source].join('|') + '|$', 'g');
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) {
return '\\' + escapes[match];
});
source += escape ? "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'" : interpolate ? "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'" : evaluate ? "';\n" + evaluate + "\n__p+='" : '';
index = offset + match.length;
});
source += "';\n";
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + "return __p;\n";
try {
var render = new Function(settings.variable || 'obj', '_', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, _);
var template = function(data) {
return render.call(this, data, _);
};
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
_.chain = function(obj) {
return _(obj)
.chain();
};
var result = function(obj) {
return this._chain ? _(obj)
.chain() : obj;
};
_.mixin(_);
each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
var obj = this._wrapped;
method.apply(obj, arguments);
if ((name == 'shift' || name == 'splice') && obj.length === 0) delete obj[0];
return result.call(this, obj);
};
});
each(['concat', 'join', 'slice'], function(name) {
var method = ArrayProto[name];
_.prototype[name] = function() {
return result.call(this, method.apply(this._wrapped, arguments));
};
});
_.extend(_.prototype, {
chain: function() {
this._chain = true;
return this;
},
value: function() {
return this._wrapped;
}
});
})
.call(this);
(function() {
var root = this;
var previousBackbone = root.Backbone;
var slice = Array.prototype.slice;
var splice = Array.prototype.splice;
var Backbone;
if (typeof exports !== 'undefined') {
Backbone = exports;
} else {
Backbone = root.Backbone = {};
}
Backbone.VERSION = '0.9.2';
var _ = root._;
if (!_ && (typeof require !== 'undefined')) _ = require('underscore');
var $ = root.jQuery || root.Zepto || root.ender;
Backbone.setDomLibrary = function(lib) {
$ = lib;
};
Backbone.noConflict = function() {
root.Backbone = previousBackbone;
return this;
};
Backbone.emulateHTTP = false;
Backbone.emulateJSON = false;
var eventSplitter = /\s+/;
var Events = Backbone.Events = {
on: function(events, callback, context) {
var calls, event, node, tail, list;
if (!callback) return this;
events = events.split(eventSplitter);
calls = this._callbacks || (this._callbacks = {});
while (event = events.shift()) {
list = calls[event];
node = list ? list.tail : {};
node.next = tail = {};
node.context = context;
node.callback = callback;
calls[event] = {
tail: tail,
next: list ? list.next : node
};
}
return this;
},
off: function(events, callback, context) {
var event, calls, node, tail, cb, ctx;
if (!(calls = this._callbacks)) return;
if (!(events || callback || context)) {
delete this._callbacks;
return this;
}
events = events ? events.split(eventSplitter) : _.keys(calls);
while (event = events.shift()) {
node = calls[event];
delete calls[event];
if (!node || !(callback || context)) continue;
tail = node.tail;
while ((node = node.next) !== tail) {
cb = node.callback;
ctx = node.context;
if ((callback && cb !== callback) || (context && ctx !== context)) {
this.on(event, cb, ctx);
}
}
}
return this;
},
trigger: function(events) {
var event, node, calls, tail, args, all, rest;
if (!(calls = this._callbacks)) return this;
all = calls.all;
events = events.split(eventSplitter);
rest = slice.call(arguments, 1);
while (event = events.shift()) {
if (node = calls[event]) {
tail = node.tail;
while ((node = node.next) !== tail) {
node.callback.apply(node.context || this, rest);
}
}
if (node = all) {
tail = node.tail;
args = [event].concat(rest);
while ((node = node.next) !== tail) {
node.callback.apply(node.context || this, args);
}
}
}
return this;
}
};
Events.bind = Events.on;
Events.unbind = Events.off;
var Model = Backbone.Model = function(attributes, options) {
var defaults;
attributes || (attributes = {});
if (options && options.parse) attributes = this.parse(attributes);
if (defaults = getValue(this, 'defaults')) {
attributes = _.extend({}, defaults, attributes);
}
if (options && options.collection) this.collection = options.collection;
this.attributes = {};
this._escapedAttributes = {};
this.cid = _.uniqueId('c');
this.changed = {};
this._silent = {};
this._pending = {};
this.set(attributes, {
silent: true
});
this.changed = {};
this._silent = {};
this._pending = {};
this._previousAttributes = _.clone(this.attributes);
this.initialize.apply(this, arguments);
};
_.extend(Model.prototype, Events, {
changed: null,
_silent: null,
_pending: null,
idAttribute: 'id',
initialize: function() {},
toJSON: function(options) {
return _.clone(this.attributes);
},
get: function(attr) {
return this.attributes[attr];
},
escape: function(attr) {
var html;
if (html = this._escapedAttributes[attr]) return html;
var val = this.get(attr);
return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val);
},
has: function(attr) {
return this.get(attr) != null;
},
set: function(key, value, options) {
var attrs, attr, val;
if (_.isObject(key) || key == null) {
attrs = key;
options = value;
} else {
attrs = {};
attrs[key] = value;
}
options || (options = {});
if (!attrs) return this;
if (attrs instanceof Model) attrs = attrs.attributes;
if (options.unset) for (attr in attrs) attrs[attr] = void 0;
if (!this._validate(attrs, options)) return false;
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
var changes = options.changes = {};
var now = this.attributes;
var escaped = this._escapedAttributes;
var prev = this._previousAttributes || {};
for (attr in attrs) {
val = attrs[attr];
if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) {
delete escaped[attr];
(options.silent ? this._silent : changes)[attr] = true;
}
options.unset ? delete now[attr] : now[attr] = val;
if (!_.isEqual(prev[attr], val) || (_.has(now, attr) != _.has(prev, attr))) {
this.changed[attr] = val;
if (!options.silent) this._pending[attr] = true;
} else {
delete this.changed[attr];
delete this._pending[attr];
}
}
if (!options.silent) this.change(options);
return this;
},
unset: function(attr, options) {
(options || (options = {}))
.unset = true;
return this.set(attr, null, options);
},
clear: function(options) {
(options || (options = {}))
.unset = true;
return this.set(_.clone(this.attributes), options);
},
fetch: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
options.success = function(resp, status, xhr) {
if (!model.set(model.parse(resp, xhr), options)) return false;
if (success) success(model, resp);
};
options.error = Backbone.wrapError(options.error, model, options);
return (this.sync || Backbone.sync)
.call(this, 'read', this, options);
},
save: function(key, value, options) {
var attrs, current;
if (_.isObject(key) || key == null) {
attrs = key;
options = value;
} else {
attrs = {};
attrs[key] = value;
}
options = options ? _.clone(options) : {};
if (options.wait) {
if (!this._validate(attrs, options)) return false;
current = _.clone(this.attributes);
}
var silentOptions = _.extend({}, options, {
silent: true
});
if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) {
return false;
}
var model = this;
var success = options.success;
options.success = function(resp, status, xhr) {
var serverAttrs = model.parse(resp, xhr);
if (options.wait) {
delete options.wait;
serverAttrs = _.extend(attrs || {}, serverAttrs);
}
if (!model.set(serverAttrs, options)) return false;
if (success) {
success(model, resp);
} else {
model.trigger('sync', model, resp, options);
}
};
options.error = Backbone.wrapError(options.error, model, options);
var method = this.isNew() ? 'create' : 'update';
var xhr = (this.sync || Backbone.sync)
.call(this, method, this, options);
if (options.wait) this.set(current, silentOptions);
return xhr;
},
destroy: function(options) {
options = options ? _.clone(options) : {};
var model = this;
var success = options.success;
var triggerDestroy = function() {
model.trigger('destroy', model, model.collection, options);
};
if (this.isNew()) {
triggerDestroy();
return false;
}
options.success = function(resp) {
if (options.wait) triggerDestroy();
if (success) {
success(model, resp);
} else {
model.trigger('sync', model, resp, options);
}
};
options.error = Backbone.wrapError(options.error, model, options);
var xhr = (this.sync || Backbone.sync)
.call(this, 'delete', this, options);
if (!options.wait) triggerDestroy();
return xhr;
},
url: function() {
var base = getValue(this, 'urlRoot') || getValue(this.collection, 'url') || urlError();
if (this.isNew()) return base;
return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id);
},
parse: function(resp, xhr) {
return resp;
},
clone: function() {
return new this.constructor(this.attributes);
},
isNew: function() {
return this.id == null;
},
change: function(options) {
options || (options = {});
var changing = this._changing;
this._changing = true;
for (var attr in this._silent) this._pending[attr] = true;
var changes = _.extend({}, options.changes, this._silent);
this._silent = {};
for (var attr in changes) {
this.trigger('change:' + attr, this, this.get(attr), options);
}
if (changing) return this;
while (!_.isEmpty(this._pending)) {
this._pending = {};
this.trigger('change', this, options);
for (var attr in this.changed) {
if (this._pending[attr] || this._silent[attr]) continue;
delete this.changed[attr];
}
this._previousAttributes = _.clone(this.attributes);
}
this._changing = false;
return this;
},
hasChanged: function(attr) {
if (!arguments.length) return !_.isEmpty(this.changed);
return _.has(this.changed, attr);
},
changedAttributes: function(diff) {
if (!diff) return this.hasChanged() ? _.clone(this.changed) : false;
var val, changed = false,
old = this._previousAttributes;
for (var attr in diff) {
if (_.isEqual(old[attr], (val = diff[attr]))) continue;
(changed || (changed = {}))[attr] = val;
}
return changed;
},
previous: function(attr) {
if (!arguments.length || !this._previousAttributes) return null;
return this._previousAttributes[attr];
},
previousAttributes: function() {
return _.clone(this._previousAttributes);
},
isValid: function() {
return !this.validate(this.attributes);
},
_validate: function(attrs, options) {
if (options.silent || !this.validate) return true;
attrs = _.extend({}, this.attributes, attrs);
var error = this.validate(attrs, options);
if (!error) return true;
if (options && options.error) {
options.error(this, error, options);
} else {
this.trigger('error', this, error, options);
}
return false;
}
});
var Collection = Backbone.Collection = function(models, options) {
options || (options = {});
if (options.model) this.model = options.model;
if (options.comparator) this.comparator = options.comparator;
this._reset();
this.initialize.apply(this, arguments);
if (models) this.reset(models, {
silent: true,
parse: options.parse
});
};
_.extend(Collection.prototype, Events, {
model: Model,
initialize: function() {},
toJSON: function(options) {
return this.map(function(model) {
return model.toJSON(options);
});
},
add: function(models, options) {
var i, index, length, model, cid, id, cids = {}, ids = {}, dups = [];
options || (options = {});
models = _.isArray(models) ? models.slice() : [models];
for (i = 0, length = models.length; i < length; i++) {
if (!(model = models[i] = this._prepareModel(models[i], options))) {
throw new Error("Can't add an invalid model to a collection");
}
cid = model.cid;
id = model.id;
if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) {
dups.push(i);
continue;
}
cids[cid] = ids[id] = model;
}
i = dups.length;
while (i--) {
models.splice(dups[i], 1);
}
for (i = 0, length = models.length; i < length; i++) {
(model = models[i])
.on('all', this._onModelEvent, this);
this._byCid[model.cid] = model;
if (model.id != null) this._byId[model.id] = model;
}
this.length += length;
index = options.at != null ? options.at : this.models.length;
splice.apply(this.models, [index, 0].concat(models));
if (this.comparator) this.sort({
silent: true
});
if (options.silent) return this;
for (i = 0, length = this.models.length; i < length; i++) {
if (!cids[(model = this.models[i])
.cid]) continue;
options.index = i;
model.trigger('add', model, this, options);
}
return this;
},
remove: function(models, options) {
var i, l, index, model;
options || (options = {});
models = _.isArray(models) ? models.slice() : [models];
for (i = 0, l = models.length; i < l; i++) {
model = this.getByCid(models[i]) || this.get(models[i]);
if (!model) continue;
delete this._byId[model.id];
delete this._byCid[model.cid];
index = this.indexOf(model);
this.models.splice(index, 1);
this.length--;
if (!options.silent) {
options.index = index;
model.trigger('remove', model, this, options);
}
this._removeReference(model);
}
return this;
},
push: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, options);
return model;
},
pop: function(options) {
var model = this.at(this.length - 1);
this.remove(model, options);
return model;
},
unshift: function(model, options) {
model = this._prepareModel(model, options);
this.add(model, _.extend({
at: 0
}, options));
return model;
},
shift: function(options) {
var model = this.at(0);
this.remove(model, options);
return model;
},
get: function(id) {
if (id == null) return void 0;
return this._byId[id.id != null ? id.id : id];
},
getByCid: function(cid) {
return cid && this._byCid[cid.cid || cid];
},
at: function(index) {
return this.models[index];
},
where: function(attrs) {
if (_.isEmpty(attrs)) return [];
return this.filter(function(model) {
for (var key in attrs) {
if (attrs[key] !== model.get(key)) return false;
}
return true;
});
},
sort: function(options) {
options || (options = {});
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
var boundComparator = _.bind(this.comparator, this);
if (this.comparator.length == 1) {
this.models = this.sortBy(boundComparator);
} else {
this.models.sort(boundComparator);
}
if (!options.silent) this.trigger('reset', this, options);
return this;
},
pluck: function(attr) {
return _.map(this.models, function(model) {
return model.get(attr);
});
},
reset: function(models, options) {
models || (models = []);
options || (options = {});
for (var i = 0, l = this.models.length; i < l; i++) {
this._removeReference(this.models[i]);
}
this._reset();
this.add(models, _.extend({
silent: true
}, options));
if (!options.silent) this.trigger('reset', this, options);
return this;
},
fetch: function(options) {
options = options ? _.clone(options) : {};
if (options.parse === undefined) options.parse = true;
var collection = this;
var success = options.success;
options.success = function(resp, status, xhr) {
collection[options.add ? 'add' : 'reset'](collection.parse(resp, xhr), options);
if (success) success(collection, resp);
};
options.error = Backbone.wrapError(options.error, collection, options);
return (this.sync || Backbone.sync)
.call(this, 'read', this, options);
},
create: function(model, options) {
var coll = this;
options = options ? _.clone(options) : {};
model = this._prepareModel(model, options);
if (!model) return false;
if (!options.wait) coll.add(model, options);
var success = options.success;
options.success = function(nextModel, resp, xhr) {
if (options.wait) coll.add(nextModel, options);
if (success) {
success(nextModel, resp);
} else {
nextModel.trigger('sync', model, resp, options);
}
};
model.save(null, options);
return model;
},
parse: function(resp, xhr) {
return resp;
},
chain: function() {
return _(this.models)
.chain();
},
_reset: function(options) {
this.length = 0;
this.models = [];
this._byId = {};
this._byCid = {};
},
_prepareModel: function(model, options) {
options || (options = {});
if (!(model instanceof Model)) {
var attrs = model;
options.collection = this;
model = new this.model(attrs, options);
if (!model._validate(model.attributes, options)) model = false;
} else if (!model.collection) {
model.collection = this;
}
return model;
},
_removeReference: function(model) {
if (this == model.collection) {
delete model.collection;
}
model.off('all', this._onModelEvent, this);
},
_onModelEvent: function(event, model, collection, options) {
if ((event == 'add' || event == 'remove') && collection != this) return;
if (event == 'destroy') {
this.remove(model, options);
}
if (model && event === 'change:' + model.idAttribute) {
delete this._byId[model.previous(model.idAttribute)];
this._byId[model.id] = model;
}
this.trigger.apply(this, arguments);
}
});
var methods = ['forEach', 'each', 'map', 'reduce', 'reduceRight', 'find', 'detect', 'filter', 'select', 'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke', 'max', 'min', 'sortBy', 'sortedIndex', 'toArray', 'size', 'first', 'initial', 'rest', 'last', 'without', 'indexOf', 'shuffle', 'lastIndexOf', 'isEmpty', 'groupBy'];
_.each(methods, function(method) {
Collection.prototype[method] = function() {
return _[method].apply(_, [this.models].concat(_.toArray(arguments)));
};
});
var Router = Backbone.Router = function(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
};
var namedParam = /:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g;
_.extend(Router.prototype, Events, {
initialize: function() {},
route: function(route, name, callback) {
Backbone.history || (Backbone.history = new History);
if (!_.isRegExp(route)) route = this._routeToRegExp(route);
if (!callback) callback = this[name];
Backbone.history.route(route, _.bind(function(fragment) {
var args = this._extractParameters(route, fragment);
callback && callback.apply(this, args);
this.trigger.apply(this, ['route:' + name].concat(args));
Backbone.history.trigger('route', this, name, args);
}, this));
return this;
},
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
},
_bindRoutes: function() {
if (!this.routes) return;
var routes = [];
for (var route in this.routes) {
routes.unshift([route, this.routes[route]]);
}
for (var i = 0, l = routes.length; i < l; i++) {
this.route(routes[i][0], routes[i][1], this[routes[i][1]]);
}
},
_routeToRegExp: function(route) {
route = route.replace(escapeRegExp, '\\$&')
.replace(namedParam, '([^\/]+)')
.replace(splatParam, '(.*?)');
return new RegExp('^' + route + '$');
},
_extractParameters: function(route, fragment) {
return route.exec(fragment)
.slice(1);
}
});
var History = Backbone.History = function() {
this.handlers = [];
_.bindAll(this, 'checkUrl');
};
var routeStripper = /^[#\/]/;
var isExplorer = /msie [\w.]+/;
History.started = false;
_.extend(History.prototype, Events, {
interval: 50,
getHash: function(windowOverride) {
var loc = windowOverride ? windowOverride.location : window.location;
var match = loc.href.match(/#(.*)$/);
return match ? match[1] : '';
},
getFragment: function(fragment, forcePushState) {
if (fragment == null) {
if (this._hasPushState || forcePushState) {
fragment = window.location.pathname;
var search = window.location.search;
if (search) fragment += search;
} else {
fragment = this.getHash();
}
}
if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length);
return fragment.replace(routeStripper, '');
},
start: function(options) {
if (History.started) throw new Error("Backbone.history has already been started");
History.started = true;
this.options = _.extend({}, {
root: '/'
}, this.options, options);
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState = !! this.options.pushState;
this._hasPushState = !! (this.options.pushState && window.history && window.history.pushState);
var fragment = this.getFragment();
var docMode = document.documentMode;
var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7));
if (oldIE) {
this.iframe = $('<iframe src="javascript:0" tabindex="-1" />')
.hide()
.appendTo('body')[0].contentWindow;
this.navigate(fragment);
}
if (this._hasPushState) {
$(window)
.bind('popstate', this.checkUrl);
} else if (this._wantsHashChange && ('onhashchange' in window) && !oldIE) {
$(window)
.bind('hashchange', this.checkUrl);
} else if (this._wantsHashChange) {
this._checkUrlInterval = setInterval(this.checkUrl, this.interval);
}
this.fragment = fragment;
var loc = window.location;
var atRoot = loc.pathname == this.options.root;
if (this._wantsHashChange && this._wantsPushState && !this._hasPushState && !atRoot) {
this.fragment = this.getFragment(null, true);
window.location.replace(this.options.root + '#' + this.fragment);
return true;
} else if (this._wantsPushState && this._hasPushState && atRoot && loc.hash) {
this.fragment = this.getHash()
.replace(routeStripper, '');
window.history.replaceState({}, document.title, loc.protocol + '//' + loc.host + this.options.root + this.fragment);
}
if (!this.options.silent) {
return this.loadUrl();
}
},
stop: function() {
$(window)
.unbind('popstate', this.checkUrl)
.unbind('hashchange', this.checkUrl);
clearInterval(this._checkUrlInterval);
History.started = false;
},
route: function(route, callback) {
this.handlers.unshift({
route: route,
callback: callback
});
},
checkUrl: function(e) {
var current = this.getFragment();
if (current == this.fragment && this.iframe) current = this.getFragment(this.getHash(this.iframe));
if (current == this.fragment) return false;
if (this.iframe) this.navigate(current);
this.loadUrl() || this.loadUrl(this.getHash());
},
loadUrl: function(fragmentOverride) {
var fragment = this.fragment = this.getFragment(fragmentOverride);
var matched = _.any(this.handlers, function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
return matched;
},
navigate: function(fragment, options) {
if (!History.started) return false;
if (!options || options === true) options = {
trigger: options
};
var frag = (fragment || '')
.replace(routeStripper, '');
if (this.fragment == frag) return;
if (this._hasPushState) {
if (frag.indexOf(this.options.root) != 0) frag = this.options.root + frag;
this.fragment = frag;
window.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, frag);
} else if (this._wantsHashChange) {
this.fragment = frag;
this._updateHash(window.location, frag, options.replace);
if (this.iframe && (frag != this.getFragment(this.getHash(this.iframe)))) {
if (!options.replace) this.iframe.document.open()
.close();
this._updateHash(this.iframe.location, frag, options.replace);
}
} else {
window.location.assign(this.options.root + fragment);
}
if (options.trigger) this.loadUrl(fragment);
},
_updateHash: function(location, fragment, replace) {
if (replace) {
location.replace(location.toString()
.replace(/(javascript:|#).*$/, '') + '#' + fragment);
} else {
location.hash = fragment;
}
}
});
var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
this._configure(options || {});
this._ensureElement();
this.initialize.apply(this, arguments);
this.delegateEvents();
};
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName'];
_.extend(View.prototype, Events, {
tagName: 'div',
$: function(selector) {
return this.$el.find(selector);
},
initialize: function() {},
render: function() {
return this;
},
remove: function() {
this.$el.remove();
return this;
},
make: function(tagName, attributes, content) {
var el = document.createElement(tagName);
if (attributes) $(el)
.attr(attributes);
if (content) $(el)
.html(content);
return el;
},
setElement: function(element, delegate) {
if (this.$el) this.undelegateEvents();
this.$el = (element instanceof $) ? element : $(element);
this.el = this.$el[0];
if (delegate !== false) this.delegateEvents();
return this;
},
delegateEvents: function(events) {
if (!(events || (events = getValue(this, 'events')))) return;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (!_.isFunction(method)) method = this[events[key]];
if (!method) throw new Error('Method "' + events[key] + '" does not exist');
var match = key.match(delegateEventSplitter);
var eventName = match[1],
selector = match[2];
method = _.bind(method, this);
eventName += '.delegateEvents' + this.cid;
if (selector === '') {
this.$el.bind(eventName, method);
} else {
this.$el.delegate(selector, eventName, method);
}
}
},
undelegateEvents: function() {
this.$el.unbind('.delegateEvents' + this.cid);
},
_configure: function(options) {
if (this.options) options = _.extend({}, this.options, options);
for (var i = 0, l = viewOptions.length; i < l; i++) {
var attr = viewOptions[i];
if (options[attr]) this[attr] = options[attr];
}
this.options = options;
},
_ensureElement: function() {
if (!this.el) {
var attrs = getValue(this, 'attributes') || {};
if (this.id) attrs.id = this.id;
if (this.className) attrs['class'] = this.className;
this.setElement(this.make(this.tagName, attrs), false);
} else {
this.setElement(this.el, false);
}
}
});
var extend = function(protoProps, classProps) {
var child = inherits(this, protoProps, classProps);
child.extend = this.extend;
return child;
};
Model.extend = Collection.extend = Router.extend = View.extend = extend;
var methodMap = {
'create': 'POST',
'update': 'PUT',
'delete': 'DELETE',
'read': 'GET'
};
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
options || (options = {});
var params = {
type: type,
dataType: 'json'
};
if (!options.url) {
params.url = getValue(model, 'url') || urlError();
}
if (!options.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
if (Backbone.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.data = params.data ? {
model: params.data
} : {};
}
if (Backbone.emulateHTTP) {
if (type === 'PUT' || type === 'DELETE') {
if (Backbone.emulateJSON) params.data._method = type;
params.type = 'POST';
params.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
};
}
}
if (params.type !== 'GET' && !Backbone.emulateJSON) {
params.processData = false;
}
return $.ajax(_.extend(params, options));
};
Backbone.wrapError = function(onError, originalModel, options) {
return function(model, resp) {
resp = model === originalModel ? resp : model;
if (onError) {
onError(originalModel, resp, options);
} else {
originalModel.trigger('error', originalModel, resp, options);
}
};
};
var ctor = function() {};
var inherits = function(parent, protoProps, staticProps) {
var child;
if (protoProps && protoProps.hasOwnProperty('constructor')) {
child = protoProps.constructor;
} else {
child = function() {
parent.apply(this, arguments);
};
}
_.extend(child, parent);
ctor.prototype = parent.prototype;
child.prototype = new ctor();
if (protoProps) _.extend(child.prototype, protoProps);
if (staticProps) _.extend(child, staticProps);
child.prototype.constructor = child;
child.__super__ = parent.prototype;
return child;
};
var getValue = function(object, prop) {
if (!(object && object[prop])) return null;
return _.isFunction(object[prop]) ? object[prop]() : object[prop];
};
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
})
.call(this);
! function($) {
$(function() {
"use strict";
$.support.transition = (function() {
var transitionEnd = (function() {
var el = document.createElement('bootstrap'),
transEndEventNames = {
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'transitionend',
'OTransition': 'oTransitionEnd otransitionend',
'transition': 'transitionend'
}, name
for (name in transEndEventNames) {
if (el.style[name] !== undefined) {
return transEndEventNames[name]
}
}
}())
return transitionEnd && {
end: transitionEnd
}
})()
})
}(window.jQuery);
! function($) {
"use strict";
var dismiss = '[data-dismiss="alert"]',
Alert = function(el) {
$(el)
.on('click', dismiss, this.close)
}
Alert.prototype.close = function(e) {
var $this = $(this),
selector = $this.attr('data-target'),
$parent
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '')
}
$parent = $(selector)
e && e.preventDefault()
$parent.length || ($parent = $this.hasClass('alert') ? $this : $this.parent())
$parent.trigger(e = $.Event('close'))
if (e.isDefaultPrevented()) return
$parent.removeClass('in')
function removeElement() {
$parent.trigger('closed')
.remove()
}
$.support.transition && $parent.hasClass('fade') ? $parent.on($.support.transition.end, removeElement) : removeElement()
}
$.fn.alert = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('alert')
if (!data) $this.data('alert', (data = new Alert(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.alert.Constructor = Alert
$(function() {
$('body')
.on('click.alert.data-api', dismiss, Alert.prototype.close)
})
}(window.jQuery);
! function($) {
"use strict";
var Button = function(element, options) {
this.$element = $(element)
this.options = $.extend({}, $.fn.button.defaults, options)
}
Button.prototype.setState = function(state) {
var d = 'disabled',
$el = this.$element,
data = $el.data(),
val = $el.is('input') ? 'val' : 'html'
state = state + 'Text'
data.resetText || $el.data('resetText', $el[val]())
$el[val](data[state] || this.options[state])
setTimeout(function() {
state == 'loadingText' ? $el.addClass(d)
.attr(d, d) : $el.removeClass(d)
.removeAttr(d)
}, 0)
}
Button.prototype.toggle = function() {
var $parent = this.$element.parent('[data-toggle="buttons-radio"]')
$parent && $parent.find('.active')
.removeClass('active')
this.$element.toggleClass('active')
}
$.fn.button = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('button'),
options = typeof option == 'object' && option
if (!data) $this.data('button', (data = new Button(this, options)))
if (option == 'toggle') data.toggle()
else if (option) data.setState(option)
})
}
$.fn.button.defaults = {
loadingText: 'loading...'
}
$.fn.button.Constructor = Button
$(function() {
$('body')
.on('click.button.data-api', '[data-toggle^=button]', function(e) {
var $btn = $(e.target)
if (!$btn.hasClass('btn')) $btn = $btn.closest('.btn')
$btn.button('toggle')
})
})
}(window.jQuery);
! function($) {
"use strict";
var Carousel = function(element, options) {
this.$element = $(element)
this.options = options
this.options.slide && this.slide(this.options.slide)
this.options.pause == 'hover' && this.$element.on('mouseenter', $.proxy(this.pause, this))
.on('mouseleave', $.proxy(this.cycle, this))
}
Carousel.prototype = {
cycle: function(e) {
if (!e) this.paused = false
this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval))
return this
},
to: function(pos) {
var $active = this.$element.find('.item.active'),
children = $active.parent()
.children(),
activePos = children.index($active),
that = this
if (pos > (children.length - 1) || pos < 0) return
if (this.sliding) {
return this.$element.one('slid', function() {
that.to(pos)
})
}
if (activePos == pos) {
return this.pause()
.cycle()
}
return this.slide(pos > activePos ? 'next' : 'prev', $(children[pos]))
},
pause: function(e) {
if (!e) this.paused = true
if (this.$element.find('.next, .prev')
.length && $.support.transition.end) {
this.$element.trigger($.support.transition.end)
this.cycle()
}
clearInterval(this.interval)
this.interval = null
return this
},
next: function() {
if (this.sliding) return
return this.slide('next')
},
prev: function() {
if (this.sliding) return
return this.slide('prev')
},
slide: function(type, next) {
var $active = this.$element.find('.item.active'),
$next = next || $active[type](),
isCycling = this.interval,
direction = type == 'next' ? 'left' : 'right',
fallback = type == 'next' ? 'first' : 'last',
that = this,
e = $.Event('slide', {
relatedTarget: $next[0]
})
this.sliding = true
isCycling && this.pause()
$next = $next.length ? $next : this.$element.find('.item')[fallback]()
if ($next.hasClass('active')) return
if ($.support.transition && this.$element.hasClass('slide')) {
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$next.addClass(type)
$next[0].offsetWidth
$active.addClass(direction)
$next.addClass(direction)
this.$element.one($.support.transition.end, function() {
$next.removeClass([type, direction].join(' '))
.addClass('active')
$active.removeClass(['active', direction].join(' '))
that.sliding = false
setTimeout(function() {
that.$element.trigger('slid')
}, 0)
})
} else {
this.$element.trigger(e)
if (e.isDefaultPrevented()) return
$active.removeClass('active')
$next.addClass('active')
this.sliding = false
this.$element.trigger('slid')
}
isCycling && this.cycle()
return this
}
}
$.fn.carousel = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('carousel'),
options = $.extend({}, $.fn.carousel.defaults, typeof option == 'object' && option),
action = typeof option == 'string' ? option : options.slide
if (!data) $this.data('carousel', (data = new Carousel(this, options)))
if (typeof option == 'number') data.to(option)
else if (action) data[action]()
else if (options.interval) data.cycle()
})
}
$.fn.carousel.defaults = {
interval: 5000,
pause: 'hover'
}
$.fn.carousel.Constructor = Carousel
$(function() {
$('body')
.on('click.carousel.data-api', '[data-slide]', function(e) {
var $this = $(this),
href, $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')),
options = !$target.data('modal') && $.extend({}, $target.data(), $this.data())
$target.carousel(options)
e.preventDefault()
})
})
}(window.jQuery);
! function($) {
"use strict";
var Collapse = function(element, options) {
this.$element = $(element)
this.options = $.extend({}, $.fn.collapse.defaults, options)
if (this.options.parent) {
this.$parent = $(this.options.parent)
}
this.options.toggle && this.toggle()
}
Collapse.prototype = {
constructor: Collapse,
dimension: function() {
var hasWidth = this.$element.hasClass('width')
return hasWidth ? 'width' : 'height'
},
show: function() {
var dimension, scroll, actives, hasData
if (this.transitioning) return
dimension = this.dimension()
scroll = $.camelCase(['scroll', dimension].join('-'))
actives = this.$parent && this.$parent.find('> .accordion-group > .in')
if (actives && actives.length) {
hasData = actives.data('collapse')
if (hasData && hasData.transitioning) return
actives.collapse('hide')
hasData || actives.data('collapse', null)
}
this.$element[dimension](0)
this.transition('addClass', $.Event('show'), 'shown')
$.support.transition && this.$element[dimension](this.$element[0][scroll])
},
hide: function() {
var dimension
if (this.transitioning) return
dimension = this.dimension()
this.reset(this.$element[dimension]())
this.transition('removeClass', $.Event('hide'), 'hidden')
this.$element[dimension](0)
},
reset: function(size) {
var dimension = this.dimension()
this.$element.removeClass('collapse')[dimension](size || 'auto')[0].offsetWidth
this.$element[size !== null ? 'addClass' : 'removeClass']('collapse')
return this
},
transition: function(method, startEvent, completeEvent) {
var that = this,
complete = function() {
if (startEvent.type == 'show') that.reset()
that.transitioning = 0
that.$element.trigger(completeEvent)
}
this.$element.trigger(startEvent)
if (startEvent.isDefaultPrevented()) return
this.transitioning = 1
this.$element[method]('in')
$.support.transition && this.$element.hasClass('collapse') ? this.$element.one($.support.transition.end, complete) : complete()
},
toggle: function() {
this[this.$element.hasClass('in') ? 'hide' : 'show']()
}
}
$.fn.collapse = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('collapse'),
options = typeof option == 'object' && option
if (!data) $this.data('collapse', (data = new Collapse(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.collapse.defaults = {
toggle: true
}
$.fn.collapse.Constructor = Collapse
$(function() {
$('body')
.on('click.collapse.data-api', '[data-toggle=collapse]', function(e) {
var $this = $(this),
href, target = $this.attr('data-target') || e.preventDefault() || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, ''),
option = $(target)
.data('collapse') ? 'toggle' : $this.data()
$this[$(target)
.hasClass('in') ? 'addClass' : 'removeClass']('collapsed')
$(target)
.collapse(option)
})
})
}(window.jQuery);
! function($) {
"use strict";
var toggle = '[data-toggle=dropdown]',
Dropdown = function(element) {
var $el = $(element)
.on('click.dropdown.data-api', this.toggle)
$('html')
.on('click.dropdown.data-api', function() {
$el.parent()
.removeClass('open')
})
}
Dropdown.prototype = {
constructor: Dropdown,
toggle: function(e) {
var $this = $(this),
$parent, isActive
if ($this.is('.disabled, :disabled')) return
$parent = getParent($this)
isActive = $parent.hasClass('open')
clearMenus()
if (!isActive) {
$parent.toggleClass('open')
$this.focus()
}
return false
},
keydown: function(e) {
var $this, $items, $active, $parent, isActive, index
if (!/(38|40|27)/.test(e.keyCode)) return
$this = $(this)
e.preventDefault()
e.stopPropagation()
if ($this.is('.disabled, :disabled')) return
$parent = getParent($this)
isActive = $parent.hasClass('open')
if (!isActive || (isActive && e.keyCode == 27)) return $this.click()
$items = $('[role=menu] li:not(.divider) a', $parent)
if (!$items.length) return
index = $items.index($items.filter(':focus'))
if (e.keyCode == 38 && index > 0) index--
if (e.keyCode == 40 && index < $items.length - 1) index++
if (!~index) index = 0
$items.eq(index)
.focus()
}
}
function clearMenus() {
getParent($(toggle))
.removeClass('open')
}
function getParent($this) {
var selector = $this.attr('data-target'),
$parent
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '')
}
$parent = $(selector)
$parent.length || ($parent = $this.parent())
return $parent
}
$.fn.dropdown = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('dropdown')
if (!data) $this.data('dropdown', (data = new Dropdown(this)))
if (typeof option == 'string') data[option].call($this)
})
}
$.fn.dropdown.Constructor = Dropdown
$(function() {
$('html')
.on('click.dropdown.data-api touchstart.dropdown.data-api', clearMenus)
$('body')
.on('click.dropdown touchstart.dropdown.data-api', '.dropdown', function(e) {
e.stopPropagation()
})
.on('click.dropdown.data-api touchstart.dropdown.data-api', toggle, Dropdown.prototype.toggle)
.on('keydown.dropdown.data-api touchstart.dropdown.data-api', toggle + ', [role=menu]', Dropdown.prototype.keydown)
})
}(window.jQuery);
! function($) {
"use strict";
var Modal = function(element, options) {
this.options = options
this.$element = $(element)
.delegate('[data-dismiss="modal"]', 'click.dismiss.modal', $.proxy(this.hide, this))
this.options.remote && this.$element.find('.modal-body')
.load(this.options.remote)
}
Modal.prototype = {
constructor: Modal,
toggle: function() {
return this[!this.isShown ? 'show' : 'hide']()
},
show: function() {
var that = this,
e = $.Event('show')
this.$element.trigger(e)
if (this.isShown || e.isDefaultPrevented()) return
$('body')
.addClass('modal-open')
this.isShown = true
this.escape()
this.backdrop(function() {
var transition = $.support.transition && that.$element.hasClass('fade')
if (!that.$element.parent()
.length) {
that.$element.appendTo(document.body)
}
that.$element.show()
if (transition) {
that.$element[0].offsetWidth
}
that.$element.addClass('in')
.attr('aria-hidden', false)
.focus()
that.enforceFocus()
transition ? that.$element.one($.support.transition.end, function() {
that.$element.trigger('shown')
}) : that.$element.trigger('shown')
})
},
hide: function(e) {
e && e.preventDefault()
var that = this
e = $.Event('hide')
this.$element.trigger(e)
if (!this.isShown || e.isDefaultPrevented()) return
this.isShown = false
$('body')
.removeClass('modal-open')
this.escape()
$(document)
.off('focusin.modal')
this.$element.removeClass('in')
.attr('aria-hidden', true)
$.support.transition && this.$element.hasClass('fade') ? this.hideWithTransition() : this.hideModal()
},
enforceFocus: function() {
var that = this
$(document)
.on('focusin.modal', function(e) {
if (that.$element[0] !== e.target && !that.$element.has(e.target)
.length) {
that.$element.focus()
}
})
},
escape: function() {
var that = this
if (this.isShown && this.options.keyboard) {
this.$element.on('keyup.dismiss.modal', function(e) {
e.which == 27 && that.hide()
})
} else if (!this.isShown) {
this.$element.off('keyup.dismiss.modal')
}
},
hideWithTransition: function() {
var that = this,
timeout = setTimeout(function() {
that.$element.off($.support.transition.end)
that.hideModal()
}, 500)
this.$element.one($.support.transition.end, function() {
clearTimeout(timeout)
that.hideModal()
})
},
hideModal: function(that) {
this.$element.hide()
.trigger('hidden')
this.backdrop()
},
removeBackdrop: function() {
this.$backdrop.remove()
this.$backdrop = null
},
backdrop: function(callback) {
var that = this,
animate = this.$element.hasClass('fade') ? 'fade' : ''
if (this.isShown && this.options.backdrop) {
var doAnimate = $.support.transition && animate
this.$backdrop = $('<div class="modal-backdrop ' + animate + '" />')
.appendTo(document.body)
if (this.options.backdrop != 'static') {
this.$backdrop.click($.proxy(this.hide, this))
}
if (doAnimate) this.$backdrop[0].offsetWidth
this.$backdrop.addClass('in')
doAnimate ? this.$backdrop.one($.support.transition.end, callback) : callback()
} else if (!this.isShown && this.$backdrop) {
this.$backdrop.removeClass('in')
$.support.transition && this.$element.hasClass('fade') ? this.$backdrop.one($.support.transition.end, $.proxy(this.removeBackdrop, this)) : this.removeBackdrop()
} else if (callback) {
callback()
}
}
}
$.fn.modal = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('modal'),
options = $.extend({}, $.fn.modal.defaults, $this.data(), typeof option == 'object' && option)
if (!data) $this.data('modal', (data = new Modal(this, options)))
if (typeof option == 'string') data[option]()
else if (options.show) data.show()
})
}
$.fn.modal.defaults = {
backdrop: true,
keyboard: true,
show: true
}
$.fn.modal.Constructor = Modal
$(function() {
$('body')
.on('click.modal.data-api', '[data-toggle="modal"]', function(e) {
var $this = $(this),
href = $this.attr('href'),
$target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))),
option = $target.data('modal') ? 'toggle' : $.extend({
remote: !/#/.test(href) && href
}, $target.data(), $this.data())
e.preventDefault()
$target.modal(option)
.one('hide', function() {
$this.focus()
})
})
})
}(window.jQuery);
! function($) {
"use strict";
var Tooltip = function(element, options) {
this.init('tooltip', element, options)
}
Tooltip.prototype = {
constructor: Tooltip,
init: function(type, element, options) {
var eventIn, eventOut
this.type = type
this.$element = $(element)
this.options = this.getOptions(options)
this.enabled = true
if (this.options.trigger == 'click') {
this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))
} else if (this.options.trigger != 'manual') {
eventIn = this.options.trigger == 'hover' ? 'mouseenter' : 'focus'
eventOut = this.options.trigger == 'hover' ? 'mouseleave' : 'blur'
this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))
this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))
}
this.options.selector ? (this._options = $.extend({}, this.options, {
trigger: 'manual',
selector: ''
})) : this.fixTitle()
},
getOptions: function(options) {
options = $.extend({}, $.fn[this.type].defaults, options, this.$element.data())
if (options.delay && typeof options.delay == 'number') {
options.delay = {
show: options.delay,
hide: options.delay
}
}
return options
},
enter: function(e) {
var self = $(e.currentTarget)[this.type](this._options)
.data(this.type)
if (!self.options.delay || !self.options.delay.show) return self.show()
clearTimeout(this.timeout)
self.hoverState = 'in'
this.timeout = setTimeout(function() {
if (self.hoverState == 'in') self.show()
}, self.options.delay.show)
},
leave: function(e) {
var self = $(e.currentTarget)[this.type](this._options)
.data(this.type)
if (this.timeout) clearTimeout(this.timeout)
if (!self.options.delay || !self.options.delay.hide) return self.hide()
self.hoverState = 'out'
this.timeout = setTimeout(function() {
if (self.hoverState == 'out') self.hide()
}, self.options.delay.hide)
},
show: function() {
var $tip, inside, pos, actualWidth, actualHeight, placement, tp
if (this.hasContent() && this.enabled) {
$tip = this.tip()
this.setContent()
if (this.options.animation) {
$tip.addClass('fade')
}
placement = typeof this.options.placement == 'function' ? this.options.placement.call(this, $tip[0], this.$element[0]) : this.options.placement
inside = /in/.test(placement)
$tip.remove()
.css({
top: 0,
left: 0,
display: 'block'
})
.appendTo(inside ? this.$element : document.body)
pos = this.getPosition(inside)
actualWidth = $tip[0].offsetWidth
actualHeight = $tip[0].offsetHeight
switch (inside ? placement.split(' ')[1] : placement) {
case 'bottom':
tp = {
top: pos.top + pos.height,
left: pos.left + pos.width / 2 - actualWidth / 2
}
break
case 'top':
tp = {
top: pos.top - actualHeight,
left: pos.left + pos.width / 2 - actualWidth / 2
}
break
case 'left':
tp = {
top: pos.top + pos.height / 2 - actualHeight / 2,
left: pos.left - actualWidth
}
break
case 'right':
tp = {
top: pos.top + pos.height / 2 - actualHeight / 2,
left: pos.left + pos.width
}
break
}
$tip.css(tp)
.addClass(placement)
.addClass('in')
}
},
setContent: function() {
var $tip = this.tip(),
title = this.getTitle()
$tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)
$tip.removeClass('fade in top bottom left right')
},
hide: function() {
var that = this,
$tip = this.tip()
$tip.removeClass('in')
function removeWithAnimation() {
var timeout = setTimeout(function() {
$tip.off($.support.transition.end)
.remove()
}, 500)
$tip.one($.support.transition.end, function() {
clearTimeout(timeout)
$tip.remove()
})
}
$.support.transition && this.$tip.hasClass('fade') ? removeWithAnimation() : $tip.remove()
return this
},
fixTitle: function() {
var $e = this.$element
if ($e.attr('title') || typeof($e.attr('data-original-title')) != 'string') {
$e.attr('data-original-title', $e.attr('title') || '')
.removeAttr('title')
}
},
hasContent: function() {
return this.getTitle()
},
getPosition: function(inside) {
return $.extend({}, (inside ? {
top: 0,
left: 0
} : this.$element.offset()), {
width: this.$element[0].offsetWidth,
height: this.$element[0].offsetHeight
})
},
getTitle: function() {
var title, $e = this.$element,
o = this.options
title = $e.attr('data-original-title') || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)
return title
},
tip: function() {
return this.$tip = this.$tip || $(this.options.template)
},
validate: function() {
if (!this.$element[0].parentNode) {
this.hide()
this.$element = null
this.options = null
}
},
enable: function() {
this.enabled = true
},
disable: function() {
this.enabled = false
},
toggleEnabled: function() {
this.enabled = !this.enabled
},
toggle: function() {
this[this.tip()
.hasClass('in') ? 'hide' : 'show']()
},
destroy: function() {
this.hide()
.$element.off('.' + this.type)
.removeData(this.type)
}
}
$.fn.tooltip = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('tooltip'),
options = typeof option == 'object' && option
if (!data) $this.data('tooltip', (data = new Tooltip(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tooltip.Constructor = Tooltip
$.fn.tooltip.defaults = {
animation: true,
placement: 'top',
selector: false,
template: '<div class="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',
trigger: 'hover',
title: '',
delay: 0,
html: true
}
}(window.jQuery);
! function($) {
"use strict";
var Popover = function(element, options) {
this.init('popover', element, options)
}
Popover.prototype = $.extend({}, $.fn.tooltip.Constructor.prototype, {
constructor: Popover,
setContent: function() {
var $tip = this.tip(),
title = this.getTitle(),
content = this.getContent()
$tip.find('.popover-title')[this.options.html ? 'html' : 'text'](title)
$tip.find('.popover-content > *')[this.options.html ? 'html' : 'text'](content)
$tip.removeClass('fade top bottom left right in')
},
hasContent: function() {
return this.getTitle() || this.getContent()
},
getContent: function() {
var content, $e = this.$element,
o = this.options
content = $e.attr('data-content') || (typeof o.content == 'function' ? o.content.call($e[0]) : o.content)
return content
},
tip: function() {
if (!this.$tip) {
this.$tip = $(this.options.template)
}
return this.$tip
},
destroy: function() {
this.hide()
.$element.off('.' + this.type)
.removeData(this.type)
}
})
$.fn.popover = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('popover'),
options = typeof option == 'object' && option
if (!data) $this.data('popover', (data = new Popover(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.popover.Constructor = Popover
$.fn.popover.defaults = $.extend({}, $.fn.tooltip.defaults, {
placement: 'right',
trigger: 'click',
content: '',
template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><h3 class="popover-title"></h3><div class="popover-content"><p></p></div></div></div>'
})
}(window.jQuery);
! function($) {
"use strict";
function ScrollSpy(element, options) {
var process = $.proxy(this.process, this),
$element = $(element)
.is('body') ? $(window) : $(element),
href
this.options = $.extend({}, $.fn.scrollspy.defaults, options)
this.$scrollElement = $element.on('scroll.scroll-spy.data-api', process)
this.selector = (this.options.target || ((href = $(element)
.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) || '') + ' .nav li > a'
this.$body = $('body')
this.refresh()
this.process()
}
ScrollSpy.prototype = {
constructor: ScrollSpy,
refresh: function() {
var self = this,
$targets
this.offsets = $([])
this.targets = $([])
$targets = this.$body.find(this.selector)
.map(function() {
var $el = $(this),
href = $el.data('target') || $el.attr('href'),
$href = /^#\w/.test(href) && $(href)
return ($href && $href.length && [
[$href.position()
.top, href]
]) || null
})
.sort(function(a, b) {
return a[0] - b[0]
})
.each(function() {
self.offsets.push(this[0])
self.targets.push(this[1])
})
},
process: function() {
var scrollTop = this.$scrollElement.scrollTop() + this.options.offset,
scrollHeight = this.$scrollElement[0].scrollHeight || this.$body[0].scrollHeight,
maxScroll = scrollHeight - this.$scrollElement.height(),
offsets = this.offsets,
targets = this.targets,
activeTarget = this.activeTarget,
i
if (scrollTop >= maxScroll) {
return activeTarget != (i = targets.last()[0]) && this.activate(i)
}
for (i = offsets.length; i--;) {
activeTarget != targets[i] && scrollTop >= offsets[i] && (!offsets[i + 1] || scrollTop <= offsets[i + 1]) && this.activate(targets[i])
}
},
activate: function(target) {
var active, selector
this.activeTarget = target
$(this.selector)
.parent('.active')
.removeClass('active')
selector = this.selector + '[data-target="' + target + '"],' + this.selector + '[href="' + target + '"]'
active = $(selector)
.parent('li')
.addClass('active')
if (active.parent('.dropdown-menu')
.length) {
active = active.closest('li.dropdown')
.addClass('active')
}
active.trigger('activate')
}
}
$.fn.scrollspy = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('scrollspy'),
options = typeof option == 'object' && option
if (!data) $this.data('scrollspy', (data = new ScrollSpy(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.scrollspy.Constructor = ScrollSpy
$.fn.scrollspy.defaults = {
offset: 10
}
$(window)
.on('load', function() {
$('[data-spy="scroll"]')
.each(function() {
var $spy = $(this)
$spy.scrollspy($spy.data())
})
})
}(window.jQuery);
! function($) {
"use strict";
var Tab = function(element) {
this.element = $(element)
}
Tab.prototype = {
constructor: Tab,
show: function() {
var $this = this.element,
$ul = $this.closest('ul:not(.dropdown-menu)'),
selector = $this.attr('data-target'),
previous, $target, e
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '')
}
if ($this.parent('li')
.hasClass('active')) return
previous = $ul.find('.active a')
.last()[0]
e = $.Event('show', {
relatedTarget: previous
})
$this.trigger(e)
if (e.isDefaultPrevented()) return
$target = $(selector)
this.activate($this.parent('li'), $ul)
this.activate($target, $target.parent(), function() {
$this.trigger({
type: 'shown',
relatedTarget: previous
})
})
},
activate: function(element, container, callback) {
var $active = container.find('> .active'),
transition = callback && $.support.transition && $active.hasClass('fade')
function next() {
$active.removeClass('active')
.find('> .dropdown-menu > .active')
.removeClass('active')
element.addClass('active')
if (transition) {
element[0].offsetWidth
element.addClass('in')
} else {
element.removeClass('fade')
}
if (element.parent('.dropdown-menu')) {
element.closest('li.dropdown')
.addClass('active')
}
callback && callback()
}
transition ? $active.one($.support.transition.end, next) : next()
$active.removeClass('in')
}
}
$.fn.tab = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('tab')
if (!data) $this.data('tab', (data = new Tab(this)))
if (typeof option == 'string') data[option]()
})
}
$.fn.tab.Constructor = Tab
$(function() {
$('body')
.on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function(e) {
e.preventDefault()
$(this)
.tab('show')
})
})
}(window.jQuery);
! function($) {
"use strict";
var Typeahead = function(element, options) {
this.$element = $(element)
this.options = $.extend({}, $.fn.typeahead.defaults, options)
this.matcher = this.options.matcher || this.matcher
this.sorter = this.options.sorter || this.sorter
this.highlighter = this.options.highlighter || this.highlighter
this.updater = this.options.updater || this.updater
this.$menu = $(this.options.menu)
.appendTo('body')
this.source = this.options.source
this.shown = false
this.listen()
}
Typeahead.prototype = {
constructor: Typeahead,
select: function() {
var val = this.$menu.find('.active')
.attr('data-value')
this.$element.val(this.updater(val))
.change()
return this.hide()
},
updater: function(item) {
return item
},
show: function() {
var pos = $.extend({}, this.$element.offset(), {
height: this.$element[0].offsetHeight
})
this.$menu.css({
top: pos.top + pos.height,
left: pos.left
})
this.$menu.show()
this.shown = true
return this
},
hide: function() {
this.$menu.hide()
this.shown = false
return this
},
lookup: function(event) {
var items
this.query = this.$element.val()
if (!this.query || this.query.length < this.options.minLength) {
return this.shown ? this.hide() : this
}
items = $.isFunction(this.source) ? this.source(this.query, $.proxy(this.process, this)) : this.source
return items ? this.process(items) : this
},
process: function(items) {
var that = this
items = $.grep(items, function(item) {
return that.matcher(item)
})
items = this.sorter(items)
if (!items.length) {
return this.shown ? this.hide() : this
}
return this.render(items.slice(0, this.options.items))
.show()
},
matcher: function(item) {
return~item.toLowerCase()
.indexOf(this.query.toLowerCase())
},
sorter: function(items) {
var beginswith = [],
caseSensitive = [],
caseInsensitive = [],
item
while (item = items.shift()) {
if (!item.toLowerCase()
.indexOf(this.query.toLowerCase())) beginswith.push(item)
else if (~item.indexOf(this.query)) caseSensitive.push(item)
else caseInsensitive.push(item)
}
return beginswith.concat(caseSensitive, caseInsensitive)
},
highlighter: function(item) {
var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
return item.replace(new RegExp('(' + query + ')', 'ig'), function($1, match) {
return '<strong>' + match + '</strong>'
})
},
render: function(items) {
var that = this
items = $(items)
.map(function(i, item) {
i = $(that.options.item)
.attr('data-value', item)
i.find('a')
.html(that.highlighter(item))
return i[0]
})
items.first()
.addClass('active')
this.$menu.html(items)
return this
},
next: function(event) {
var active = this.$menu.find('.active')
.removeClass('active'),
next = active.next()
if (!next.length) {
next = $(this.$menu.find('li')[0])
}
next.addClass('active')
},
prev: function(event) {
var active = this.$menu.find('.active')
.removeClass('active'),
prev = active.prev()
if (!prev.length) {
prev = this.$menu.find('li')
.last()
}
prev.addClass('active')
},
listen: function() {
this.$element.on('blur', $.proxy(this.blur, this))
.on('keypress', $.proxy(this.keypress, this))
.on('keyup', $.proxy(this.keyup, this))
if ($.browser.webkit || $.browser.msie) {
this.$element.on('keydown', $.proxy(this.keydown, this))
}
this.$menu.on('click', $.proxy(this.click, this))
.on('mouseenter', 'li', $.proxy(this.mouseenter, this))
},
move: function(e) {
if (!this.shown) return
switch (e.keyCode) {
case 9:
case 13:
case 27:
e.preventDefault()
break
case 38:
e.preventDefault()
this.prev()
break
case 40:
e.preventDefault()
this.next()
break
}
e.stopPropagation()
},
keydown: function(e) {
this.suppressKeyPressRepeat = !~$.inArray(e.keyCode, [40, 38, 9, 13, 27])
this.move(e)
},
keypress: function(e) {
if (this.suppressKeyPressRepeat) return
this.move(e)
},
keyup: function(e) {
switch (e.keyCode) {
case 40:
case 38:
break
case 9:
case 13:
if (!this.shown) return
this.select()
break
case 27:
if (!this.shown) return
this.hide()
break
default:
this.lookup()
}
e.stopPropagation()
e.preventDefault()
},
blur: function(e) {
var that = this
setTimeout(function() {
that.hide()
}, 150)
},
click: function(e) {
e.stopPropagation()
e.preventDefault()
this.select()
},
mouseenter: function(e) {
this.$menu.find('.active')
.removeClass('active')
$(e.currentTarget)
.addClass('active')
}
}
$.fn.typeahead = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('typeahead'),
options = typeof option == 'object' && option
if (!data) $this.data('typeahead', (data = new Typeahead(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.typeahead.defaults = {
source: [],
items: 8,
menu: '<ul class="typeahead dropdown-menu"></ul>',
item: '<li><a href="#"></a></li>',
minLength: 1
}
$.fn.typeahead.Constructor = Typeahead
$(function() {
$('body')
.on('focus.typeahead.data-api', '[data-provide="typeahead"]', function(e) {
var $this = $(this)
if ($this.data('typeahead')) return
e.preventDefault()
$this.typeahead($this.data())
})
})
}(window.jQuery);
! function($) {
"use strict";
var Affix = function(element, options) {
this.options = $.extend({}, $.fn.affix.defaults, options)
this.$window = $(window)
.on('scroll.affix.data-api', $.proxy(this.checkPosition, this))
this.$element = $(element)
this.checkPosition()
}
Affix.prototype.checkPosition = function() {
if (!this.$element.is(':visible')) return
var scrollHeight = $(document)
.height(),
scrollTop = this.$window.scrollTop(),
position = this.$element.offset(),
offset = this.options.offset,
offsetBottom = offset.bottom,
offsetTop = offset.top,
reset = 'affix affix-top affix-bottom',
affix
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top()
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()
affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ? false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' : offsetTop != null && scrollTop <= offsetTop ? 'top' : false
if (this.affixed === affix) return
this.affixed = affix
this.unpin = affix == 'bottom' ? position.top - scrollTop : null
this.$element.removeClass(reset)
.addClass('affix' + (affix ? '-' + affix : ''))
}
$.fn.affix = function(option) {
return this.each(function() {
var $this = $(this),
data = $this.data('affix'),
options = typeof option == 'object' && option
if (!data) $this.data('affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()
})
}
$.fn.affix.Constructor = Affix
$.fn.affix.defaults = {
offset: 0
}
$(window)
.on('load', function() {
$('[data-spy="affix"]')
.each(function() {
var $spy = $(this),
data = $spy.data()
data.offset = data.offset || {}
data.offsetBottom && (data.offset.bottom = data.offsetBottom)
data.offsetTop && (data.offset.top = data.offsetTop)
$spy.affix(data)
})
})
}(window.jQuery);
! function() {
var DEFAULT_WIDTH = 100;
navigator.getMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
var imgCanvas = document.createElement('canvas');
var imgCtx = imgCanvas.getContext('2d');
var videoCanvas = document.createElement('canvas');
var videoCtx = videoCanvas.getContext('2d');
var videoWidth, videoHeight, video, container, stream, videoTimer;
var chars = ['@', '#', '$', '=', '*', '!', ';', ':', '~', '-', ',', '.', ' ', ' '];
var charLen = chars.length - 1;
function getChar(val) {
return chars[parseInt(val * charLen, 10)];
}
function logError(err) {
if (console && console.log) console.log('Error!', err);
return false;
}
function setVideoDimension(width, height) {
videoCanvas.width = videoWidth = width;
videoCanvas.height = videoHeight = height;
}
function renderVideo(videoEl, containerEl, cb, ontick) {
cb = cb || function() {};
if (typeof navigator.getMedia !== 'function') {
var msg = 'Error: browser does not support getUserMedia';
containerEl.innerHTML = msg;
return logError(msg);
}
video = videoEl;
container = containerEl;
navigator.getMedia({
video: true,
audio: false
}, function(localMediaStream) {
stream = localMediaStream;
var url = window.URL || window.webkitURL;
video.src = url.createObjectURL(localMediaStream);
startRender(15, ontick);
video.onloadedmetadata = logError;
cb();
}, logError);
return true;
}
function startRender(interval, ontick) {
ontick = ontick || function() {};
if (typeof interval !== 'number') interval = 20;
videoTimer = setInterval(function() {
if (stream) {
var w = videoWidth,
h = videoHeight;
videoCtx.drawImage(video, 0, 0, w, h);
var data = videoCtx.getImageData(0, 0, w, h)
.data;
var asciiString = getAsciiString(data, w, h);
container.textContent = asciiString;
ontick(asciiString);
}
}, interval);
}
function stopRender() {
if (videoTimer) clearInterval(videoTimer);
}
function renderImage(image, container, cb) {
cb = cb || function() {};
function drawImage(image) {
var ratio = image.width / image.height;
imgCanvas.width = w = DEFAULT_WIDTH;
imgCanvas.height = h = w / ratio;
imgCtx.drawImage(image, 0, 0, w, h);
data = imgCtx.getImageData(0, 0, w, h)
.data;
container.textContent = getAsciiString(data, w, h);
cb();
}
if (image.tagName == "CANVAS") {
drawImage(image);
} else {
if (image.complete) {
drawImage(image);
} else {
image.addEventListener('load', function() {
drawImage(image);
});
}
}
}
function getRGB(d, i) {
return [d[i = i * 4], d[i + 1], d[i + 2]];
}
function getAsciiString(d, width, height) {
var len = width * height - 1,
str = '';
for (var i = 0; i < len; i++) {
if (i % width === 0) str += '\n';
var rgb = getRGB(d, i);
var val = Math.max(rgb[0], rgb[1], rgb[2]) / 255;
str += getChar(val);
}
return str;
}
setVideoDimension(DEFAULT_WIDTH, parseInt(DEFAULT_WIDTH * 3 / 4, 10));
window.Jscii = {
setVideoDimension: setVideoDimension,
setResolution: function(r) {
DEFAULT_WIDTH = r;
setVideoDimension(DEFAULT_WIDTH, parseInt(DEFAULT_WIDTH * 3 / 4, 10));
},
renderVideo: renderVideo,
startRender: startRender,
stopRender: stopRender,
renderImage: renderImage
};
}();
var fx = function() {
function n(b, c, d) {
return Math.max(b, Math.min(c, d))
}
function v(b) {
return {
_: b,
loadContentsOf: function(c) {
this._.loadContentsOf(c)
},
destroy: function() {
this._.destroy()
}
}
}
function C(b) {
return v(r.fromElement(b))
}
function D(b, c) {
var d = a.getExtension("OES_texture_float") ? a.FLOAT : a.UNSIGNED_BYTE;
this._.texture && this._.texture.destroy();
this._.spareTexture && this._.spareTexture.destroy();
this.width = b;
this.height = c;
this._.texture = new r(b, c, a.RGBA, d);
this._.spareTexture = new r(b, c, a.RGBA, d);
this._.extraTexture = this._.extraTexture || new r(0, 0, a.RGBA, d);
this._.flippedShader = this._.flippedShader || new l(null, "uniform sampler2D texture;varying vec2 texCoord;void main(){gl_FragColor=texture2D(texture,vec2(texCoord.x,1.0-texCoord.y));}");
this._.isInitialized = true
}
function E(b, c, d) {
if (!this._.isInitialized || b._.width != this.width || b._.height != this.height) D.call(this, c ? c : b._.width, d ? d : b._.height);
b._.use();
this._.texture.drawTo(function() {
l.getDefaultShader()
.drawRect()
});
return this
}
function F() {
this._.texture.use();
this._.flippedShader.drawRect();
return this
}
function m(b, c, d, e) {
(d || this._.texture)
.use();
this._.spareTexture.drawTo(function() {
b.uniforms(c)
.drawRect()
});
this._.spareTexture.swapWith(e || this._.texture)
}
function G(b) {
b.parentNode.insertBefore(this, b);
b.parentNode.removeChild(b);
return this
}
function H() {
var b = new r(this._.texture.width, this._.texture.height, a.RGBA, a.UNSIGNED_BYTE);
this._.texture.use();
b.drawTo(function() {
l.getDefaultShader()
.drawRect()
});
return v(b)
}
function w() {
var b = this._.texture.width,
c = this._.texture.height,
d = new Uint8Array(b * c * 4);
this._.texture.drawTo(function() {
a.readPixels(0, 0, b, c, a.RGBA, a.UNSIGNED_BYTE, d)
});
return d
}
function I(b) {
var c = this._.texture.width,
d = this._.texture.height,
e = w.call(this),
f = document.createElement("canvas"),
g = f.getContext("2d");
f.width = c;
f.height = d;
c = g.createImageData(c, d);
for (d = 0; d < e.length; d++) c.data[d] = e[d];
g.putImageData(c, 0, 0);
return f.toDataURL(b)
}
function k(b) {
return function() {
a = this._.gl;
return b.apply(this, arguments)
}
}
function x(b, c, d, e, f, g, h, i) {
var j = d - f,
o = e - g,
p = h - f,
y = i - g;
f = b - d + f - h;
g = c - e + g - i;
var z = j * y - p * o;
p = (f * y - p * g) / z;
j = (j * g - f * o) / z;
return [d - b + p * d, e - c + p * e, p, h - b + j * h, i - c + j * i, j, b, c, 1]
}
function A(b) {
var c = b[0],
d = b[1],
e = b[2],
f = b[3],
g = b[4],
h = b[5],
i = b[6],
j = b[7];
b = b[8];
var o = c * g * b - c * h * j - d * f * b + d * h * i + e * f * j - e * g * i;
return [(g * b - h * j) / o, (e * j - d * b) / o, (d * h - e * g) / o, (h * i - f * b) / o, (c * b - e * i) / o, (e * f - c * h) / o, (f * j - g * i) / o, (d * i - c * j) / o, (c * g - d * f) / o]
}
function J(b, c) {
return [b[0] * c[0] + b[1] * c[3] + b[2] * c[6], b[0] * c[1] + b[1] * c[4] + b[2] * c[7], b[0] * c[2] + b[1] * c[5] + b[2] * c[8], b[3] * c[0] + b[4] * c[3] + b[5] * c[6], b[3] * c[1] + b[4] * c[4] + b[5] * c[7], b[3] * c[2] + b[4] * c[5] + b[5] * c[8], b[6] * c[0] + b[7] * c[3] + b[8] * c[6], b[6] * c[1] + b[7] * c[4] + b[8] * c[7], b[6] * c[2] + b[7] * c[5] + b[8] * c[8]]
}
function B(b) {
var c = b.length;
this.xa = [];
this.ya = [];
this.u = [];
this.y2 = [];
b.sort(function(g, h) {
return g[0] - h[0]
});
for (var d = 0; d < c; d++) {
this.xa.push(b[d][0]);
this.ya.push(b[d][1])
}
this.u[0] = 0;
this.y2[0] = 0;
for (d = 1; d < c - 1; ++d) {
b = this.xa[d + 1] - this.xa[d - 1];
var e = (this.xa[d] - this.xa[d - 1]) / b,
f = e * this.y2[d - 1] + 2;
this.y2[d] = (e - 1) / f;
this.u[d] = (6 * ((this.ya[d + 1] - this.ya[d]) / (this.xa[d + 1] - this.xa[d]) - (this.ya[d] - this.ya[d - 1]) / (this.xa[d] - this.xa[d - 1])) / b - e * this.u[d - 1]) / f
}
this.y2[c - 1] = 0;
for (d = c - 2; d >= 0; --d) this.y2[d] = this.y2[d] * this.y2[d + 1] + this.u[d]
}
function t(b, c) {
return new l(null, b + "uniform sampler2D texture;uniform vec2 texSize;varying vec2 texCoord;void main(){vec2 coord=texCoord*texSize;" + c + "gl_FragColor=texture2D(texture,coord/texSize);vec2 clampedCoord=clamp(coord,vec2(0.0),texSize);if(coord!=clampedCoord){gl_FragColor.a*=max(0.0,1.0-length(coord-clampedCoord));}}")
}
function K(b, c) {
a.brightnessContrast = a.brightnessContrast || new l(null, "uniform sampler2D texture;uniform float brightness;uniform float contrast;varying vec2 texCoord;void main(){vec4 color=texture2D(texture,texCoord);color.rgb+=brightness;if(contrast>0.0){color.rgb=(color.rgb-0.5)/(1.0-contrast)+0.5;}else{color.rgb=(color.rgb-0.5)*(1.0+contrast)+0.5;}gl_FragColor=color;}");
m.call(this, a.brightnessContrast, {
brightness: n(-1, b, 1),
contrast: n(-1, c, 1)
});
return this
}
function s(b) {
b = new B(b);
for (var c = [], d = 0; d < 256; d++) c.push(n(0, Math.floor(b.interpolate(d / 255) * 256), 255));
return c
}
function L(b, c, d) {
b = s(b);
if (arguments.length == 1) c = d = b;
else {
c = s(c);
d = s(d)
}
for (var e = [], f = 0; f < 256; f++) e.splice(e.length, 0, b[f], c[f], d[f], 255);
this._.extraTexture.initFromBytes(256, 1, e);
this._.extraTexture.use(1);
a.curves = a.curves || new l(null, "uniform sampler2D texture;uniform sampler2D map;varying vec2 texCoord;void main(){vec4 color=texture2D(texture,texCoord);color.r=texture2D(map,vec2(color.r)).r;color.g=texture2D(map,vec2(color.g)).g;color.b=texture2D(map,vec2(color.b)).b;gl_FragColor=color;}");
a.curves.textures({
map: 1
});
m.call(this, a.curves, {});
return this
}
function M(b) {
a.denoise = a.denoise || new l(null, "uniform sampler2D texture;uniform float exponent;uniform float strength;uniform vec2 texSize;varying vec2 texCoord;void main(){vec4 center=texture2D(texture,texCoord);vec4 color=vec4(0.0);float total=0.0;for(float x=-4.0;x<=4.0;x+=1.0){for(float y=-4.0;y<=4.0;y+=1.0){vec4 sample=texture2D(texture,texCoord+vec2(x,y)/texSize);float weight=1.0-abs(dot(sample.rgb-center.rgb,vec3(0.25)));weight=pow(weight,exponent);color+=sample*weight;total+=weight;}}gl_FragColor=color/total;}");
for (var c = 0; c < 2; c++) m.call(this, a.denoise, {
exponent: Math.max(0, b),
texSize: [this.width, this.height]
});
return this
}
function N(b, c) {
a.hueSaturation = a.hueSaturation || new l(null, "uniform sampler2D texture;uniform float hue;uniform float saturation;varying vec2 texCoord;void main(){vec4 color=texture2D(texture,texCoord);float angle=hue*3.14159265;float s=sin(angle),c=cos(angle);vec3 weights=(vec3(2.0*c,-sqrt(3.0)*s-c,sqrt(3.0)*s-c)+1.0)/3.0;float len=length(color.rgb);color.rgb=vec3(dot(color.rgb,weights.xyz),dot(color.rgb,weights.zxy),dot(color.rgb,weights.yzx));float average=(color.r+color.g+color.b)/3.0;if(saturation>0.0){color.rgb+=(average-color.rgb)*(1.0-1.0/(1.001-saturation));}else{color.rgb+=(average-color.rgb)*(-saturation);}gl_FragColor=color;}");
m.call(this, a.hueSaturation, {
hue: n(-1, b, 1),
saturation: n(-1, c, 1)
});
return this
}
function O(b) {
a.noise = a.noise || new l(null, "uniform sampler2D texture;uniform float amount;varying vec2 texCoord;float rand(vec2 co){return fract(sin(dot(co.xy,vec2(12.9898,78.233)))*43758.5453);}void main(){vec4 color=texture2D(texture,texCoord);float diff=(rand(texCoord)-0.5)*amount;color.r+=diff;color.g+=diff;color.b+=diff;gl_FragColor=color;}");
m.call(this, a.noise, {
amount: n(0, b, 1)
});
return this
}
function P(b) {
a.sepia = a.sepia || new l(null, "uniform sampler2D texture;uniform float amount;varying vec2 texCoord;void main(){vec4 color=texture2D(texture,texCoord);float r=color.r;float g=color.g;float b=color.b;color.r=min(1.0,(r*(1.0-(0.607*amount)))+(g*(0.769*amount))+(b*(0.189*amount)));color.g=min(1.0,(r*0.349*amount)+(g*(1.0-(0.314*amount)))+(b*0.168*amount));color.b=min(1.0,(r*0.272*amount)+(g*0.534*amount)+(b*(1.0-(0.869*amount))));gl_FragColor=color;}");
m.call(this, a.sepia, {
amount: n(0, b, 1)
});
return this
}
function Q(b, c) {
a.unsharpMask = a.unsharpMask || new l(null, "uniform sampler2D blurredTexture;uniform sampler2D originalTexture;uniform float strength;uniform float threshold;varying vec2 texCoord;void main(){vec4 blurred=texture2D(blurredTexture,texCoord);vec4 original=texture2D(originalTexture,texCoord);gl_FragColor=mix(blurred,original,1.0+strength);}");
this._.extraTexture.ensureFormat(this._.texture);
this._.texture.use();
this._.extraTexture.drawTo(function() {
l.getDefaultShader()
.drawRect()
});
this._.extraTexture.use(1);
this.triangleBlur(b);
a.unsharpMask.textures({
originalTexture: 1
});
m.call(this, a.unsharpMask, {
strength: c
});
this._.extraTexture.unuse(1);
return this
}
function R(b) {
a.vibrance = a.vibrance || new l(null, "uniform sampler2D texture;uniform float amount;varying vec2 texCoord;void main(){vec4 color=texture2D(texture,texCoord);float average=(color.r+color.g+color.b)/3.0;float mx=max(color.r,max(color.g,color.b));float amt=(mx-average)*(-amount*3.0);color.rgb=mix(color.rgb,vec3(mx),amt);gl_FragColor=color;}");
m.call(this, a.vibrance, {
amount: n(-1, b, 1)
});
return this
}
function S(b, c) {
a.vignette = a.vignette || new l(null, "uniform sampler2D texture;uniform float size;uniform float amount;varying vec2 texCoord;void main(){vec4 color=texture2D(texture,texCoord);float dist=distance(texCoord,vec2(0.5,0.5));color.rgb*=smoothstep(0.8,size*0.799,dist*(amount+size));gl_FragColor=color;}");
m.call(this, a.vignette, {
size: n(0, b, 1),
amount: n(0, c, 1)
});
return this
}
function T(b, c, d) {
a.lensBlurPrePass = a.lensBlurPrePass || new l(null, "uniform sampler2D texture;uniform float power;varying vec2 texCoord;void main(){vec4 color=texture2D(texture,texCoord);color=pow(color,vec4(power));gl_FragColor=vec4(color);}");
var e = "uniform sampler2D texture0;uniform sampler2D texture1;uniform vec2 delta0;uniform vec2 delta1;uniform float power;varying vec2 texCoord;" + q + "vec4 sample(vec2 delta){float offset=random(vec3(delta,151.7182),0.0);vec4 color=vec4(0.0);float total=0.0;for(float t=0.0;t<=30.0;t++){float percent=(t+offset)/30.0;color+=texture2D(texture0,texCoord+delta*percent);total+=1.0;}return color/total;}";
a.lensBlur0 = a.lensBlur0 || new l(null, e + "void main(){gl_FragColor=sample(delta0);}");
a.lensBlur1 = a.lensBlur1 || new l(null, e + "void main(){gl_FragColor=(sample(delta0)+sample(delta1))*0.5;}");
a.lensBlur2 = a.lensBlur2 || (new l(null, e + "void main(){vec4 color=(sample(delta0)+2.0*texture2D(texture1,texCoord))/3.0;gl_FragColor=pow(color,vec4(power));}"))
.textures({
texture1: 1
});
e = [];
for (var f = 0; f < 3; f++) {
var g = d + f * Math.PI * 2 / 3;
e.push([b * Math.sin(g) / this.width, b * Math.cos(g) / this.height])
}
b = Math.pow(10, n(-1, c, 1));
m.call(this, a.lensBlurPrePass, {
power: b
});
this._.extraTexture.ensureFormat(this._.texture);
m.call(this, a.lensBlur0, {
delta0: e[0]
}, this._.texture, this._.extraTexture);
m.call(this, a.lensBlur1, {
delta0: e[1],
delta1: e[2]
}, this._.extraTexture, this._.extraTexture);
m.call(this, a.lensBlur0, {
delta0: e[1]
});
this._.extraTexture.use(1);
m.call(this, a.lensBlur2, {
power: 1 / b,
delta0: e[2]
});
return this
}
function U(b, c, d, e, f, g) {
a.tiltShift = a.tiltShift || new l(null, "uniform sampler2D texture;uniform float blurRadius;uniform float gradientRadius;uniform vec2 start;uniform vec2 end;uniform vec2 delta;uniform vec2 texSize;varying vec2 texCoord;" + q + "void main(){vec4 color=vec4(0.0);float total=0.0;float offset=random(vec3(12.9898,78.233,151.7182),0.0);vec2 normal=normalize(vec2(start.y-end.y,end.x-start.x));float radius=smoothstep(0.0,1.0,abs(dot(texCoord*texSize-start,normal))/gradientRadius)*blurRadius;for(float t=-30.0;t<=30.0;t++){float percent=(t+offset-0.5)/30.0;float weight=1.0-abs(percent);vec4 sample=texture2D(texture,texCoord+delta/texSize*percent*radius);sample.rgb*=sample.a;color+=sample*weight;total+=weight;}gl_FragColor=color/total;gl_FragColor.rgb/=gl_FragColor.a+0.00001;}");
var h = d - b,
i = e - c,
j = Math.sqrt(h * h + i * i);
m.call(this, a.tiltShift, {
blurRadius: f,
gradientRadius: g,
start: [b, c],
end: [d, e],
delta: [h / j, i / j],
texSize: [this.width, this.height]
});
m.call(this, a.tiltShift, {
blurRadius: f,
gradientRadius: g,
start: [b, c],
end: [d, e],
delta: [-i / j, h / j],
texSize: [this.width, this.height]
});
return this
}
function V(b) {
a.triangleBlur = a.triangleBlur || new l(null, "uniform sampler2D texture;uniform vec2 delta;varying vec2 texCoord;" + q + "void main(){vec4 color=vec4(0.0);float total=0.0;float offset=random(vec3(12.9898,78.233,151.7182),0.0);for(float t=-30.0;t<=30.0;t++){float percent=(t+offset-0.5)/30.0;float weight=1.0-abs(percent);vec4 sample=texture2D(texture,texCoord+delta*percent);sample.rgb*=sample.a;color+=sample*weight;total+=weight;}gl_FragColor=color/total;gl_FragColor.rgb/=gl_FragColor.a+0.00001;}");
m.call(this, a.triangleBlur, {
delta: [b / this.width, 0]
});
m.call(this, a.triangleBlur, {
delta: [0, b / this.height]
});
return this
}
function W(b, c, d) {
a.zoomBlur = a.zoomBlur || new l(null, "uniform sampler2D texture;uniform vec2 center;uniform float strength;uniform vec2 texSize;varying vec2 texCoord;" + q + "void main(){vec4 color=vec4(0.0);float total=0.0;vec2 toCenter=center-texCoord*texSize;float offset=random(vec3(12.9898,78.233,151.7182),0.0);for(float t=0.0;t<=40.0;t++){float percent=(t+offset)/40.0;float weight=4.0*(percent-percent*percent);vec4 sample=texture2D(texture,texCoord+toCenter*percent*strength/texSize);sample.rgb*=sample.a;color+=sample*weight;total+=weight;}gl_FragColor=color/total;gl_FragColor.rgb/=gl_FragColor.a+0.00001;}");
m.call(this, a.zoomBlur, {
center: [b, c],
strength: d,
texSize: [this.width, this.height]
});
return this
}
function X(b, c, d, e) {
a.colorHalftone = a.colorHalftone || new l(null, "uniform sampler2D texture;uniform vec2 center;uniform float angle;uniform float scale;uniform vec2 texSize;varying vec2 texCoord;float pattern(float angle){float s=sin(angle),c=cos(angle);vec2 tex=texCoord*texSize-center;vec2 point=vec2(c*tex.x-s*tex.y,s*tex.x+c*tex.y)*scale;return(sin(point.x)*sin(point.y))*4.0;}void main(){vec4 color=texture2D(texture,texCoord);vec3 cmy=1.0-color.rgb;float k=min(cmy.x,min(cmy.y,cmy.z));cmy=(cmy-k)/(1.0-k);cmy=clamp(cmy*10.0-3.0+vec3(pattern(angle+0.26179),pattern(angle+1.30899),pattern(angle)),0.0,1.0);k=clamp(k*10.0-5.0+pattern(angle+0.78539),0.0,1.0);gl_FragColor=vec4(1.0-cmy-k,color.a);}");
m.call(this, a.colorHalftone, {
center: [b, c],
angle: d,
scale: Math.PI / e,
texSize: [this.width, this.height]
});
return this
}
function Y(b, c, d, e) {
a.dotScreen = a.dotScreen || new l(null, "uniform sampler2D texture;uniform vec2 center;uniform float angle;uniform float scale;uniform vec2 texSize;varying vec2 texCoord;float pattern(){float s=sin(angle),c=cos(angle);vec2 tex=texCoord*texSize-center;vec2 point=vec2(c*tex.x-s*tex.y,s*tex.x+c*tex.y)*scale;return(sin(point.x)*sin(point.y))*4.0;}void main(){vec4 color=texture2D(texture,texCoord);float average=(color.r+color.g+color.b)/3.0;gl_FragColor=vec4(vec3(average*10.0-5.0+pattern()),color.a);}");
m.call(this, a.dotScreen, {
center: [b, c],
angle: d,
scale: Math.PI / e,
texSize: [this.width, this.height]
});
return this
}
function Z(b) {
a.edgeWork1 = a.edgeWork1 || new l(null, "uniform sampler2D texture;uniform vec2 delta;varying vec2 texCoord;" + q + "void main(){vec2 color=vec2(0.0);vec2 total=vec2(0.0);float offset=random(vec3(12.9898,78.233,151.7182),0.0);for(float t=-30.0;t<=30.0;t++){float percent=(t+offset-0.5)/30.0;float weight=1.0-abs(percent);vec3 sample=texture2D(texture,texCoord+delta*percent).rgb;float average=(sample.r+sample.g+sample.b)/3.0;color.x+=average*weight;total.x+=weight;if(abs(t)<15.0){weight=weight*2.0-1.0;color.y+=average*weight;total.y+=weight;}}gl_FragColor=vec4(color/total,0.0,1.0);}");
a.edgeWork2 = a.edgeWork2 || new l(null, "uniform sampler2D texture;uniform vec2 delta;varying vec2 texCoord;" + q + "void main(){vec2 color=vec2(0.0);vec2 total=vec2(0.0);float offset=random(vec3(12.9898,78.233,151.7182),0.0);for(float t=-30.0;t<=30.0;t++){float percent=(t+offset-0.5)/30.0;float weight=1.0-abs(percent);vec2 sample=texture2D(texture,texCoord+delta*percent).xy;color.x+=sample.x*weight;total.x+=weight;if(abs(t)<15.0){weight=weight*2.0-1.0;color.y+=sample.y*weight;total.y+=weight;}}float c=clamp(10000.0*(color.y/total.y-color.x/total.x)+0.5,0.0,1.0);gl_FragColor=vec4(c,c,c,1.0);}");
m.call(this, a.edgeWork1, {
delta: [b / this.width, 0]
});
m.call(this, a.edgeWork2, {
delta: [0, b / this.height]
});
return this
}
function $(b, c, d) {
a.hexagonalPixelate = a.hexagonalPixelate || new l(null, "uniform sampler2D texture;uniform vec2 center;uniform float scale;uniform vec2 texSize;varying vec2 texCoord;void main(){vec2 tex=(texCoord*texSize-center)/scale;tex.y/=0.866025404;tex.x-=tex.y*0.5;vec2 a;if(tex.x+tex.y-floor(tex.x)-floor(tex.y)<1.0)a=vec2(floor(tex.x),floor(tex.y));else a=vec2(ceil(tex.x),ceil(tex.y));vec2 b=vec2(ceil(tex.x),floor(tex.y));vec2 c=vec2(floor(tex.x),ceil(tex.y));vec3 TEX=vec3(tex.x,tex.y,1.0-tex.x-tex.y);vec3 A=vec3(a.x,a.y,1.0-a.x-a.y);vec3 B=vec3(b.x,b.y,1.0-b.x-b.y);vec3 C=vec3(c.x,c.y,1.0-c.x-c.y);float alen=length(TEX-A);float blen=length(TEX-B);float clen=length(TEX-C);vec2 choice;if(alen<blen){if(alen<clen)choice=a;else choice=c;}else{if(blen<clen)choice=b;else choice=c;}choice.x+=choice.y*0.5;choice.y*=0.866025404;choice*=scale/texSize;gl_FragColor=texture2D(texture,choice+center/texSize);}");
m.call(this, a.hexagonalPixelate, {
center: [b, c],
scale: d,
texSize: [this.width, this.height]
});
return this
}
function aa(b) {
a.ink = a.ink || new l(null, "uniform sampler2D texture;uniform float strength;uniform vec2 texSize;varying vec2 texCoord;void main(){vec2 dx=vec2(1.0/texSize.x,0.0);vec2 dy=vec2(0.0,1.0/texSize.y);vec4 color=texture2D(texture,texCoord);float bigTotal=0.0;float smallTotal=0.0;vec3 bigAverage=vec3(0.0);vec3 smallAverage=vec3(0.0);for(float x=-2.0;x<=2.0;x+=1.0){for(float y=-2.0;y<=2.0;y+=1.0){vec3 sample=texture2D(texture,texCoord+dx*x+dy*y).rgb;bigAverage+=sample;bigTotal+=1.0;if(abs(x)+abs(y)<2.0){smallAverage+=sample;smallTotal+=1.0;}}}vec3 edge=max(vec3(0.0),bigAverage/bigTotal-smallAverage/smallTotal);gl_FragColor=vec4(color.rgb-dot(edge,edge)*strength*100000.0,color.a);}");
m.call(this, a.ink, {
strength: b * b * b * b * b,
texSize: [this.width, this.height]
});
return this
}
function ba(b, c, d, e) {
a.bulgePinch = a.bulgePinch || t("uniform float radius;uniform float strength;uniform vec2 center;", "coord-=center;float distance=length(coord);if(distance<radius){float percent=distance/radius;if(strength>0.0){coord*=mix(1.0,smoothstep(0.0,radius/distance,percent),strength*0.75);}else{coord*=mix(1.0,pow(percent,1.0+strength*0.75)*radius/distance,1.0-percent);}}coord+=center;");
m.call(this, a.bulgePinch, {
radius: d,
strength: n(-1, e, 1),
center: [b, c],
texSize: [this.width, this.height]
});
return this
}
function ca(b, c, d) {
a.matrixWarp = a.matrixWarp || t("uniform mat3 matrix;uniform bool useTextureSpace;", "if(useTextureSpace)coord=coord/texSize*2.0-1.0;vec3 warp=matrix*vec3(coord,1.0);coord=warp.xy/warp.z;if(useTextureSpace)coord=(coord*0.5+0.5)*texSize;");
b = Array.prototype.concat.apply([], b);
if (b.length == 4) b = [b[0], b[1], 0, b[2], b[3], 0, 0, 0, 1];
else if (b.length != 9) throw "can only warp with 2x2 or 3x3 matrix";
m.call(this, a.matrixWarp, {
matrix: c ? A(b) : b,
texSize: [this.width, this.height],
useTextureSpace: d | 0
});
return this
}
function da(b, c) {
var d = x.apply(null, c),
e = x.apply(null, b);
return this.matrixWarp(J(A(d), e))
}
function ea(b, c, d, e) {
a.swirl = a.swirl || t("uniform float radius;uniform float angle;uniform vec2 center;", "coord-=center;float distance=length(coord);if(distance<radius){float percent=(radius-distance)/radius;float theta=percent*percent*angle;float s=sin(theta);float c=cos(theta);coord=vec2(coord.x*c-coord.y*s,coord.x*s+coord.y*c);}coord+=center;");
m.call(this, a.swirl, {
radius: d,
center: [b, c],
angle: e,
texSize: [this.width, this.height]
});
return this
}
var u = {}, a;
u.canvas = function() {
var b = document.createElement("canvas");
try {
a = b.getContext("experimental-webgl", {
premultipliedAlpha: false
})
} catch (c) {
a = null
}
if (!a) throw "This browser does not support WebGL";
b._ = {
gl: a,
isInitialized: false,
texture: null,
spareTexture: null,
flippedShader: null
};
b.texture = k(C);
b.draw = k(E);
b.update = k(F);
b.replace = k(G);
b.contents = k(H);
b.getPixelArray = k(w);
b.toDataURL = k(I);
b.brightnessContrast = k(K);
b.hexagonalPixelate = k($);
b.hueSaturation = k(N);
b.colorHalftone = k(X);
b.triangleBlur = k(V);
b.unsharpMask = k(Q);
b.perspective = k(da);
b.matrixWarp = k(ca);
b.bulgePinch = k(ba);
b.tiltShift = k(U);
b.dotScreen = k(Y);
b.edgeWork = k(Z);
b.lensBlur = k(T);
b.zoomBlur = k(W);
b.noise = k(O);
b.denoise = k(M);
b.curves = k(L);
b.swirl = k(ea);
b.ink = k(aa);
b.vignette = k(S);
b.vibrance = k(R);
b.sepia = k(P);
return b
};
u.splineInterpolate = s;
var l = function() {
function b(f, g) {
var h = a.createShader(f);
a.shaderSource(h, g);
a.compileShader(h);
if (!a.getShaderParameter(h, a.COMPILE_STATUS)) throw "compile error: " + a.getShaderInfoLog(h);
return h
}
function c(f, g) {
this.texCoordAttribute = this.vertexAttribute = null;
this.program = a.createProgram();
f = f || d;
g = g || e;
g = "precision highp float;" + g;
a.attachShader(this.program, b(a.VERTEX_SHADER, f));
a.attachShader(this.program, b(a.FRAGMENT_SHADER, g));
a.linkProgram(this.program);
if (!a.getProgramParameter(this.program, a.LINK_STATUS)) throw "link error: " + a.getProgramInfoLog(this.program);
}
var d = "attribute vec2 vertex;attribute vec2 _texCoord;varying vec2 texCoord;void main(){texCoord=_texCoord;gl_Position=vec4(vertex*2.0-1.0,0.0,1.0);}",
e = "uniform sampler2D texture;varying vec2 texCoord;void main(){gl_FragColor=texture2D(texture,texCoord);}";
c.prototype.destroy = function() {
a.deleteProgram(this.program);
this.program = null
};
c.prototype.uniforms = function(f) {
a.useProgram(this.program);
for (var g in f) if (f.hasOwnProperty(g)) {
var h = a.getUniformLocation(this.program, g);
if (h !== null) {
var i = f[g];
if (Object.prototype.toString.call(i) == "[object Array]") switch (i.length) {
case 1:
a.uniform1fv(h, new Float32Array(i));
break;
case 2:
a.uniform2fv(h, new Float32Array(i));
break;
case 3:
a.uniform3fv(h, new Float32Array(i));
break;
case 4:
a.uniform4fv(h, new Float32Array(i));
break;
case 9:
a.uniformMatrix3fv(h, false, new Float32Array(i));
break;
case 16:
a.uniformMatrix4fv(h, false, new Float32Array(i));
break;
default:
throw "dont't know how to load uniform \"" + g + '" of length ' + i.length;
} else if (Object.prototype.toString.call(i) == "[object Number]") a.uniform1f(h, i);
else throw 'attempted to set uniform "' + g + '" to invalid value ' + (i || "undefined")
.toString();
}
}
return this
};
c.prototype.textures = function(f) {
a.useProgram(this.program);
for (var g in f) f.hasOwnProperty(g) && a.uniform1i(a.getUniformLocation(this.program, g), f[g]);
return this
};
c.prototype.drawRect = function(f, g, h, i) {
var j = a.getParameter(a.VIEWPORT);
g = g !== void 0 ? (g - j[1]) / j[3] : 0;
f = f !== void 0 ? (f - j[0]) / j[2] : 0;
h = h !== void 0 ? (h - j[0]) / j[2] : 1;
i = i !== void 0 ? (i - j[1]) / j[3] : 1;
if (a.vertexBuffer == null) a.vertexBuffer = a.createBuffer();
a.bindBuffer(a.ARRAY_BUFFER, a.vertexBuffer);
a.bufferData(a.ARRAY_BUFFER, new Float32Array([f, g, f, i, h, g, h, i]), a.STATIC_DRAW);
if (a.texCoordBuffer == null) {
a.texCoordBuffer = a.createBuffer();
a.bindBuffer(a.ARRAY_BUFFER, a.texCoordBuffer);
a.bufferData(a.ARRAY_BUFFER, new Float32Array([0, 0, 0, 1, 1, 0, 1, 1]), a.STATIC_DRAW)
}
if (this.vertexAttribute == null) {
this.vertexAttribute = a.getAttribLocation(this.program, "vertex");
a.enableVertexAttribArray(this.vertexAttribute)
}
if (this.texCoordAttribute == null) {
this.texCoordAttribute = a.getAttribLocation(this.program, "_texCoord");
a.enableVertexAttribArray(this.texCoordAttribute)
}
a.useProgram(this.program);
a.bindBuffer(a.ARRAY_BUFFER, a.vertexBuffer);
a.vertexAttribPointer(this.vertexAttribute, 2, a.FLOAT, false, 0, 0);
a.bindBuffer(a.ARRAY_BUFFER, a.texCoordBuffer);
a.vertexAttribPointer(this.texCoordAttribute, 2, a.FLOAT, false, 0, 0);
a.drawArrays(a.TRIANGLE_STRIP, 0, 4)
};
c.getDefaultShader = function() {
a.defaultShader = a.defaultShader || new c;
return a.defaultShader
};
return c
}();
B.prototype.interpolate = function(b) {
for (var c = 0, d = this.ya.length - 1; d - c > 1;) {
var e = d + c >> 1;
if (this.xa[e] > b) d = e;
else c = e
}
e = this.xa[d] - this.xa[c];
var f = (this.xa[d] - b) / e;
b = (b - this.xa[c]) / e;
return f * this.ya[c] + b * this.ya[d] + ((f * f * f - f) * this.y2[c] + (b * b * b - b) * this.y2[d]) * e * e / 6
};
var r = function() {
function b(e, f, g, h) {
this.id = a.createTexture();
this.width = e;
this.height = f;
this.format = g;
this.type = h;
a.bindTexture(a.TEXTURE_2D, this.id);
a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MAG_FILTER, a.LINEAR);
a.texParameteri(a.TEXTURE_2D, a.TEXTURE_MIN_FILTER, a.LINEAR);
a.texParameteri(a.TEXTURE_2D, a.TEXTURE_WRAP_S, a.CLAMP_TO_EDGE);
a.texParameteri(a.TEXTURE_2D, a.TEXTURE_WRAP_T, a.CLAMP_TO_EDGE);
e && f && a.texImage2D(a.TEXTURE_2D, 0, this.format, e, f, 0, this.format, this.type, null)
}
function c(e) {
if (d == null) d = document.createElement("canvas");
d.width = e.width;
d.height = e.height;
e = d.getContext("2d");
e.clearRect(0, 0, d.width, d.height);
return e
}
b.fromElement = function(e) {
var f = new b(0, 0, a.RGBA, a.UNSIGNED_BYTE);
f.loadContentsOf(e);
return f
};
b.prototype.loadContentsOf = function(e) {
this.width = e.width || e.videoWidth;
this.height = e.height || e.videoHeight;
a.bindTexture(a.TEXTURE_2D, this.id);
a.texImage2D(a.TEXTURE_2D, 0, this.format, this.format, this.type, e)
};
b.prototype.initFromBytes = function(e, f, g) {
this.width = e;
this.height = f;
this.format = a.RGBA;
this.type = a.UNSIGNED_BYTE;
a.bindTexture(a.TEXTURE_2D, this.id);
a.texImage2D(a.TEXTURE_2D, 0, a.RGBA, e, f, 0, a.RGBA, this.type, new Uint8Array(g))
};
b.prototype.destroy = function() {
a.deleteTexture(this.id);
this.id = null
};
b.prototype.use = function(e) {
a.activeTexture(a.TEXTURE0 + (e || 0));
a.bindTexture(a.TEXTURE_2D, this.id)
};
b.prototype.unuse = function(e) {
a.activeTexture(a.TEXTURE0 + (e || 0));
a.bindTexture(a.TEXTURE_2D, null)
};
b.prototype.ensureFormat = function(e, f, g, h) {
if (arguments.length == 1) {
var i = arguments[0];
e = i.width;
f = i.height;
g = i.format;
h = i.type
}
if (e != this.width || f != this.height || g != this.format || h != this.type) {
this.width = e;
this.height = f;
this.format = g;
this.type = h;
a.bindTexture(a.TEXTURE_2D, this.id);
a.texImage2D(a.TEXTURE_2D, 0, this.format, e, f, 0, this.format, this.type, null)
}
};
b.prototype.drawTo = function(e) {
a.framebuffer = a.framebuffer || a.createFramebuffer();
a.bindFramebuffer(a.FRAMEBUFFER, a.framebuffer);
a.framebufferTexture2D(a.FRAMEBUFFER, a.COLOR_ATTACHMENT0, a.TEXTURE_2D, this.id, 0);
a.viewport(0, 0, this.width, this.height);
e();
a.bindFramebuffer(a.FRAMEBUFFER, null)
};
var d = null;
b.prototype.fillUsingCanvas = function(e) {
e(c(this));
this.format = a.RGBA;
this.type = a.UNSIGNED_BYTE;
a.bindTexture(a.TEXTURE_2D, this.id);
a.texImage2D(a.TEXTURE_2D, 0, a.RGBA, a.RGBA, a.UNSIGNED_BYTE, d);
return this
};
b.prototype.toImage = function(e) {
this.use();
l.getDefaultShader()
.drawRect();
var f = this.width * this.height * 4,
g = new Uint8Array(f),
h = c(this),
i = h.createImageData(this.width, this.height);
a.readPixels(0, 0, this.width, this.height, a.RGBA, a.UNSIGNED_BYTE, g);
for (var j = 0; j < f; j++) i.data[j] = g[j];
h.putImageData(i, 0, 0);
e.src = d.toDataURL()
};
b.prototype.swapWith = function(e) {
var f;
f = e.id;
e.id = this.id;
this.id = f;
f = e.width;
e.width = this.width;
this.width = f;
f = e.height;
e.height = this.height;
this.height = f;
f = e.format;
e.format = this.format;
this.format = f
};
return b
}(),
q = "float random(vec3 scale,float seed){return fract(sin(dot(gl_FragCoord.xyz+seed,scale))*43758.5453+seed);}";
return u
}();
(function(exports) {
var bitsToNum = function(ba) {
return ba.reduce(function(s, n) {
return s * 2 + n;
}, 0);
};
var byteToBitArr = function(bite) {
var a = [];
for (var i = 7; i >= 0; i--) {
a.push( !! (bite & (1 << i)));
}
return a;
};
var Stream = function(data) {
this.data = data;
this.len = this.data.length;
this.pos = 0;
this.readByte = function() {
if (this.pos >= this.data.length) {
throw new Error('Attempted to read past end of stream.');
}
return data.charCodeAt(this.pos++) & 0xFF;
};
this.readBytes = function(n) {
var bytes = [];
for (var i = 0; i < n; i++) {
bytes.push(this.readByte());
}
return bytes;
};
this.read = function(n) {
var s = '';
for (var i = 0; i < n; i++) {
s += String.fromCharCode(this.readByte());
}
return s;
};
this.readUnsigned = function() {
var a = this.readBytes(2);
return (a[1] << 8) + a[0];
};
};
var lzwDecode = function(minCodeSize, data) {
var pos = 0;
var readCode = function(size) {
var code = 0;
for (var i = 0; i < size; i++) {
if (data.charCodeAt(pos >> 3) & (1 << (pos & 7))) {
code |= 1 << i;
}
pos++;
}
return code;
};
var output = [];
var clearCode = 1 << minCodeSize;
var eoiCode = clearCode + 1;
var codeSize = minCodeSize + 1;
var dict = [];
var clear = function() {
dict = [];
codeSize = minCodeSize + 1;
for (var i = 0; i < clearCode; i++) {
dict[i] = [i];
}
dict[clearCode] = [];
dict[eoiCode] = null;
};
var code;
var last;
while (true) {
last = code;
code = readCode(codeSize);
if (code === clearCode) {
clear();
continue;
}
if (code === eoiCode) break;
if (code < dict.length) {
if (last !== clearCode) {
dict.push(dict[last].concat(dict[code][0]));
}
} else {
if (code !== dict.length) throw new Error('Invalid LZW code.');
dict.push(dict[last].concat(dict[last][0]));
}
output.push.apply(output, dict[code]);
if (dict.length === (1 << codeSize) && codeSize < 12) {
codeSize++;
}
}
return output;
};
var parseGIF = function(st, handler) {
handler || (handler = {});
var parseCT = function(entries) {
var ct = [];
for (var i = 0; i < entries; i++) {
ct.push(st.readBytes(3));
}
return ct;
};
var readSubBlocks = function() {
var size, data;
data = '';
do {
size = st.readByte();
data += st.read(size);
} while (size !== 0);
return data;
};
var parseHeader = function() {
var hdr = {};
hdr.sig = st.read(3);
hdr.ver = st.read(3);
if (hdr.sig !== 'GIF') throw new Error('Not a GIF file.');
hdr.width = st.readUnsigned();
hdr.height = st.readUnsigned();
var bits = byteToBitArr(st.readByte());
hdr.gctFlag = bits.shift();
hdr.colorRes = bitsToNum(bits.splice(0, 3));
hdr.sorted = bits.shift();
hdr.gctSize = bitsToNum(bits.splice(0, 3));
hdr.bgColor = st.readByte();
hdr.pixelAspectRatio = st.readByte();
if (hdr.gctFlag) {
hdr.gct = parseCT(1 << (hdr.gctSize + 1));
}
handler.hdr && handler.hdr(hdr);
};
var parseExt = function(block) {
var parseGCExt = function(block) {
var blockSize = st.readByte();
var bits = byteToBitArr(st.readByte());
block.reserved = bits.splice(0, 3);
block.disposalMethod = bitsToNum(bits.splice(0, 3));
block.userInput = bits.shift();
block.transparencyGiven = bits.shift();
block.delayTime = st.readUnsigned();
block.transparencyIndex = st.readByte();
block.terminator = st.readByte();
handler.gce && handler.gce(block);
};
var parseComExt = function(block) {
block.comment = readSubBlocks();
handler.com && handler.com(block);
};
var parsePTExt = function(block) {
var blockSize = st.readByte();
block.ptHeader = st.readBytes(12);
block.ptData = readSubBlocks();
handler.pte && handler.pte(block);
};
var parseAppExt = function(block) {
var parseNetscapeExt = function(block) {
var blockSize = st.readByte();
block.unknown = st.readByte();
block.iterations = st.readUnsigned();
block.terminator = st.readByte();
handler.app && handler.app.NETSCAPE && handler.app.NETSCAPE(block);
};
var parseUnknownAppExt = function(block) {
block.appData = readSubBlocks();
handler.app && handler.app[block.identifier] && handler.app[block.identifier](block);
};
var blockSize = st.readByte();
block.identifier = st.read(8);
block.authCode = st.read(3);
switch (block.identifier) {
case 'NETSCAPE':
parseNetscapeExt(block);
break;
default:
parseUnknownAppExt(block);
break;
}
};
var parseUnknownExt = function(block) {
block.data = readSubBlocks();
handler.unknown && handler.unknown(block);
};
block.label = st.readByte();
switch (block.label) {
case 0xF9:
block.extType = 'gce';
parseGCExt(block);
break;
case 0xFE:
block.extType = 'com';
parseComExt(block);
break;
case 0x01:
block.extType = 'pte';
parsePTExt(block);
break;
case 0xFF:
block.extType = 'app';
parseAppExt(block);
break;
default:
block.extType = 'unknown';
parseUnknownExt(block);
break;
}
};
var parseImg = function(img) {
var deinterlace = function(pixels, width) {
var newPixels = new Array(pixels.length);
var rows = pixels.length / width;
var cpRow = function(toRow, fromRow) {
var fromPixels = pixels.slice(fromRow * width, (fromRow + 1) * width);
newPixels.splice.apply(newPixels, [toRow * width, width].concat(fromPixels));
};
var offsets = [0, 4, 2, 1];
var steps = [8, 8, 4, 2];
var fromRow = 0;
for (var pass = 0; pass < 4; pass++) {
for (var toRow = offsets[pass]; toRow < rows; toRow += steps[pass]) {
cpRow(toRow, fromRow)
fromRow++;
}
}
return newPixels;
};
img.leftPos = st.readUnsigned();
img.topPos = st.readUnsigned();
img.width = st.readUnsigned();
img.height = st.readUnsigned();
var bits = byteToBitArr(st.readByte());
img.lctFlag = bits.shift();
img.interlaced = bits.shift();
img.sorted = bits.shift();
img.reserved = bits.splice(0, 2);
img.lctSize = bitsToNum(bits.splice(0, 3));
if (img.lctFlag) {
img.lct = parseCT(1 << (img.lctSize + 1));
}
img.lzwMinCodeSize = st.readByte();
var lzwData = readSubBlocks();
img.pixels = lzwDecode(img.lzwMinCodeSize, lzwData);
if (img.interlaced) {
img.pixels = deinterlace(img.pixels, img.width);
}
handler.img && handler.img(img);
};
var parseBlock = function() {
var block = {};
block.sentinel = st.readByte();
switch (String.fromCharCode(block.sentinel)) {
case '!':
block.type = 'ext';
parseExt(block);
break;
case ',':
block.type = 'img';
parseImg(block);
break;
case ';':
block.type = 'eof';
handler.eof && handler.eof(block);
break;
default:
throw new Error('Unknown block: 0x' + block.sentinel.toString(16));
}
if (block.type !== 'eof') setTimeout(parseBlock, 0);
};
var parse = function() {
parseHeader();
setTimeout(parseBlock, 0);
};
parse();
};
if (typeof exports !== 'undefined') {
exports.Stream = Stream;
exports.parseGIF = parseGIF;
}
})(window);
/*! getUserMedia - v0.1.0 - 2012-08-19
https://github.com/addyosmani/getUserMedia.js
Copyright (c) 2012 addyosmani; Licensed MIT */
;
(function(window, document) {
"use strict";
window.getUserMedia = function(options, successCallback, errorCallback) {
if (options !== undefined) {
navigator.getUserMedia_ = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
if ( !! navigator.getUserMedia_) {
var option_object = {};
var option_string = '';
var getUserMediaOptions, container, temp, video, ow, oh;
if (options.video === true) {
option_object.video = true;
option_string = 'video';
}
if (options.audio === true) {
option_object.audio = true;
if (option_string !== '') {
option_string = option_string + ', ';
}
option_string = option_string + 'audio';
}
container = document.getElementById(options.el);
temp = document.createElement('video');
ow = parseInt(container.offsetWidth, 10);
oh = parseInt(container.offsetHeight, 10);
if (options.width < ow && options.height < oh) {
options.width = ow;
options.height = oh;
}
temp.width = options.width;
temp.height = options.height;
temp.autoplay = true;
container.appendChild(temp);
video = temp;
options.videoEl = video;
options.context = 'webrtc';
try {
navigator.getUserMedia_(option_object, successCallback, errorCallback);
} catch (e) {
try {
navigator.getUserMedia_(option_string, successCallback, errorCallback);
} catch (e2) {
return undefined;
}
}
} else {
if (options.noFallback === undefined || options.noFallback === false) {
var source, el, cam;
source = '<object id="XwebcamXobjectX" type="application/x-shockwave-flash" data="' + options.swffile + '" width="' + options.width + '" height="' + options.height + '"><param name="movie" value="' + options.swffile + '" /><param name="FlashVars" value="mode=' + options.mode + '&quality=' + options.quality + '" /><param name="allowScriptAccess" value="always" /></object>';
el = document.getElementById(options.el);
el.innerHTML = source;
(function register(run) {
cam = document.getElementById('XwebcamXobjectX');
if (cam.capture !== undefined) {
options.capture = function(x) {
try {
return cam.capture(x);
} catch (e) {}
};
options.save = function(x) {
try {
return cam.save(x);
} catch (e) {}
};
options.setCamera = function(x) {
try {
return cam.setCamera(x);
} catch (e) {}
};
options.getCameraList = function() {
try {
return cam.getCameraList();
} catch (e) {}
};
options.context = 'flash';
options.onLoad = successCallback;
} else if (run === 0) {
errorCallback();
} else {
window.setTimeout(register, 1000 * (4 - run), run - 1);
}
}(3));
}
}
}
};
}(this, document));
/*!
FileReader.js - a lightweight wrapper for common FileReader usage.
Copyright 2012 Brian Grinstead - MIT License.
See http://github.com/bgrins/filereader.js for documentation.
*/
(function(window, document) {
var FileReader = window.FileReader;
var FileReaderSyncSupport = false;
var workerScript = "self.addEventListener('message', function(e) { var data=e.data; try { var reader = new FileReaderSync; postMessage({ result: reader[data.readAs](data.file), extra: data.extra, file: data.file})} catch(e){ postMessage({ result:'error', extra:data.extra, file:data.file}); } }, false);";
var syncDetectionScript = "self.addEventListener('message', function(e) { postMessage(!!FileReaderSync); }, false);";
var fileReaderEvents = ['loadstart', 'progress', 'load', 'abort', 'error', 'loadend'];
var FileReaderJS = window.FileReaderJS = {
enabled: false,
setupInput: setupInput,
setupDrop: setupDrop,
setupClipboard: setupClipboard,
sync: false,
output: [],
opts: {
dragClass: "drag",
accept: false,
readAsDefault: 'BinaryString',
readAsMap: {
'image/*': 'DataURL',
'text/*': 'Text'
},
on: {
loadstart: noop,
progress: noop,
load: noop,
abort: noop,
error: noop,
loadend: noop,
skip: noop,
groupstart: noop,
groupend: noop,
beforestart: noop
}
}
};
if (typeof(jQuery) !== "undefined") {
jQuery.fn.fileReaderJS = function(opts) {
return this.each(function() {
$(this)
.is("input") ? setupInput(this, opts) : setupDrop(this, opts);
});
};
jQuery.fn.fileClipboard = function(opts) {
return this.each(function() {
setupClipboard(this, opts);
});
};
}
if (!FileReader) {
return;
}
var WorkerHelper = (function() {
var URL = window.URL || window.webkitURL;
var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
function getURL(script) {
if (window.Worker && BlobBuilder && URL) {
var bb = new BlobBuilder();
bb.append(script);
return URL.createObjectURL(bb.getBlob());
}
return null;
};
function getWorker(script, onmessage) {
var url = getURL(script);
if (url) {
var worker = new Worker(url);
worker.onmessage = onmessage;
return worker;
}
return null;
};
return {
getURL: getURL,
getWorker: getWorker
};
})();
function setupClipboard(element, opts) {
if (!FileReaderJS.enabled) {
return;
}
var instanceOptions = extend(extend({}, FileReaderJS.opts), opts);
element.addEventListener("paste", onpaste, false);
function onpaste(e) {
var files = [];
var clipboardData = e.clipboardData || {};
var items = clipboardData.items || [];
for (var i = 0; i < items.length; i++) {
var file = items[i].getAsFile();
if (file) {
var matches = new RegExp("/\(.*\)")
.exec(file.type);
if (!file.name && matches) {
var extension = matches[1];
file.name = "clipboard" + i + "." + extension;
}
files.push(file);
}
}
if (files.length) {
processFileList(files, instanceOptions);
e.preventDefault();
e.stopPropagation();
}
}
};
function setupInput(input, opts) {
if (!FileReaderJS.enabled) {
return;
}
var instanceOptions = extend(extend({}, FileReaderJS.opts), opts);
input.addEventListener("change", inputChange, false);
input.addEventListener("drop", inputDrop, false);
function inputChange(e) {
processFileList(input.files, instanceOptions);
}
function inputDrop(e) {
e.stopPropagation();
e.preventDefault();
processFileList(e.dataTransfer.files, instanceOptions);
}
}
function setupDrop(dropbox, opts) {
if (!FileReaderJS.enabled) {
return;
}
var instanceOptions = extend(extend({}, FileReaderJS.opts), opts);
var dragClass = instanceOptions.dragClass;
var initializedOnBody = false;
dropbox.addEventListener("dragenter", onlyWithFiles(dragenter), false);
dropbox.addEventListener("dragleave", onlyWithFiles(dragleave), false);
dropbox.addEventListener("dragover", onlyWithFiles(dragover), false);
dropbox.addEventListener("drop", onlyWithFiles(drop), false);
document.body.addEventListener("dragstart", bodydragstart, true);
document.body.addEventListener("dragend", bodydragend, true);
document.body.addEventListener("drop", bodydrop, false);
function bodydragend(e) {
initializedOnBody = false;
}
function bodydragstart(e) {
initializedOnBody = true;
}
function bodydrop(e) {
if (e.dataTransfer.files && e.dataTransfer.files.length) {
e.stopPropagation();
e.preventDefault();
}
}
function onlyWithFiles(fn) {
return function() {
if (!initializedOnBody) {
fn.apply(this, arguments);
}
};
}
function drop(e) {
e.stopPropagation();
e.preventDefault();
if (dragClass) {
removeClass(dropbox, dragClass);
}
processFileList(e.dataTransfer.files, instanceOptions);
}
function dragenter(e) {
e.stopPropagation();
e.preventDefault();
if (dragClass) {
addClass(dropbox, dragClass);
}
}
function dragleave(e) {
if (dragClass) {
removeClass(dropbox, dragClass);
}
}
function dragover(e) {
e.stopPropagation();
e.preventDefault();
if (dragClass) {
addClass(dropbox, dragClass);
}
}
}
function setupCustomFileProperties(files, groupID) {
for (var i = 0; i < files.length; i++) {
var file = files[i];
file.extra = {
nameNoExtension: file.name.substring(0, file.name.lastIndexOf('.')),
extension: file.name.substring(file.name.lastIndexOf('.') + 1),
fileID: i,
uniqueID: getUniqueID(),
groupID: groupID,
prettySize: prettySize(file.size)
};
}
}
function getReadAsMethod(type, readAsMap, readAsDefault) {
for (var r in readAsMap) {
if (type.match(new RegExp(r))) {
return 'readAs' + readAsMap[r];
}
}
return 'readAs' + readAsDefault;
}
function processFileList(files, opts) {
var filesLeft = files.length;
var group = {
groupID: getGroupID(),
files: files,
started: new Date()
};
function groupEnd() {
group.ended = new Date();
opts.on.groupend(group);
}
function groupFileDone() {
if (--filesLeft == 0) {
groupEnd();
}
}
FileReaderJS.output.push(group);
setupCustomFileProperties(files, group.groupID);
opts.on.groupstart(group);
if (!files.length) {
groupEnd();
return;
}
var sync = FileReaderJS.sync && FileReaderSyncSupport;
var syncWorker;
if (sync) {
syncWorker = WorkerHelper.getWorker(workerScript, function(e) {
var file = e.data.file;
var result = e.data.result;
if (!file.extra) {
file.extra = e.data.extra;
}
file.extra.ended = new Date();
opts.on[result === "error" ? "error" : "load"]({
target: {
result: result
}
}, file);
groupFileDone();
});
}
Array.prototype.forEach.call(files, function(file) {
file.extra.started = new Date();
if (window.DEVELOPMENT) {
var URL = window.URL || window.webkitURL;
if (URL && file.type.match("image/gif") && window.GLOBALGIFLOADER) {
GLOBALGIFLOADER(window.URL.createObjectURL(file));
return;
}
}
if (opts.accept && !file.type.match(new RegExp(opts.accept))) {
opts.on.skip(file);
groupFileDone();
return;
}
if (opts.on.beforestart(file) === false) {
opts.on.skip(file);
groupFileDone();
return;
}
var readAs = getReadAsMethod(file.type, opts.readAsMap, opts.readAsDefault);
if (sync && syncWorker) {
syncWorker.postMessage({
file: file,
extra: file.extra,
readAs: readAs
});
} else {
var reader = new FileReader();
fileReaderEvents.forEach(function(eventName) {
reader['on' + eventName] = function(e) {
if (eventName == 'load' || eventName == 'error') {
file.extra.ended = new Date();
}
opts.on[eventName](e, file);
if (eventName == 'loadend') {
groupFileDone();
}
};
});
reader[readAs](file);
}
});
}
function checkFileReaderSyncSupport() {
return false;
var worker = WorkerHelper.getWorker(syncDetectionScript, function(e) {
FileReaderSyncSupport = e.data;
});
if (worker) {
worker.postMessage();
}
}
function noop() {}
function extend(destination, source) {
for (var property in source) {
if (source[property] && source[property].constructor && source[property].constructor === Object) {
destination[property] = destination[property] || {};
arguments.callee(destination[property], source[property]);
} else {
destination[property] = source[property];
}
}
return destination;
}
function hasClass(el, name) {
return new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)")
.test(el.className);
}
function addClass(el, name) {
if (!hasClass(el, name)) {
el.className = el.className ? [el.className, name].join(' ') : name;
}
}
function removeClass(el, name) {
if (hasClass(el, name)) {
var c = el.className;
el.className = c.replace(new RegExp("(?:^|\\s+)" + name + "(?:\\s+|$)", "g"), " ")
.replace(/^\s\s*/, '')
.replace(/\s\s*$/, '');
}
}
function prettySize(bytes) {
var s = ['bytes', 'kb', 'MB', 'GB', 'TB', 'PB'];
var e = Math.floor(Math.log(bytes) / Math.log(1024));
return (bytes / Math.pow(1024, Math.floor(e)))
.toFixed(2) + " " + s[e];
}
var getGroupID = (function(id) {
return function() {
return id++;
}
})(0);
var getUniqueID = (function(id) {
return function() {
return id++;
}
})(0);
FileReaderJS.enabled = true;
checkFileReaderSyncSupport();
})(this, document);
this.Handlebars = {};
(function(Handlebars) {
Handlebars.VERSION = "1.0.rc.1";
Handlebars.helpers = {};
Handlebars.partials = {};
Handlebars.registerHelper = function(name, fn, inverse) {
if (inverse) {
fn.not = inverse;
}
this.helpers[name] = fn;
};
Handlebars.registerPartial = function(name, str) {
this.partials[name] = str;
};
Handlebars.registerHelper('helperMissing', function(arg) {
if (arguments.length === 2) {
return undefined;
} else {
throw new Error("Could not find property '" + arg + "'");
}
});
var toString = Object.prototype.toString,
functionType = "[object Function]";
Handlebars.registerHelper('blockHelperMissing', function(context, options) {
var inverse = options.inverse || function() {}, fn = options.fn;
var ret = "";
var type = toString.call(context);
if (type === functionType) {
context = context.call(this);
}
if (context === true) {
return fn(this);
} else if (context === false || context == null) {
return inverse(this);
} else if (type === "[object Array]") {
if (context.length > 0) {
return Handlebars.helpers.each(context, options);
} else {
return inverse(this);
}
} else {
return fn(context);
}
});
Handlebars.K = function() {};
Handlebars.createFrame = Object.create || function(object) {
Handlebars.K.prototype = object;
var obj = new Handlebars.K();
Handlebars.K.prototype = null;
return obj;
};
Handlebars.registerHelper('each', function(context, options) {
var fn = options.fn,
inverse = options.inverse;
var ret = "",
data;
if (options.data) {
data = Handlebars.createFrame(options.data);
}
if (context && context.length > 0) {
for (var i = 0, j = context.length; i < j; i++) {
if (data) {
data.index = i;
}
ret = ret + fn(context[i], {
data: data
});
}
} else {
ret = inverse(this);
}
return ret;
});
Handlebars.registerHelper('if', function(context, options) {
var type = toString.call(context);
if (type === functionType) {
context = context.call(this);
}
if (!context || Handlebars.Utils.isEmpty(context)) {
return options.inverse(this);
} else {
return options.fn(this);
}
});
Handlebars.registerHelper('unless', function(context, options) {
var fn = options.fn,
inverse = options.inverse;
options.fn = inverse;
options.inverse = fn;
return Handlebars.helpers['if'].call(this, context, options);
});
Handlebars.registerHelper('with', function(context, options) {
return options.fn(context);
});
Handlebars.registerHelper('log', function(context) {
Handlebars.log(context);
});
}(this.Handlebars));;
var handlebars = (function() {
var parser = {
trace: function trace() {},
yy: {},
symbols_: {
"error": 2,
"root": 3,
"program": 4,
"EOF": 5,
"statements": 6,
"simpleInverse": 7,
"statement": 8,
"openInverse": 9,
"closeBlock": 10,
"openBlock": 11,
"mustache": 12,
"partial": 13,
"CONTENT": 14,
"COMMENT": 15,
"OPEN_BLOCK": 16,
"inMustache": 17,
"CLOSE": 18,
"OPEN_INVERSE": 19,
"OPEN_ENDBLOCK": 20,
"path": 21,
"OPEN": 22,
"OPEN_UNESCAPED": 23,
"OPEN_PARTIAL": 24,
"params": 25,
"hash": 26,
"DATA": 27,
"param": 28,
"STRING": 29,
"INTEGER": 30,
"BOOLEAN": 31,
"hashSegments": 32,
"hashSegment": 33,
"ID": 34,
"EQUALS": 35,
"pathSegments": 36,
"SEP": 37,
"$accept": 0,
"$end": 1
},
terminals_: {
2: "error",
5: "EOF",
14: "CONTENT",
15: "COMMENT",
16: "OPEN_BLOCK",
18: "CLOSE",
19: "OPEN_INVERSE",
20: "OPEN_ENDBLOCK",
22: "OPEN",
23: "OPEN_UNESCAPED",
24: "OPEN_PARTIAL",
27: "DATA",
29: "STRING",
30: "INTEGER",
31: "BOOLEAN",
34: "ID",
35: "EQUALS",
37: "SEP"
},
productions_: [0, [3, 2],
[4, 3],
[4, 1],
[4, 0],
[6, 1],
[6, 2],
[8, 3],
[8, 3],
[8, 1],
[8, 1],
[8, 1],
[8, 1],
[11, 3],
[9, 3],
[10, 3],
[12, 3],
[12, 3],
[13, 3],
[13, 4],
[7, 2],
[17, 3],
[17, 2],
[17, 2],
[17, 1],
[17, 1],
[25, 2],
[25, 1],
[28, 1],
[28, 1],
[28, 1],
[28, 1],
[28, 1],
[26, 1],
[32, 2],
[32, 1],
[33, 3],
[33, 3],
[33, 3],
[33, 3],
[33, 3],
[21, 1],
[36, 3],
[36, 1]
],
performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) {
var $0 = $$.length - 1;
switch (yystate) {
case 1:
return $$[$0 - 1];
break;
case 2:
this.$ = new yy.ProgramNode($$[$0 - 2], $$[$0]);
break;
case 3:
this.$ = new yy.ProgramNode($$[$0]);
break;
case 4:
this.$ = new yy.ProgramNode([]);
break;
case 5:
this.$ = [$$[$0]];
break;
case 6:
$$[$0 - 1].push($$[$0]);
this.$ = $$[$0 - 1];
break;
case 7:
this.$ = new yy.BlockNode($$[$0 - 2], $$[$0 - 1].inverse, $$[$0 - 1], $$[$0]);
break;
case 8:
this.$ = new yy.BlockNode($$[$0 - 2], $$[$0 - 1], $$[$0 - 1].inverse, $$[$0]);
break;
case 9:
this.$ = $$[$0];
break;
case 10:
this.$ = $$[$0];
break;
case 11:
this.$ = new yy.ContentNode($$[$0]);
break;
case 12:
this.$ = new yy.CommentNode($$[$0]);
break;
case 13:
this.$ = new yy.MustacheNode($$[$0 - 1][0], $$[$0 - 1][1]);
break;
case 14:
this.$ = new yy.MustacheNode($$[$0 - 1][0], $$[$0 - 1][1]);
break;
case 15:
this.$ = $$[$0 - 1];
break;
case 16:
this.$ = new yy.MustacheNode($$[$0 - 1][0], $$[$0 - 1][1]);
break;
case 17:
this.$ = new yy.MustacheNode($$[$0 - 1][0], $$[$0 - 1][1], true);
break;
case 18:
this.$ = new yy.PartialNode($$[$0 - 1]);
break;
case 19:
this.$ = new yy.PartialNode($$[$0 - 2], $$[$0 - 1]);
break;
case 20:
break;
case 21:
this.$ = [
[$$[$0 - 2]].concat($$[$0 - 1]), $$[$0]
];
break;
case 22:
this.$ = [
[$$[$0 - 1]].concat($$[$0]), null];
break;
case 23:
this.$ = [
[$$[$0 - 1]], $$[$0]
];
break;
case 24:
this.$ = [
[$$[$0]], null];
break;
case 25:
this.$ = [
[new yy.DataNode($$[$0])], null];
break;
case 26:
$$[$0 - 1].push($$[$0]);
this.$ = $$[$0 - 1];
break;
case 27:
this.$ = [$$[$0]];
break;
case 28:
this.$ = $$[$0];
break;
case 29:
this.$ = new yy.StringNode($$[$0]);
break;
case 30:
this.$ = new yy.IntegerNode($$[$0]);
break;
case 31:
this.$ = new yy.BooleanNode($$[$0]);
break;
case 32:
this.$ = new yy.DataNode($$[$0]);
break;
case 33:
this.$ = new yy.HashNode($$[$0]);
break;
case 34:
$$[$0 - 1].push($$[$0]);
this.$ = $$[$0 - 1];
break;
case 35:
this.$ = [$$[$0]];
break;
case 36:
this.$ = [$$[$0 - 2], $$[$0]];
break;
case 37:
this.$ = [$$[$0 - 2], new yy.StringNode($$[$0])];
break;
case 38:
this.$ = [$$[$0 - 2], new yy.IntegerNode($$[$0])];
break;
case 39:
this.$ = [$$[$0 - 2], new yy.BooleanNode($$[$0])];
break;
case 40:
this.$ = [$$[$0 - 2], new yy.DataNode($$[$0])];
break;
case 41:
this.$ = new yy.IdNode($$[$0]);
break;
case 42:
$$[$0 - 2].push($$[$0]);
this.$ = $$[$0 - 2];
break;
case 43:
this.$ = [$$[$0]];
break;
}
},
table: [{
3: 1,
4: 2,
5: [2, 4],
6: 3,
8: 4,
9: 5,
11: 6,
12: 7,
13: 8,
14: [1, 9],
15: [1, 10],
16: [1, 12],
19: [1, 11],
22: [1, 13],
23: [1, 14],
24: [1, 15]
}, {
1: [3]
}, {
5: [1, 16]
}, {
5: [2, 3],
7: 17,
8: 18,
9: 5,
11: 6,
12: 7,
13: 8,
14: [1, 9],
15: [1, 10],
16: [1, 12],
19: [1, 19],
20: [2, 3],
22: [1, 13],
23: [1, 14],
24: [1, 15]
}, {
5: [2, 5],
14: [2, 5],
15: [2, 5],
16: [2, 5],
19: [2, 5],
20: [2, 5],
22: [2, 5],
23: [2, 5],
24: [2, 5]
}, {
4: 20,
6: 3,
8: 4,
9: 5,
11: 6,
12: 7,
13: 8,
14: [1, 9],
15: [1, 10],
16: [1, 12],
19: [1, 11],
20: [2, 4],
22: [1, 13],
23: [1, 14],
24: [1, 15]
}, {
4: 21,
6: 3,
8: 4,
9: 5,
11: 6,
12: 7,
13: 8,
14: [1, 9],
15: [1, 10],
16: [1, 12],
19: [1, 11],
20: [2, 4],
22: [1, 13],
23: [1, 14],
24: [1, 15]
}, {
5: [2, 9],
14: [2, 9],
15: [2, 9],
16: [2, 9],
19: [2, 9],
20: [2, 9],
22: [2, 9],
23: [2, 9],
24: [2, 9]
}, {
5: [2, 10],
14: [2, 10],
15: [2, 10],
16: [2, 10],
19: [2, 10],
20: [2, 10],
22: [2, 10],
23: [2, 10],
24: [2, 10]
}, {
5: [2, 11],
14: [2, 11],
15: [2, 11],
16: [2, 11],
19: [2, 11],
20: [2, 11],
22: [2, 11],
23: [2, 11],
24: [2, 11]
}, {
5: [2, 12],
14: [2, 12],
15: [2, 12],
16: [2, 12],
19: [2, 12],
20: [2, 12],
22: [2, 12],
23: [2, 12],
24: [2, 12]
}, {
17: 22,
21: 23,
27: [1, 24],
34: [1, 26],
36: 25
}, {
17: 27,
21: 23,
27: [1, 24],
34: [1, 26],
36: 25
}, {
17: 28,
21: 23,
27: [1, 24],
34: [1, 26],
36: 25
}, {
17: 29,
21: 23,
27: [1, 24],
34: [1, 26],
36: 25
}, {
21: 30,
34: [1, 26],
36: 25
}, {
1: [2, 1]
}, {
6: 31,
8: 4,
9: 5,
11: 6,
12: 7,
13: 8,
14: [1, 9],
15: [1, 10],
16: [1, 12],
19: [1, 11],
22: [1, 13],
23: [1, 14],
24: [1, 15]
}, {
5: [2, 6],
14: [2, 6],
15: [2, 6],
16: [2, 6],
19: [2, 6],
20: [2, 6],
22: [2, 6],
23: [2, 6],
24: [2, 6]
}, {
17: 22,
18: [1, 32],
21: 23,
27: [1, 24],
34: [1, 26],
36: 25
}, {
10: 33,
20: [1, 34]
}, {
10: 35,
20: [1, 34]
}, {
18: [1, 36]
}, {
18: [2, 24],
21: 41,
25: 37,
26: 38,
27: [1, 45],
28: 39,
29: [1, 42],
30: [1, 43],
31: [1, 44],
32: 40,
33: 46,
34: [1, 47],
36: 25
}, {
18: [2, 25]
}, {
18: [2, 41],
27: [2, 41],
29: [2, 41],
30: [2, 41],
31: [2, 41],
34: [2, 41],
37: [1, 48]
}, {
18: [2, 43],
27: [2, 43],
29: [2, 43],
30: [2, 43],
31: [2, 43],
34: [2, 43],
37: [2, 43]
}, {
18: [1, 49]
}, {
18: [1, 50]
}, {
18: [1, 51]
}, {
18: [1, 52],
21: 53,
34: [1, 26],
36: 25
}, {
5: [2, 2],
8: 18,
9: 5,
11: 6,
12: 7,
13: 8,
14: [1, 9],
15: [1, 10],
16: [1, 12],
19: [1, 11],
20: [2, 2],
22: [1, 13],
23: [1, 14],
24: [1, 15]
}, {
14: [2, 20],
15: [2, 20],
16: [2, 20],
19: [2, 20],
22: [2, 20],
23: [2, 20],
24: [2, 20]
}, {
5: [2, 7],
14: [2, 7],
15: [2, 7],
16: [2, 7],
19: [2, 7],
20: [2, 7],
22: [2, 7],
23: [2, 7],
24: [2, 7]
}, {
21: 54,
34: [1, 26],
36: 25
}, {
5: [2, 8],
14: [2, 8],
15: [2, 8],
16: [2, 8],
19: [2, 8],
20: [2, 8],
22: [2, 8],
23: [2, 8],
24: [2, 8]
}, {
14: [2, 14],
15: [2, 14],
16: [2, 14],
19: [2, 14],
20: [2, 14],
22: [2, 14],
23: [2, 14],
24: [2, 14]
}, {
18: [2, 22],
21: 41,
26: 55,
27: [1, 45],
28: 56,
29: [1, 42],
30: [1, 43],
31: [1, 44],
32: 40,
33: 46,
34: [1, 47],
36: 25
}, {
18: [2, 23]
}, {
18: [2, 27],
27: [2, 27],
29: [2, 27],
30: [2, 27],
31: [2, 27],
34: [2, 27]
}, {
18: [2, 33],
33: 57,
34: [1, 58]
}, {
18: [2, 28],
27: [2, 28],
29: [2, 28],
30: [2, 28],
31: [2, 28],
34: [2, 28]
}, {
18: [2, 29],
27: [2, 29],
29: [2, 29],
30: [2, 29],
31: [2, 29],
34: [2, 29]
}, {
18: [2, 30],
27: [2, 30],
29: [2, 30],
30: [2, 30],
31: [2, 30],
34: [2, 30]
}, {
18: [2, 31],
27: [2, 31],
29: [2, 31],
30: [2, 31],
31: [2, 31],
34: [2, 31]
}, {
18: [2, 32],
27: [2, 32],
29: [2, 32],
30: [2, 32],
31: [2, 32],
34: [2, 32]
}, {
18: [2, 35],
34: [2, 35]
}, {
18: [2, 43],
27: [2, 43],
29: [2, 43],
30: [2, 43],
31: [2, 43],
34: [2, 43],
35: [1, 59],
37: [2, 43]
}, {
34: [1, 60]
}, {
14: [2, 13],
15: [2, 13],
16: [2, 13],
19: [2, 13],
20: [2, 13],
22: [2, 13],
23: [2, 13],
24: [2, 13]
}, {
5: [2, 16],
14: [2, 16],
15: [2, 16],
16: [2, 16],
19: [2, 16],
20: [2, 16],
22: [2, 16],
23: [2, 16],
24: [2, 16]
}, {
5: [2, 17],
14: [2, 17],
15: [2, 17],
16: [2, 17],
19: [2, 17],
20: [2, 17],
22: [2, 17],
23: [2, 17],
24: [2, 17]
}, {
5: [2, 18],
14: [2, 18],
15: [2, 18],
16: [2, 18],
19: [2, 18],
20: [2, 18],
22: [2, 18],
23: [2, 18],
24: [2, 18]
}, {
18: [1, 61]
}, {
18: [1, 62]
}, {
18: [2, 21]
}, {
18: [2, 26],
27: [2, 26],
29: [2, 26],
30: [2, 26],
31: [2, 26],
34: [2, 26]
}, {
18: [2, 34],
34: [2, 34]
}, {
35: [1, 59]
}, {
21: 63,
27: [1, 67],
29: [1, 64],
30: [1, 65],
31: [1, 66],
34: [1, 26],
36: 25
}, {
18: [2, 42],
27: [2, 42],
29: [2, 42],
30: [2, 42],
31: [2, 42],
34: [2, 42],
37: [2, 42]
}, {
5: [2, 19],
14: [2, 19],
15: [2, 19],
16: [2, 19],
19: [2, 19],
20: [2, 19],
22: [2, 19],
23: [2, 19],
24: [2, 19]
}, {
5: [2, 15],
14: [2, 15],
15: [2, 15],
16: [2, 15],
19: [2, 15],
20: [2, 15],
22: [2, 15],
23: [2, 15],
24: [2, 15]
}, {
18: [2, 36],
34: [2, 36]
}, {
18: [2, 37],
34: [2, 37]
}, {
18: [2, 38],
34: [2, 38]
}, {
18: [2, 39],
34: [2, 39]
}, {
18: [2, 40],
34: [2, 40]
}],
defaultActions: {
16: [2, 1],
24: [2, 25],
38: [2, 23],
55: [2, 21]
},
parseError: function parseError(str, hash) {
throw new Error(str);
},
parse: function parse(input) {
var self = this,
stack = [0],
vstack = [null],
lstack = [],
table = this.table,
yytext = "",
yylineno = 0,
yyleng = 0,
recovering = 0,
TERROR = 2,
EOF = 1;
this.lexer.setInput(input);
this.lexer.yy = this.yy;
this.yy.lexer = this.lexer;
this.yy.parser = this;
if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
var yyloc = this.lexer.yylloc;
lstack.push(yyloc);
var ranges = this.lexer.options && this.lexer.options.ranges;
if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
function popStack(n) {
stack.length = stack.length - 2 * n;
vstack.length = vstack.length - n;
lstack.length = lstack.length - n;
}
function lex() {
var token;
token = self.lexer.lex() || 1;
if (typeof token !== "number") {
token = self.symbols_[token] || token;
}
return token;
}
var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected;
while (true) {
state = stack[stack.length - 1];
if (this.defaultActions[state]) {
action = this.defaultActions[state];
} else {
if (symbol === null || typeof symbol == "undefined") {
symbol = lex();
}
action = table[state] && table[state][symbol];
}
if (typeof action === "undefined" || !action.length || !action[0]) {
var errStr = "";
if (!recovering) {
expected = [];
for (p in table[state])
if (this.terminals_[p] && p > 2) {
expected.push("'" + this.terminals_[p] + "'");
}
if (this.lexer.showPosition) {
errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
} else {
errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
}
this.parseError(errStr, {
text: this.lexer.match,
token: this.terminals_[symbol] || symbol,
line: this.lexer.yylineno,
loc: yyloc,
expected: expected
});
}
}
if (action[0] instanceof Array && action.length > 1) {
throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
}
switch (action[0]) {
case 1:
stack.push(symbol);
vstack.push(this.lexer.yytext);
lstack.push(this.lexer.yylloc);
stack.push(action[1]);
symbol = null;
if (!preErrorSymbol) {
yyleng = this.lexer.yyleng;
yytext = this.lexer.yytext;
yylineno = this.lexer.yylineno;
yyloc = this.lexer.yylloc;
if (recovering > 0) recovering--;
} else {
symbol = preErrorSymbol;
preErrorSymbol = null;
}
break;
case 2:
len = this.productions_[action[1]][1];
yyval.$ = vstack[vstack.length - len];
yyval._$ = {
first_line: lstack[lstack.length - (len || 1)].first_line,
last_line: lstack[lstack.length - 1].last_line,
first_column: lstack[lstack.length - (len || 1)].first_column,
last_column: lstack[lstack.length - 1].last_column
};
if (ranges) {
yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
}
r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
if (typeof r !== "undefined") {
return r;
}
if (len) {
stack = stack.slice(0, - 1 * len * 2);
vstack = vstack.slice(0, - 1 * len);
lstack = lstack.slice(0, - 1 * len);
}
stack.push(this.productions_[action[1]][0]);
vstack.push(yyval.$);
lstack.push(yyval._$);
newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
stack.push(newState);
break;
case 3:
return true;
}
}
return true;
}
};
var lexer = (function() {
var lexer = ({
EOF: 1,
parseError: function parseError(str, hash) {
if (this.yy.parser) {
this.yy.parser.parseError(str, hash);
} else {
throw new Error(str);
}
},
setInput: function(input) {
this._input = input;
this._more = this._less = this.done = false;
this.yylineno = this.yyleng = 0;
this.yytext = this.matched = this.match = '';
this.conditionStack = ['INITIAL'];
this.yylloc = {
first_line: 1,
first_column: 0,
last_line: 1,
last_column: 0
};
if (this.options.ranges) this.yylloc.range = [0, 0];
this.offset = 0;
return this;
},
input: function() {
var ch = this._input[0];
this.yytext += ch;
this.yyleng++;
this.offset++;
this.match += ch;
this.matched += ch;
var lines = ch.match(/(?:\r\n?|\n).*/g);
if (lines) {
this.yylineno++;
this.yylloc.last_line++;
} else {
this.yylloc.last_column++;
}
if (this.options.ranges) this.yylloc.range[1]++;
this._input = this._input.slice(1);
return ch;
},
unput: function(ch) {
var len = ch.length;
var lines = ch.split(/(?:\r\n?|\n)/g);
this._input = ch + this._input;
this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
this.offset -= len;
var oldLines = this.match.split(/(?:\r\n?|\n)/g);
this.match = this.match.substr(0, this.match.length - 1);
this.matched = this.matched.substr(0, this.matched.length - 1);
if (lines.length - 1) this.yylineno -= lines.length - 1;
var r = this.yylloc.range;
this.yylloc = {
first_line: this.yylloc.first_line,
last_line: this.yylineno + 1,
first_column: this.yylloc.first_column,
last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len
};
if (this.options.ranges) {
this.yylloc.range = [r[0], r[0] + this.yyleng - len];
}
return this;
},
more: function() {
this._more = true;
return this;
},
less: function(n) {
this.unput(this.match.slice(n));
},
pastInput: function() {
var past = this.matched.substr(0, this.matched.length - this.match.length);
return (past.length > 20 ? '...' : '') + past.substr(-20)
.replace(/\n/g, "");
},
upcomingInput: function() {
var next = this.match;
if (next.length < 20) {
next += this._input.substr(0, 20 - next.length);
}
return (next.substr(0, 20) + (next.length > 20 ? '...' : ''))
.replace(/\n/g, "");
},
showPosition: function() {
var pre = this.pastInput();
var c = new Array(pre.length + 1)
.join("-");
return pre + this.upcomingInput() + "\n" + c + "^";
},
next: function() {
if (this.done) {
return this.EOF;
}
if (!this._input) this.done = true;
var token, match, tempMatch, index, col, lines;
if (!this._more) {
this.yytext = '';
this.match = '';
}
var rules = this._currentRules();
for (var i = 0; i < rules.length; i++) {
tempMatch = this._input.match(this.rules[rules[i]]);
if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
match = tempMatch;
index = i;
if (!this.options.flex) break;
}
}
if (match) {
lines = match[0].match(/(?:\r\n?|\n).*/g);
if (lines) this.yylineno += lines.length;
this.yylloc = {
first_line: this.yylloc.last_line,
last_line: this.yylineno + 1,
first_column: this.yylloc.last_column,
last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length
};
this.yytext += match[0];
this.match += match[0];
this.matches = match;
this.yyleng = this.yytext.length;
if (this.options.ranges) {
this.yylloc.range = [this.offset, this.offset += this.yyleng];
}
this._more = false;
this._input = this._input.slice(match[0].length);
this.matched += match[0];
token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
if (this.done && this._input) this.done = false;
if (token) return token;
else return;
}
if (this._input === "") {
return this.EOF;
} else {
return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), {
text: "",
token: null,
line: this.yylineno
});
}
},
lex: function lex() {
var r = this.next();
if (typeof r !== 'undefined') {
return r;
} else {
return this.lex();
}
},
begin: function begin(condition) {
this.conditionStack.push(condition);
},
popState: function popState() {
return this.conditionStack.pop();
},
_currentRules: function _currentRules() {
return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
},
topState: function() {
return this.conditionStack[this.conditionStack.length - 2];
},
pushState: function begin(condition) {
this.begin(condition);
}
});
lexer.options = {};
lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) {
var YYSTATE = YY_START
switch ($avoiding_name_collisions) {
case 0:
if (yy_.yytext.slice(-1) !== "\\") this.begin("mu");
if (yy_.yytext.slice(-1) === "\\") yy_.yytext = yy_.yytext.substr(0, yy_.yyleng - 1), this.begin("emu");
if (yy_.yytext) return 14;
break;
case 1:
return 14;
break;
case 2:
if (yy_.yytext.slice(-1) !== "\\") this.popState();
if (yy_.yytext.slice(-1) === "\\") yy_.yytext = yy_.yytext.substr(0, yy_.yyleng - 1);
return 14;
break;
case 3:
return 24;
break;
case 4:
return 16;
break;
case 5:
return 20;
break;
case 6:
return 19;
break;
case 7:
return 19;
break;
case 8:
return 23;
break;
case 9:
return 23;
break;
case 10:
yy_.yytext = yy_.yytext.substr(3, yy_.yyleng - 5);
this.popState();
return 15;
break;
case 11:
return 22;
break;
case 12:
return 35;
break;
case 13:
return 34;
break;
case 14:
return 34;
break;
case 15:
return 37;
break;
case 16:
break;
case 17:
this.popState();
return 18;
break;
case 18:
this.popState();
return 18;
break;
case 19:
yy_.yytext = yy_.yytext.substr(1, yy_.yyleng - 2)
.replace(/\\"/g, '"');
return 29;
break;
case 20:
yy_.yytext = yy_.yytext.substr(1, yy_.yyleng - 2)
.replace(/\\"/g, '"');
return 29;
break;
case 21:
yy_.yytext = yy_.yytext.substr(1);
return 27;
break;
case 22:
return 31;
break;
case 23:
return 31;
break;
case 24:
return 30;
break;
case 25:
return 34;
break;
case 26:
yy_.yytext = yy_.yytext.substr(1, yy_.yyleng - 2);
return 34;
break;
case 27:
return 'INVALID';
break;
case 28:
return 5;
break;
}
};
lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/, /^(?:[^\x00]+)/, /^(?:[^\x00]{2,}?(?=(\{\{|$)))/, /^(?:\{\{>)/, /^(?:\{\{#)/, /^(?:\{\{\/)/, /^(?:\{\{\^)/, /^(?:\{\{\s*else\b)/, /^(?:\{\{\{)/, /^(?:\{\{&)/, /^(?:\{\{![\s\S]*?\}\})/, /^(?:\{\{)/, /^(?:=)/, /^(?:\.(?=[} ]))/, /^(?:\.\.)/, /^(?:[\/.])/, /^(?:\s+)/, /^(?:\}\}\})/, /^(?:\}\})/, /^(?:"(\\["]|[^"])*")/, /^(?:'(\\[']|[^'])*')/, /^(?:@[a-zA-Z]+)/, /^(?:true(?=[}\s]))/, /^(?:false(?=[}\s]))/, /^(?:[0-9]+(?=[}\s]))/, /^(?:[a-zA-Z0-9_$-]+(?=[=}\s\/.]))/, /^(?:\[[^\]]*\])/, /^(?:.)/, /^(?:$)/];
lexer.conditions = {
"mu": {
"rules": [3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28],
"inclusive": false
},
"emu": {
"rules": [2],
"inclusive": false
},
"INITIAL": {
"rules": [0, 1, 28],
"inclusive": true
}
};
return lexer;
})()
parser.lexer = lexer;
function Parser() {
this.yy = {};
}
Parser.prototype = parser;
parser.Parser = Parser;
return new Parser;
})();
if (typeof require !== 'undefined' && typeof exports !== 'undefined') {
exports.parser = handlebars;
exports.Parser = handlebars.Parser;
exports.parse = function() {
return handlebars.parse.apply(handlebars, arguments);
}
exports.main = function commonjsMain(args) {
if (!args[1]) throw new Error('Usage: ' + args[0] + ' FILE');
var source, cwd;
if (typeof process !== 'undefined') {
source = require('fs')
.readFileSync(require('path')
.resolve(args[1]), "utf8");
} else {
source = require("file")
.path(require("file")
.cwd())
.join(args[1])
.read({
charset: "utf-8"
});
}
return exports.parser.parse(source);
}
if (typeof module !== 'undefined' && require.main === module) {
exports.main(typeof process !== 'undefined' ? process.argv.slice(1) : require("system")
.args);
}
};;
Handlebars.Parser = handlebars;
Handlebars.parse = function(string) {
Handlebars.Parser.yy = Handlebars.AST;
return Handlebars.Parser.parse(string);
};
Handlebars.print = function(ast) {
return new Handlebars.PrintVisitor()
.accept(ast);
};
Handlebars.logger = {
DEBUG: 0,
INFO: 1,
WARN: 2,
ERROR: 3,
level: 3,
log: function(level, str) {}
};
Handlebars.log = function(level, str) {
Handlebars.logger.log(level, str);
};;
(function() {
Handlebars.AST = {};
Handlebars.AST.ProgramNode = function(statements, inverse) {
this.type = "program";
this.statements = statements;
if (inverse) {
this.inverse = new Handlebars.AST.ProgramNode(inverse);
}
};
Handlebars.AST.MustacheNode = function(rawParams, hash, unescaped) {
this.type = "mustache";
this.escaped = !unescaped;
this.hash = hash;
var id = this.id = rawParams[0];
var params = this.params = rawParams.slice(1);
var eligibleHelper = this.eligibleHelper = id.isSimple;
this.isHelper = eligibleHelper && (params.length || hash);
};
Handlebars.AST.PartialNode = function(id, context) {
this.type = "partial";
this.id = id;
this.context = context;
};
var verifyMatch = function(open, close) {
if (open.original !== close.original) {
throw new Handlebars.Exception(open.original + " doesn't match " + close.original);
}
};
Handlebars.AST.BlockNode = function(mustache, program, inverse, close) {
verifyMatch(mustache.id, close);
this.type = "block";
this.mustache = mustache;
this.program = program;
this.inverse = inverse;
if (this.inverse && !this.program) {
this.isInverse = true;
}
};
Handlebars.AST.ContentNode = function(string) {
this.type = "content";
this.string = string;
};
Handlebars.AST.HashNode = function(pairs) {
this.type = "hash";
this.pairs = pairs;
};
Handlebars.AST.IdNode = function(parts) {
this.type = "ID";
this.original = parts.join(".");
var dig = [],
depth = 0;
for (var i = 0, l = parts.length; i < l; i++) {
var part = parts[i];
if (part === "..") {
depth++;
} else if (part === "." || part === "this") {
this.isScoped = true;
} else {
dig.push(part);
}
}
this.parts = dig;
this.string = dig.join('.');
this.depth = depth;
this.isSimple = parts.length === 1 && !this.isScoped && depth === 0;
};
Handlebars.AST.DataNode = function(id) {
this.type = "DATA";
this.id = id;
};
Handlebars.AST.StringNode = function(string) {
this.type = "STRING";
this.string = string;
};
Handlebars.AST.IntegerNode = function(integer) {
this.type = "INTEGER";
this.integer = integer;
};
Handlebars.AST.BooleanNode = function(bool) {
this.type = "BOOLEAN";
this.bool = bool;
};
Handlebars.AST.CommentNode = function(comment) {
this.type = "comment";
this.comment = comment;
};
})();;
Handlebars.Exception = function(message) {
var tmp = Error.prototype.constructor.apply(this, arguments);
for (var p in tmp) {
if (tmp.hasOwnProperty(p)) {
this[p] = tmp[p];
}
}
this.message = tmp.message;
};
Handlebars.Exception.prototype = new Error();
Handlebars.SafeString = function(string) {
this.string = string;
};
Handlebars.SafeString.prototype.toString = function() {
return this.string.toString();
};
(function() {
var escape = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"`": "`"
};
var badChars = /[&<>"'`]/g;
var possible = /[&<>"'`]/;
var escapeChar = function(chr) {
return escape[chr] || "&";
};
Handlebars.Utils = {
escapeExpression: function(string) {
if (string instanceof Handlebars.SafeString) {
return string.toString();
} else if (string == null || string === false) {
return "";
}
if (!possible.test(string)) {
return string;
}
return string.replace(badChars, escapeChar);
},
isEmpty: function(value) {
if (typeof value === "undefined") {
return true;
} else if (value === null) {
return true;
} else if (value === false) {
return true;
} else if (Object.prototype.toString.call(value) === "[object Array]" && value.length === 0) {
return true;
} else {
return false;
}
}
};
})();;
Handlebars.Compiler = function() {};
Handlebars.JavaScriptCompiler = function() {};
(function(Compiler, JavaScriptCompiler) {
Compiler.prototype = {
compiler: Compiler,
disassemble: function() {
var opcodes = this.opcodes,
opcode, out = [],
params, param;
for (var i = 0, l = opcodes.length; i < l; i++) {
opcode = opcodes[i];
if (opcode.opcode === 'DECLARE') {
out.push("DECLARE " + opcode.name + "=" + opcode.value);
} else {
params = [];
for (var j = 0; j < opcode.args.length; j++) {
param = opcode.args[j];
if (typeof param === "string") {
param = "\"" + param.replace("\n", "\\n") + "\"";
}
params.push(param);
}
out.push(opcode.opcode + " " + params.join(" "));
}
}
return out.join("\n");
},
guid: 0,
compile: function(program, options) {
this.children = [];
this.depths = {
list: []
};
this.options = options;
var knownHelpers = this.options.knownHelpers;
this.options.knownHelpers = {
'helperMissing': true,
'blockHelperMissing': true,
'each': true,
'if': true,
'unless': true,
'with': true,
'log': true
};
if (knownHelpers) {
for (var name in knownHelpers) {
this.options.knownHelpers[name] = knownHelpers[name];
}
}
return this.program(program);
},
accept: function(node) {
return this[node.type](node);
},
program: function(program) {
var statements = program.statements,
statement;
this.opcodes = [];
for (var i = 0, l = statements.length; i < l; i++) {
statement = statements[i];
this[statement.type](statement);
}
this.isSimple = l === 1;
this.depths.list = this.depths.list.sort(function(a, b) {
return a - b;
});
return this;
},
compileProgram: function(program) {
var result = new this.compiler()
.compile(program, this.options);
var guid = this.guid++,
depth;
this.usePartial = this.usePartial || result.usePartial;
this.children[guid] = result;
for (var i = 0, l = result.depths.list.length; i < l; i++) {
depth = result.depths.list[i];
if (depth < 2) {
continue;
} else {
this.addDepth(depth - 1);
}
}
return guid;
},
block: function(block) {
var mustache = block.mustache,
program = block.program,
inverse = block.inverse;
if (program) {
program = this.compileProgram(program);
}
if (inverse) {
inverse = this.compileProgram(inverse);
}
var type = this.classifyMustache(mustache);
if (type === "helper") {
this.helperMustache(mustache, program, inverse);
} else if (type === "simple") {
this.simpleMustache(mustache);
this.opcode('pushProgram', program);
this.opcode('pushProgram', inverse);
this.opcode('pushLiteral', '{}');
this.opcode('blockValue');
} else {
this.ambiguousMustache(mustache, program, inverse);
this.opcode('pushProgram', program);
this.opcode('pushProgram', inverse);
this.opcode('pushLiteral', '{}');
this.opcode('ambiguousBlockValue');
}
this.opcode('append');
},
hash: function(hash) {
var pairs = hash.pairs,
pair, val;
this.opcode('push', '{}');
for (var i = 0, l = pairs.length; i < l; i++) {
pair = pairs[i];
val = pair[1];
this.accept(val);
this.opcode('assignToHash', pair[0]);
}
},
partial: function(partial) {
var id = partial.id;
this.usePartial = true;
if (partial.context) {
this.ID(partial.context);
} else {
this.opcode('push', 'depth0');
}
this.opcode('invokePartial', id.original);
this.opcode('append');
},
content: function(content) {
this.opcode('appendContent', content.string);
},
mustache: function(mustache) {
var options = this.options;
var type = this.classifyMustache(mustache);
if (type === "simple") {
this.simpleMustache(mustache);
} else if (type === "helper") {
this.helperMustache(mustache);
} else {
this.ambiguousMustache(mustache);
}
if (mustache.escaped && !options.noEscape) {
this.opcode('appendEscaped');
} else {
this.opcode('append');
}
},
ambiguousMustache: function(mustache, program, inverse) {
var id = mustache.id,
name = id.parts[0];
this.opcode('getContext', id.depth);
this.opcode('pushProgram', program);
this.opcode('pushProgram', inverse);
this.opcode('invokeAmbiguous', name);
},
simpleMustache: function(mustache, program, inverse) {
var id = mustache.id;
if (id.type === 'DATA') {
this.DATA(id);
} else if (id.parts.length) {
this.ID(id);
} else {
this.addDepth(id.depth);
this.opcode('getContext', id.depth);
this.opcode('pushContext');
}
this.opcode('resolvePossibleLambda');
},
helperMustache: function(mustache, program, inverse) {
var params = this.setupFullMustacheParams(mustache, program, inverse),
name = mustache.id.parts[0];
if (this.options.knownHelpers[name]) {
this.opcode('invokeKnownHelper', params.length, name);
} else if (this.knownHelpersOnly) {
throw new Error("You specified knownHelpersOnly, but used the unknown helper " + name);
} else {
this.opcode('invokeHelper', params.length, name);
}
},
ID: function(id) {
this.addDepth(id.depth);
this.opcode('getContext', id.depth);
var name = id.parts[0];
if (!name) {
this.opcode('pushContext');
} else {
this.opcode('lookupOnContext', id.parts[0]);
}
for (var i = 1, l = id.parts.length; i < l; i++) {
this.opcode('lookup', id.parts[i]);
}
},
DATA: function(data) {
this.options.data = true;
this.opcode('lookupData', data.id);
},
STRING: function(string) {
this.opcode('pushString', string.string);
},
INTEGER: function(integer) {
this.opcode('pushLiteral', integer.integer);
},
BOOLEAN: function(bool) {
this.opcode('pushLiteral', bool.bool);
},
comment: function() {},
opcode: function(name) {
this.opcodes.push({
opcode: name,
args: [].slice.call(arguments, 1)
});
},
declare: function(name, value) {
this.opcodes.push({
opcode: 'DECLARE',
name: name,
value: value
});
},
addDepth: function(depth) {
if (isNaN(depth)) {
throw new Error("EWOT");
}
if (depth === 0) {
return;
}
if (!this.depths[depth]) {
this.depths[depth] = true;
this.depths.list.push(depth);
}
},
classifyMustache: function(mustache) {
var isHelper = mustache.isHelper;
var isEligible = mustache.eligibleHelper;
var options = this.options;
if (isEligible && !isHelper) {
var name = mustache.id.parts[0];
if (options.knownHelpers[name]) {
isHelper = true;
} else if (options.knownHelpersOnly) {
isEligible = false;
}
}
if (isHelper) {
return "helper";
} else if (isEligible) {
return "ambiguous";
} else {
return "simple";
}
},
pushParams: function(params) {
var i = params.length,
param;
while (i--) {
param = params[i];
if (this.options.stringParams) {
if (param.depth) {
this.addDepth(param.depth);
}
this.opcode('getContext', param.depth || 0);
this.opcode('pushStringParam', param.string);
} else {
this[param.type](param);
}
}
},
setupMustacheParams: function(mustache) {
var params = mustache.params;
this.pushParams(params);
if (mustache.hash) {
this.hash(mustache.hash);
} else {
this.opcode('pushLiteral', '{}');
}
return params;
},
setupFullMustacheParams: function(mustache, program, inverse) {
var params = mustache.params;
this.pushParams(params);
this.opcode('pushProgram', program);
this.opcode('pushProgram', inverse);
if (mustache.hash) {
this.hash(mustache.hash);
} else {
this.opcode('pushLiteral', '{}');
}
return params;
}
};
var Literal = function(value) {
this.value = value;
};
JavaScriptCompiler.prototype = {
nameLookup: function(parent, name, type) {
if (/^[0-9]+$/.test(name)) {
return parent + "[" + name + "]";
} else if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
return parent + "." + name;
} else {
return parent + "['" + name + "']";
}
},
appendToBuffer: function(string) {
if (this.environment.isSimple) {
return "return " + string + ";";
} else {
return "buffer += " + string + ";";
}
},
initializeBuffer: function() {
return this.quotedString("");
},
namespace: "Handlebars",
compile: function(environment, options, context, asObject) {
this.environment = environment;
this.options = options || {};
Handlebars.log(Handlebars.logger.DEBUG, this.environment.disassemble() + "\n\n");
this.name = this.environment.name;
this.isChild = !! context;
this.context = context || {
programs: [],
aliases: {}
};
this.preamble();
this.stackSlot = 0;
this.stackVars = [];
this.registers = {
list: []
};
this.compileStack = [];
this.compileChildren(environment, options);
var opcodes = environment.opcodes,
opcode;
this.i = 0;
for (l = opcodes.length; this.i < l; this.i++) {
opcode = opcodes[this.i];
if (opcode.opcode === 'DECLARE') {
this[opcode.name] = opcode.value;
} else {
this[opcode.opcode].apply(this, opcode.args);
}
}
return this.createFunctionContext(asObject);
},
nextOpcode: function() {
var opcodes = this.environment.opcodes,
opcode = opcodes[this.i + 1];
return opcodes[this.i + 1];
},
eat: function(opcode) {
this.i = this.i + 1;
},
preamble: function() {
var out = [];
if (!this.isChild) {
var namespace = this.namespace;
var copies = "helpers = helpers || " + namespace + ".helpers;";
if (this.environment.usePartial) {
copies = copies + " partials = partials || " + namespace + ".partials;";
}
if (this.options.data) {
copies = copies + " data = data || {};";
}
out.push(copies);
} else {
out.push('');
}
if (!this.environment.isSimple) {
out.push(", buffer = " + this.initializeBuffer());
} else {
out.push("");
}
this.lastContext = 0;
this.source = out;
},
createFunctionContext: function(asObject) {
var locals = this.stackVars.concat(this.registers.list);
if (locals.length > 0) {
this.source[1] = this.source[1] + ", " + locals.join(", ");
}
if (!this.isChild) {
var aliases = [];
for (var alias in this.context.aliases) {
this.source[1] = this.source[1] + ', ' + alias + '=' + this.context.aliases[alias];
}
}
if (this.source[1]) {
this.source[1] = "var " + this.source[1].substring(2) + ";";
}
if (!this.isChild) {
this.source[1] += '\n' + this.context.programs.join('\n') + '\n';
}
if (!this.environment.isSimple) {
this.source.push("return buffer;");
}
var params = this.isChild ? ["depth0", "data"] : ["Handlebars", "depth0", "helpers", "partials", "data"];
for (var i = 0, l = this.environment.depths.list.length; i < l; i++) {
params.push("depth" + this.environment.depths.list[i]);
}
if (asObject) {
params.push(this.source.join("\n "));
return Function.apply(this, params);
} else {
var functionSource = 'function ' + (this.name || '') + '(' + params.join(',') + ') {\n ' + this.source.join("\n ") + '}';
Handlebars.log(Handlebars.logger.DEBUG, functionSource + "\n\n");
return functionSource;
}
},
blockValue: function() {
this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing';
var params = ["depth0"];
this.setupParams(0, params);
this.replaceStack(function(current) {
params.splice(1, 0, current);
return current + " = blockHelperMissing.call(" + params.join(", ") + ")";
});
},
ambiguousBlockValue: function() {
this.context.aliases.blockHelperMissing = 'helpers.blockHelperMissing';
var params = ["depth0"];
this.setupParams(0, params);
var current = this.topStack();
params.splice(1, 0, current);
this.source.push("if (!" + this.lastHelper + ") { " + current + " = blockHelperMissing.call(" + params.join(", ") + "); }");
},
appendContent: function(content) {
this.source.push(this.appendToBuffer(this.quotedString(content)));
},
append: function() {
var local = this.popStack();
this.source.push("if(" + local + " || " + local + " === 0) { " + this.appendToBuffer(local) + " }");
if (this.environment.isSimple) {
this.source.push("else { " + this.appendToBuffer("''") + " }");
}
},
appendEscaped: function() {
var opcode = this.nextOpcode(),
extra = "";
this.context.aliases.escapeExpression = 'this.escapeExpression';
if (opcode && opcode.opcode === 'appendContent') {
extra = " + " + this.quotedString(opcode.args[0]);
this.eat(opcode);
}
this.source.push(this.appendToBuffer("escapeExpression(" + this.popStack() + ")" + extra));
},
getContext: function(depth) {
if (this.lastContext !== depth) {
this.lastContext = depth;
}
},
lookupOnContext: function(name) {
this.pushStack(this.nameLookup('depth' + this.lastContext, name, 'context'));
},
pushContext: function() {
this.pushStackLiteral('depth' + this.lastContext);
},
resolvePossibleLambda: function() {
this.context.aliases.functionType = '"function"';
this.replaceStack(function(current) {
return "typeof " + current + " === functionType ? " + current + "() : " + current;
});
},
lookup: function(name) {
this.replaceStack(function(current) {
return current + " == null || " + current + " === false ? " + current + " : " + this.nameLookup(current, name, 'context');
});
},
lookupData: function(id) {
this.pushStack(this.nameLookup('data', id, 'data'));
},
pushStringParam: function(string) {
this.pushStackLiteral('depth' + this.lastContext);
this.pushString(string);
},
pushString: function(string) {
this.pushStackLiteral(this.quotedString(string));
},
push: function(expr) {
this.pushStack(expr);
},
pushLiteral: function(value) {
this.pushStackLiteral(value);
},
pushProgram: function(guid) {
if (guid != null) {
this.pushStackLiteral(this.programExpression(guid));
} else {
this.pushStackLiteral(null);
}
},
invokeHelper: function(paramSize, name) {
this.context.aliases.helperMissing = 'helpers.helperMissing';
var helper = this.lastHelper = this.setupHelper(paramSize, name);
this.register('foundHelper', helper.name);
this.pushStack("foundHelper ? foundHelper.call(" + helper.callParams + ") " + ": helperMissing.call(" + helper.helperMissingParams + ")");
},
invokeKnownHelper: function(paramSize, name) {
var helper = this.setupHelper(paramSize, name);
this.pushStack(helper.name + ".call(" + helper.callParams + ")");
},
invokeAmbiguous: function(name) {
this.context.aliases.functionType = '"function"';
this.pushStackLiteral('{}');
var helper = this.setupHelper(0, name);
var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
this.register('foundHelper', helperName);
var nonHelper = this.nameLookup('depth' + this.lastContext, name, 'context');
var nextStack = this.nextStack();
this.source.push('if (foundHelper) { ' + nextStack + ' = foundHelper.call(' + helper.callParams + '); }');
this.source.push('else { ' + nextStack + ' = ' + nonHelper + '; ' + nextStack + ' = typeof ' + nextStack + ' === functionType ? ' + nextStack + '() : ' + nextStack + '; }');
},
invokePartial: function(name) {
var params = [this.nameLookup('partials', name, 'partial'), "'" + name + "'", this.popStack(), "helpers", "partials"];
if (this.options.data) {
params.push("data");
}
this.context.aliases.self = "this";
this.pushStack("self.invokePartial(" + params.join(", ") + ");");
},
assignToHash: function(key) {
var value = this.popStack();
var hash = this.topStack();
this.source.push(hash + "['" + key + "'] = " + value + ";");
},
compiler: JavaScriptCompiler,
compileChildren: function(environment, options) {
var children = environment.children,
child, compiler;
for (var i = 0, l = children.length; i < l; i++) {
child = children[i];
compiler = new this.compiler();
this.context.programs.push('');
var index = this.context.programs.length;
child.index = index;
child.name = 'program' + index;
this.context.programs[index] = compiler.compile(child, options, this.context);
}
},
programExpression: function(guid) {
this.context.aliases.self = "this";
if (guid == null) {
return "self.noop";
}
var child = this.environment.children[guid],
depths = child.depths.list,
depth;
var programParams = [child.index, child.name, "data"];
for (var i = 0, l = depths.length; i < l; i++) {
depth = depths[i];
if (depth === 1) {
programParams.push("depth0");
} else {
programParams.push("depth" + (depth - 1));
}
}
if (depths.length === 0) {
return "self.program(" + programParams.join(", ") + ")";
} else {
programParams.shift();
return "self.programWithDepth(" + programParams.join(", ") + ")";
}
},
register: function(name, val) {
this.useRegister(name);
this.source.push(name + " = " + val + ";");
},
useRegister: function(name) {
if (!this.registers[name]) {
this.registers[name] = true;
this.registers.list.push(name);
}
},
pushStackLiteral: function(item) {
this.compileStack.push(new Literal(item));
return item;
},
pushStack: function(item) {
this.source.push(this.incrStack() + " = " + item + ";");
this.compileStack.push("stack" + this.stackSlot);
return "stack" + this.stackSlot;
},
replaceStack: function(callback) {
var item = callback.call(this, this.topStack());
this.source.push(this.topStack() + " = " + item + ";");
return "stack" + this.stackSlot;
},
nextStack: function(skipCompileStack) {
var name = this.incrStack();
this.compileStack.push("stack" + this.stackSlot);
return name;
},
incrStack: function() {
this.stackSlot++;
if (this.stackSlot > this.stackVars.length) {
this.stackVars.push("stack" + this.stackSlot);
}
return "stack" + this.stackSlot;
},
popStack: function() {
var item = this.compileStack.pop();
if (item instanceof Literal) {
return item.value;
} else {
this.stackSlot--;
return item;
}
},
topStack: function() {
var item = this.compileStack[this.compileStack.length - 1];
if (item instanceof Literal) {
return item.value;
} else {
return item;
}
},
quotedString: function(str) {
return '"' + str.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r') + '"';
},
setupHelper: function(paramSize, name) {
var params = [];
this.setupParams(paramSize, params);
var foundHelper = this.nameLookup('helpers', name, 'helper');
return {
params: params,
name: foundHelper,
callParams: ["depth0"].concat(params)
.join(", "),
helperMissingParams: ["depth0", this.quotedString(name)].concat(params)
.join(", ")
};
},
setupParams: function(paramSize, params) {
var options = [],
contexts = [],
param, inverse, program;
options.push("hash:" + this.popStack());
inverse = this.popStack();
program = this.popStack();
if (program || inverse) {
if (!program) {
this.context.aliases.self = "this";
program = "self.noop";
}
if (!inverse) {
this.context.aliases.self = "this";
inverse = "self.noop";
}
options.push("inverse:" + inverse);
options.push("fn:" + program);
}
for (var i = 0; i < paramSize; i++) {
param = this.popStack();
params.push(param);
if (this.options.stringParams) {
contexts.push(this.popStack());
}
}
if (this.options.stringParams) {
options.push("contexts:[" + contexts.join(",") + "]");
}
if (this.options.data) {
options.push("data:data");
}
params.push("{" + options.join(",") + "}");
return params.join(", ");
}
};
var reservedWords = ("break else new var" + " case finally return void" + " catch for switch while" + " continue function this with" + " default if throw" + " delete in try" + " do instanceof typeof" + " abstract enum int short" + " boolean export interface static" + " byte extends long super" + " char final native synchronized" + " class float package throws" + " const goto private transient" + " debugger implements protected volatile" + " double import public let yield")
.split(" ");
var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
for (var i = 0, l = reservedWords.length; i < l; i++) {
compilerWords[reservedWords[i]] = true;
}
JavaScriptCompiler.isValidJavaScriptVariableName = function(name) {
if (!JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]+$/.test(name)) {
return true;
}
return false;
};
})(Handlebars.Compiler, Handlebars.JavaScriptCompiler);
Handlebars.precompile = function(string, options) {
options = options || {};
var ast = Handlebars.parse(string);
var environment = new Handlebars.Compiler()
.compile(ast, options);
return new Handlebars.JavaScriptCompiler()
.compile(environment, options);
};
Handlebars.compile = function(string, options) {
options = options || {};
var compiled;
function compile() {
var ast = Handlebars.parse(string);
var environment = new Handlebars.Compiler()
.compile(ast, options);
var templateSpec = new Handlebars.JavaScriptCompiler()
.compile(environment, options, undefined, true);
return Handlebars.template(templateSpec);
}
return function(context, options) {
if (!compiled) {
compiled = compile();
}
return compiled.call(this, context, options);
};
};;
Handlebars.VM = {
template: function(templateSpec) {
var container = {
escapeExpression: Handlebars.Utils.escapeExpression,
invokePartial: Handlebars.VM.invokePartial,
programs: [],
program: function(i, fn, data) {
var programWrapper = this.programs[i];
if (data) {
return Handlebars.VM.program(fn, data);
} else if (programWrapper) {
return programWrapper;
} else {
programWrapper = this.programs[i] = Handlebars.VM.program(fn);
return programWrapper;
}
},
programWithDepth: Handlebars.VM.programWithDepth,
noop: Handlebars.VM.noop
};
return function(context, options) {
options = options || {};
return templateSpec.call(container, Handlebars, context, options.helpers, options.partials, options.data);
};
},
programWithDepth: function(fn, data, $depth) {
var args = Array.prototype.slice.call(arguments, 2);
return function(context, options) {
options = options || {};
return fn.apply(this, [context, options.data || data].concat(args));
};
},
program: function(fn, data) {
return function(context, options) {
options = options || {};
return fn(context, options.data || data);
};
},
noop: function() {
return "";
},
invokePartial: function(partial, name, context, helpers, partials, data) {
var options = {
helpers: helpers,
partials: partials,
data: data
};
if (partial === undefined) {
throw new Handlebars.Exception("The partial " + name + " could not be found");
} else if (partial instanceof Function) {
return partial(context, options);
} else if (!Handlebars.compile) {
throw new Handlebars.Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
} else {
partials[name] = Handlebars.compile(partial, {
data: data !== undefined
});
return partials[name](context, options);
}
}
};
Handlebars.template = Handlebars.VM.template;;
function generateShareLinks(linkToShare, title) {
linkToShare = encodeURIComponent(linkToShare || '');
title = encodeURIComponent(title || '');
var shareLinks = [];
shareLinks.push("<a href='http://facebook.com/sharer.php?u=" + linkToShare + "&t=" + title + "' target='_blank'><span border='0' class='sprite facebook png tip' title='Post on facebook'alt='Facebook' /></a>");
shareLinks.push("<a href='http://twitter.com/?status=" + title + "%20%23asciigram%20-%20" + linkToShare + "' target='_blank'><span border='0' class='sprite twitter png tip' title='Tweet's alt='Twitter' /></a>");
shareLinks.push("<a href='http://pinterest.com/pin/create/button/?url=" + linkToShare + "&media=http://comorichweb.nko3.jit.su/logo.png&description=" + title + "' target='_blank'><span border='0' class='sprite pinterest png tip' title='Pin' alt='Twitter' /></a>");
return shareLinks.join("");
}
function Frame(obj) {
this.content = obj.content.replace(/ /g, " ")
.replace(/<br>/g, "\n");
this.timestamp = new Date(obj.timestamp)
.getTime();
this.date = new Date(this.timestamp);
}
function FilePlayer(file, player, cb) {
var filePlayer = this;
this.playing = false;
this.player = player || document.createElement("pre");
this.ontick = function() {};
this.onfinish = function() {};
file.preview(function(preview) {
if (!filePlayer.frames) {
filePlayer.player.textContent = preview.content;
}
});
file.frames(function(frames) {
filePlayer.frames = frames;
filePlayer.isImage = frames.length === 1;
cb(filePlayer);
});
}
FilePlayer.prototype.play = function(startFrame) {
var player = this.player;
if (this.isImage) {
player.textContent = this.frames[0].content;
return;
}
if (this.playing) {
return;
}
this.playing = true;
var vid = this;
var REFRESH_RATE = 50;
var speed = 1;
startFrame = Math.min(this.frames.length - 1, Math.max(startFrame, 0)) || 0;
var startTime = (new Date())
.getTime();
var currentTime = startTime - this.frames[startFrame].timestamp;
var currentTimeOffset = startTime - this.frames[0].timestamp;
var timeShift = currentTimeOffset - currentTime;
vid.ticks = startFrame;
var frames = this.frames;
function findFrame(time) {
time = time + timeShift;
for (var i = 0; i < frames.length; i++) {
if (frames[i].timestamp > time) {
return {
frame: frames[i],
index: i,
last: i === frames.length - 1
};
}
}
}
function play() {
if (!vid.playing) {
return;
}
currentTime = (new Date())
.getTime() - currentTimeOffset;
var currentFrame = findFrame(currentTime);
if (!currentFrame) {
vid.stop();
return;
}
var currentContent = currentFrame.frame.content;
vid.playing = true;
vid.ticks++;
$("#num-ticks")
.text(vid.ticks);
vid.setFrame(currentFrame.index);
if (currentFrame.last) {
vid.pause();
vid.currentFrame = 0;
vid.onfinish();
} else {
setTimeout(play, REFRESH_RATE);
}
}
play();
};
FilePlayer.prototype.getLength = function() {
if (this.isImage) {
return 0;
}
return this.frames.length;
};
FilePlayer.prototype.setFrame = function(i) {
var index = Math.min(this.frames.length - 1, Math.max(i, 0)) || 0;
var frame = this.frames[index];
if (frame) {
this.currentFrame = index;
this.player.textContent = frame.content;
this.ontick(frame.timestamp);
}
};
FilePlayer.prototype.pause = function() {
this.playing = false;
};
FilePlayer.prototype.stop = function() {
this.ticks = 0;
this.currentFrame = 0;
this.setFrame(0);
this.playing = false;
};
FilePlayer.prototype.getResolution = function() {
var frame = this.__frames[0];
var lines = frames.split("/n");
return [lines[0].length, lines.length];
};
function File(id, frames, player) {
this.previewloaded = false;
this.loaded = false;
this.id = id;
this.__frames = [];
this.__preview = [];
if (frames) {
this.setFrames(frames);
this.setPreview(frames[0]);
}
};
File.prototype.setPreview = function(preview) {
this.__preview = preview;
this.previewloaded = true;
};
File.prototype.setFrames = function(frames) {
var frames = _.map(frames, function(frame) {
return new Frame(frame);
});
this.__frames = _.sortBy(frames, function(f) {
return f.date;
});
this.loaded = true;
};
File.prototype.frames = function(cb) {
cb = cb || $.noop;
var that = this;
if (that.loaded) {
cb(that.__frames);
return;
}
$.get("/frames/" + this.id, function(resp) {
that.setFrames(resp.frames);
cb(that.__frames);
});
};
File.prototype.preview = function(cb) {
var that = this;
cb = cb || $.noop;
if (that.previewloaded) {
cb(that.__preview);
return;
}
if (typeof(this.id) != "string") {
return;
}
$.get("/preview/" + this.id, function(resp) {
that.setPreview(new Frame({
timestamp: new Date(),
content: resp
}));
cb(that.__preview);
});
};
File.prototype.sync = function(cb) {
cb = ($.isFunction(cb)) ? cb : $.noop;
var file = this;
var frames = file.__frames;
var id = file.id;
var ajax = $.post("/add", {
frames: JSON.stringify(frames),
id: id
});
ajax.always(function(resp) {
file.id = resp;
file.synced = true;
FileStore.savePermanent(file);
cb(resp);
})
};
File.prototype.getShareUrl = function() {
if (!this.synced) {
return "";
}
return window.FULL_APP_URL + "view/" + this.id;
}
var _filestore = [];
var FileStore = {
get: function() {
return _filestore;
},
getByID: function(id) {
return _.filter(FileStore.get(), function(f) {
return id == f.id;
})[0] || {};
},
push: function(file) {
_filestore.push(file);
},
savePermanent: function(file) {
var store = Store.get("previous-files") || [];
store.push(file.id);
Store.set("previous-files", store);
},
clear: function() {
_filestore = [];
}
};
var savedStore = Store.get("previous-files") || [];
_.each(savedStore, function(i) {
var file = new File(i);
file.synced = true;
FileStore.push(file);
});
var GLView = Backbone.View.extend({
WARP_SIZE: 140,
distorting: true,
initialize: function(opts) {
if (!opts.image) {
throw "No Image provided";
}
this.image = opts.image;
this.placeholder = $("#image-space");
this.asciiContainer = $("#imgascii");
try {
this.canvas = fx.canvas();
} catch (e) {
this.canvas = $([]);
return;
}
var that = this;
if (this.image[0].complete) {
this.setupGL();
} else {
this.image.on("load", function() {
that.setupGL();
});
}
},
stop: function() {
this.distorting = false;
this.placeholder.unbind("click mousemove");
$(this.canvas)
.remove();
},
toggle: function() {
this.distorting = !this.distorting;
},
start: function() {
this.distorting = true;
},
setupGL: function() {
var image = this.image[0];
var placeholder = this.placeholder;
var asciiContainer = this.asciiContainer;
var asciiWidth = asciiContainer.width();
$(image)
.width(asciiWidth);
var canvas = this.canvas;
$(image)
.show();
var texture = canvas.texture(image);
$(image)
.hide();
canvas.draw(texture)
.update();
var that = this;
$(placeholder)
.click(function(e) {
that.toggle();
});
var WARP_SIZE = this.WARP_SIZE;
$(placeholder)
.mousemove(function(e) {
if (that.distorting) {
var offset = $(placeholder)
.offset();
var x = e.pageX - offset.left;
var y = e.pageY - offset.top;
canvas.draw(texture)
.swirl(x, y, WARP_SIZE, 4)
.update();
Jscii.renderImage(canvas, asciiContainer[0]);
}
});
}
});
var AppView = Backbone.View.extend({
SEND_TO_SERVER: false,
RESOLUTION: 150,
currenFile: [],
thumbTemplate: Handlebars.compile($("#video-list")
.html()),
events: {
"click #save": "save",
"click .save-image": "saveImage",
"click #record": "toggleRecord",
"click #results li": "previewFile",
"click #webcam": "previewLiveVideo",
"click #show-image": "previewStillImage",
"click": "cancelPreview",
"click #snapshot": "takeSnapshot",
"change #quality": "changeResolution",
"click #sync": "syncCurrent",
"click #view-url": "highlightBox"
},
cancelPreview: function() {
$("body")
.removeClass("previewing");
},
previewFile: function(e, force) {
var file;
if ($.isFunction(e.preview)) {
file = e;
} else {
file = FileStore.getByID($(e.currentTarget)
.closest("li")
.data("id"));
}
if (!force && this.currentFile && file && (this.currentFile.id == file.id)) {
return;
}
if (file) {
if (this.player) {
this.player.stop();
}
this.GL.stop();
this.currentFile = file;
file.frames(function(frames) {
$("#play-controls")
.toggle(frames.length > 1);
});
$("#share-container")
.toggle( !! file.synced);
$("#sync")
.toggle(!file.synced);
$("#view-url")
.val(file.getShareUrl());
$("#view-url-link")
.attr("href", file.getShareUrl());
this.player = new FilePlayer(file, $("#imgascii")[0], function(player) {
FilePlayerView.setFilePlayer(player);
});
}
this.previewStillImage();
return false;
},
changeResolution: function() {
this.RESOLUTION = parseInt($("#quality")
.val()) || 10;
Jscii.setResolution(this.RESOLUTION);
},
toggleRecord: function() {
var record = $("#record");
if (!this.recording) {
FrameBuffer.clear();
record.addClass("btn-warning");
} else {
record.removeClass("btn-warning");
this.save();
}
this.recording = !this.recording;
},
getCurrentFrames: function() {
return FrameBuffer.get();
},
saveImage: function(e) {
var frame = $(e.currentTarget)
.closest(".gram-container")
.find("pre")
.html();
FrameBuffer.set(frame);
this.save();
},
addDataURLSnapshot: function(url) {
var that = this;
var img = new Image();
img.onload = function() {
var pre = $("<pre />");
App.asciiImage(img, pre[0]);
FrameBuffer.set(pre.html());
App.save();
};
img.src = url;
},
takeSnapshot: function(e) {
var frame = $("#videoascii")
.html();
FrameBuffer.set(frame);
this.save();
},
renderThumbs: function() {
var that = this;
var tmpl = that.thumbTemplate;
$("#results")
.empty();
_.each(FileStore.get(), function(file) {
file.preview(function(preview) {
var obj = {
id: file.id,
preview: preview.content
};
$("#results")
.append(tmpl(obj));
})
});
},
save: function() {
var frames = this.getCurrentFrames();
if (frames.length === 0) {
log("Error, no frames provided");
return;
}
var file = new File(guid(), frames);
FileStore.push(file);
this.previewFile(file);
this.renderThumbs();
},
syncCurrent: function() {
var that = this;
if (that.currentFile) {
that.currentFile.sync(function() {
that.renderThumbs();
that.previewFile(that.currentFile, true);
});
}
},
highlightBox: function() {
$("#view-url")
.select();
},
initialize: function() {
this.asciiLogo();
var that = this;
Jscii.renderVideo($('#video')[0], $('#videoascii')[0], function() {
$("body")
.addClass("webcam-enabled");
$(".never-enabled")
.remove();
that.previewLiveVideo();
FrameBuffer.clear();
}, function(markup) {
if (that.recording) {
FrameBuffer.add(markup);
}
});
this.renderThumbs();
FileReaderJS.setupDrop(document.body, this.fileReaderOpts);
FileReaderJS.setupClipboard(document.body, this.fileReaderOpts);
FileReaderJS.setupInput(document.getElementById('file-input'), this.fileReaderOpts);
FilePlayerView.init();
},
previewLiveVideo: function() {
$("body")
.removeClass("no-video")
.addClass("yes-video");
},
previewStillImage: function() {
$("body")
.removeClass("yes-video")
.addClass("no-video");
},
fileReaderOpts: {
accept: "image/*",
on: {
load: function(e, file) {
App.addDataURLSnapshot(e.target.result);
}
}
},
asciiLogo: function() {
var img = $("#logo");
var container = $("#imgascii")[0];
var that = this;
function onload() {
that.asciiImage(img[0], container, function() {
that.GL = new GLView({
image: $("#logo")
});
img.hide();
});
}
if (img[0].complete) {
onload();
} else {
img.on("load", onload);
}
},
asciiImage: function(image, container, cb) {
Jscii.renderImage(image, container, cb);
}
});
(function(files) {
$(document)
.on('click', '.popular-preview a.post', function(e) {
var lookup = $(this)
.closest('.popular-preview')
.data('id');
var url = $(this)
.data('url');
$.post(url + lookup);
return false;
});
})();
var FilePlayerView = {
_filePlayer: null,
autoPlay: true,
loop: true,
init: function(filePlayer) {
var pauseButton = this.pauseButton = $("#player-pause");
var playButton = this.playButton = $("#player-play");
var restartButton = $("#player-restart");
var that = this;
var getFilePlayer = _.bind(this.getFilePlayer, this);
var showplaybutton = function() {
playButton.show();
pauseButton.hide();
};
pauseButton.click(function() {
var filePlayer = getFilePlayer();
filePlayer.pause();
showplaybutton();
});
playButton.click(function() {
var filePlayer = getFilePlayer();
log(filePlayer);
filePlayer.play(filePlayer.currentFrame);
playButton.hide();
pauseButton.show();
});
restartButton.click(function() {
var filePlayer = getFilePlayer();
showplaybutton();
filePlayer.stop();
});
playButton.click();
$("#timeshift")
.on("change", function(e) {
var filePlayer = getFilePlayer();
filePlayer.pause();
showplaybutton();
filePlayer.setFrame($(this)
.val());
});
if (filePlayer) {
this.setFilePlayer(filePlayer);
}
},
getFilePlayer: function() {
return this._filePlayer || {
play: function() {},
pause: function() {},
stop: function() {},
getLength: function() {
return 0;
},
setFrame: function() {},
currentFrame: 0
};
},
setFilePlayer: function(filePlayer) {
this._filePlayer = filePlayer;
log("here", filePlayer);
var player = this.getFilePlayer();
$("#file-player")
.toggleClass("image", player.isImage);
$("#timeshift")
.attr("max", player.getLength());
filePlayer.ontick = function() {
$("#timeshift")
.val(player.currentFrame);
};
var playButton = this.playButton;
var pauseButton = this.pauseButton;
filePlayer.onfinish = function() {
if (FilePlayerView.loop && filePlayer.getLength() > 2) {
filePlayer.play();
} else {
playButton.show();
pauseButton.hide();
}
};
if (FilePlayerView.autoPlay) {
playButton.click();
}
}
};
(function(file) {
if (!file) {
return;
}
var player = $("#player")[0];
var fileObj = new File(file.id, file.frames, player);
new FilePlayer(fileObj, player, function(filePlayer) {
FilePlayerView.init(filePlayer);
filePlayer.play();
});
$('.share')
.html(generateShareLinks("http://comorichweb.nko3.jit.su/view/" + file.lookup, "Check out the sweet asciigram I created!!"));
})(window.LOADEDFILE);
var FrameBuffer = {
_frames: [],
currentSize: 0,
FPS: 15,
MAX: 50,
set: function(content) {
FrameBuffer.clear();
FrameBuffer.add(content);
},
add: function(content) {
var now = Date.now();
if (FrameBuffer._frames.length) {
var lastTime = FrameBuffer._frames[FrameBuffer._frames.length - 1].timestamp;
var ms = now - lastTime;
if (ms < (1000 / FrameBuffer.FPS)) {
return;
}
}
if (FrameBuffer._frames.length >= FrameBuffer.MAX) {
FrameBuffer._frames.shift();
}
FrameBuffer._frames.push({
content: content,
timestamp: now
});
if (window.DEVELOPMENT) {
$("#num-frames")
.text(FrameBuffer._frames.length);
var size = FrameBuffer.getFullSize();
$("#size-frames")
.text(util.prettyFileSize(size));
}
},
getFrameSize: function(frame) {
return util.stringToBytes(frame.content);
},
getFullSize: function() {
var size = 0;
var fullStr = _.each(FrameBuffer._frames, function(f) {
size += FrameBuffer.getFrameSize(f);
});
return size;
},
clear: function() {
FrameBuffer._frames = [];
FrameBuffer.currentSize = 0;
},
get: function() {
return FrameBuffer._frames;
}
};
if (window.APP) {
var App = new AppView({
el: $("body")
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment